首页
/ React Native Windows 中实现 BLE 通信的 C++ 原生模块开发指南

React Native Windows 中实现 BLE 通信的 C++ 原生模块开发指南

2025-05-13 19:27:53作者:吴年前Myrtle

在 React Native Windows 项目中,开发者经常需要实现与蓝牙低功耗(BLE)设备的通信功能。本文将详细介绍如何正确开发 C++ 原生模块来实现这一功能,并解决常见的模块注册和调用问题。

核心问题分析

在 React Native Windows 0.75.13 版本中,开发者尝试通过 C++ 原生模块实现 BLE 功能时,遇到了模块注册和构建错误。主要问题包括:

  1. 模块构造函数定义不当
  2. 方法缺少 noexcept 修饰符
  3. 模块注册方式不正确
  4. JavaScript 端调用方式错误

正确的 C++ 原生模块实现

模块头文件定义

#pragma once
#include "NativeModules.h"
#include <winrt/Windows.Devices.Bluetooth.h>
#include <winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h>
#include <winrt/Windows.Devices.Enumeration.h>

namespace winrt::SampleApp::implementation {

REACT_MODULE(BleModule)
struct BleModule {
    REACT_INIT(Initialize)
    void Initialize(winrt::Microsoft::ReactNative::IReactContext const& reactContext) noexcept {
        m_reactContext = reactContext;
    }

    REACT_METHOD(StartScan)
    void StartScan() noexcept;

    REACT_METHOD(ConnectToDevice)
    void ConnectToDevice(std::string deviceId) noexcept;

private:
    winrt::Microsoft::ReactNative::IReactContext m_reactContext{ nullptr };
};

}

模块实现文件

#include "pch.h"
#include "BleModule.h"

using namespace winrt;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Bluetooth;

namespace winrt::SampleApp::implementation {

void BleModule::StartScan() noexcept {
    DeviceWatcher watcher = DeviceInformation::CreateWatcher(
        BluetoothLEDevice::GetDeviceSelector());

    watcher.Added([this](DeviceWatcher sender, DeviceInformation deviceInfo) {
        auto deviceName = deviceInfo.Name().c_str();
        if (m_reactContext) {
            m_reactContext.CallJSFunction(
                L"RCTDeviceEventEmitter", L"emit", L"onDeviceFound", deviceName);
        }
    });

    watcher.Start();
}

void BleModule::ConnectToDevice(std::string deviceId) noexcept {
    auto asyncOp = BluetoothLEDevice::FromIdAsync(winrt::to_hstring(deviceId));
    asyncOp.Completed([this](auto const& asyncInfo, auto const& status) {
        if (status == Windows::Foundation::AsyncStatus::Completed) {
            auto device = asyncInfo.GetResults();
            if (device && m_reactContext) {
                m_reactContext.CallJSFunction(
                    L"RCTDeviceEventEmitter", L"emit", L"onDeviceConnected", device.Name().c_str());
            }
        }
    });
}

}

模块注册

在 ReactPackageProvider.cpp 中,只需保留以下内容:

void ReactPackageProvider::CreatePackage(IReactPackageBuilder const &packageBuilder) noexcept
{
    AddAttributedModules(packageBuilder, true);
}

JavaScript 端调用

正确调用原生模块的方式如下:

import { TurboModuleRegistry } from 'react-native';

const BleModule = TurboModuleRegistry.get('BleModule');

const BluetoothScanner = () => {
  const scanDevices = async () => {
    if (BleModule) {
      BleModule.StartScan(); 
    } else {
      console.error('BleModule is not available');
    }
  };

  return (
    <View>
      <Button title="Start Scanning" onPress={() => scanDevices()} />
    </View>
  );
};

关键注意事项

  1. 构造函数处理:使用 REACT_INIT 宏来接收 ReactContext,而不是定义额外的构造函数。

  2. 异常处理:所有 REACT_METHOD 方法必须标记为 noexcept,这是 React Native Windows 的要求。

  3. 模块注册:使用 AddAttributedModules 自动注册所有带有 REACT_MODULE 属性的模块,无需手动添加。

  4. JavaScript 调用:确保使用正确的模块名称调用 TurboModuleRegistry.get()。

  5. 空检查:在 JavaScript 端始终检查模块是否成功加载。

替代方案:C# 实现

虽然本文重点介绍 C++ 实现,但 React Native Windows 也支持使用 C# 开发原生模块。C# 实现通常更简单,语法更友好,适合不熟悉 C++ 的开发者。但 C++ 实现通常性能更好,特别是在需要频繁与底层 API 交互的场景中。

通过遵循上述指南,开发者可以成功在 React Native Windows 应用中实现 BLE 通信功能,并避免常见的模块注册和调用问题。

登录后查看全文
热门项目推荐
相关项目推荐