Skip to content

蓝牙通信

MootingAPP 的蓝牙设备连接说明。

连接流程

┌─────────────────────────────────────────────────────────────┐
│                      蓝牙连接流程                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 请求权限 ──→ 2. 扫描设备 ──→ 3. 选择设备               │
│                                       │                     │
│                                       ▼                     │
│                               4. 建立连接                   │
│                                       │                     │
│                                       ▼                     │
│                               5. 设备配对                   │
│                                       │                     │
│                                       ▼                     │
│                               6. 连接成功                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

权限请求

Android

javascript
import { PermissionsAndroid, Platform } from 'react-native';

const requestBluetoothPermission = async () => {
  if (Platform.OS === 'android') {
    const granted = await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
      PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    ]);
    return Object.values(granted).every(
      (status) => status === PermissionsAndroid.RESULTS.GRANTED
    );
  }
  return true;
};

设备扫描

BluetoothScanScreen

jsx
const BluetoothScanScreen = ({ onConnect }) => {
  const [devices, setDevices] = useState([
    { id: '1', name: 'Mooting G1', mac: 'AA:BB:CC:DD:EE:FF' },
  ]);

  const handleConnect = (device) => {
    // 调用连接
    onConnect(device);
  };

  return (
    <FlatList
      data={devices}
      renderItem={({ item }) => (
        <TouchableOpacity onPress={() => handleConnect(item)}>
          <Text>{item.name}</Text>
          <Text>{item.mac}</Text>
        </TouchableOpacity>
      )}
    />
  );
};

连接管理

使用 AppContext

jsx
const { connectDevice, disconnectDevice, isConnected } = useAppContext();

// 连接
const handleConnect = (device) => {
  connectDevice(device);
};

// 断开
const handleDisconnect = () => {
  disconnectDevice();
};

状态显示

HomeHeader 中的连接状态

jsx
const HomeHeader = () => {
  const { isConnected, deviceInfo } = useAppContext();

  return (
    <View>
      {isConnected ? (
        <View>
          <Text>{deviceInfo.name}</Text>
          <Text>已连接</Text>
        </View>
      ) : (
        <TouchableOpacity onPress={onAddDevice}>
          <Text>添加设备</Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

未来计划

当前实现为 UI 框架,实际 BLE 通信需要集成:

  • react-native-ble-plx - BLE 通信库
  • Android Native Module - 原生蓝牙 API
  • 参考 Android SDK - Mooting_android_demo 中的 BluetoothModule

Mooting 开发者文档