60/5000与mi-fit app之类的react-native app配对mi band 4

时间:2019-10-28 11:03:46

标签: react-native bluetooth bluetooth-lowenergy react-native-ble-plx

我最近购买了mi band 4,我正在用react-native进行测试,但是我不知道该如何配对设备(如mi fit应用),mi fit应用会将请求发送至手环,并显示一条消息在她的屏幕上。确认并配对。有人可以像mi mi app一样帮我配对手镯吗?我正在使用react-native-ble-plx连接到它。

我正在使用react-native-ble-plx。我可以扫描并找到手镯,也可以连接它并阅读服务,但是当我尝试写东西时,它给了我这样的错误:MAC地址EC上的GATT异常EC:AC:59:E9:80:9F ,类型为BleGattOperation {description ='CHARACTERISTIC_READ'}。 我想这是因为她没有像mi fit那样配对。

//我的代码

import React, {Component} from 'react';
import {
  SafeAreaView, 
  PermissionsAndroid,
  ScrollView, 
  TouchableOpacity, 
  StatusBar,
} from 'react-native';

import {BleManager, Service} from 'react-native-ble-plx'; 

export default class App extends Component {
  constructor() {
    super();
    this.manager = new BleManager();
    this.state = {characteristic: [], info: '', values: {}, array_services: []};

  }



  async setupNotifications(device) {
    for (const id in this.sensors) {
      const service = this.serviceUUID(id);
      const characteristicW = this.writeUUID(id);
      const characteristicN = this.notifyUUID(id);

      const characteristic = await device.writeCharacteristicWithResponseForService(
        service,
        characteristicW,
        'AQ==' /* 0x01 in hex */,
      );

      device.monitorCharacteristicForService(
        service,
        characteristicN,
        (error, characteristic) => {
          if (error) {
            this.error(error.message);
            return;
          }
          this.updateValue(characteristic.uuid, characteristic.value);
        },
      );
    }
  }

  async requestLocationPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
        {
          title: 'Location permission for bluetooth scanning',
          message: 'wahtever',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        return true;
      } else {
        return false;
      }
    } catch (err) {
      return false;
    }
  }

  async _discoveryServices() { 
    const connectedDevice = await this.manager.connectToDevice(
      'EC:AC:59:E9:80:9F',
    );
    const services = await connectedDevice.discoverAllServicesAndCharacteristics();
    const characteristic = await this.getServicesAndCharacteristics(services);

    this.setState({characteristic});
  }

  getServicesAndCharacteristics(device) {
    return new Promise((resolve, reject) => {
      device.services().then(services => {
        const characteristics = [];
        const services_and_characteristics = [];
        services.forEach((service, i) => {
          service.characteristics().then(c => {
            services_and_characteristics.push({...c});


            characteristics.push(c);
            console.log({c});


            if (i === services.length - 1) {
              const temp = characteristics.reduce((acc, current) => {
                return [...acc, ...current];
              }, []);
              const dialog = temp.find(
                characteristic => characteristic.isWritableWithoutResponse,
              );
              if (!dialog) {
                reject('No writable characteristic');
              }
              resolve(services_and_characteristics);
            }
          });
        });
      });
    });
  }

  _read() {
    const characteristic = this.state.characteristic; 
    if (characteristic.length > 0) {
      for (let index = 0; index < 2; index++) { 
        characteristic[3][index]
          .read()
          .then(res => {
            console.log({res}, index, '++++++++++++++++++++++++==');
          })
          .catch(err => {
            console.log({err}, '++++++++++++++++++++++++==');
          });

        if (characteristic[3][index].isWritableWithResponse) {
          let valueBase64 = 'VjAuMjUuMTcuNQ==';
          characteristic[3][index]
            .writeWithResponse(valueBase64)
            .then(res => {
              console.log({res}, index, '++++++++++++++++++++++++==');
            })
            .catch(err => {
              console.log({err}, '++++++++++++++++++++++++==');
            });
        }

        if (characteristic[3][index].isWritableWithoutResponse) {
          let valueBase64 = ' VjAuMjUuMTcuNQ==';
          characteristic[3][index]
            .writeWithoutResponse(valueBase64)
            .then(res => {
              console.log({res}, index, '++++++++++++++++++++++++==');
            })
            .catch(err => {
              console.log({err}, '++++++++++++++++++++++++==');
            });
        }
      }
    }
  }

  render() {
    return (
      <>
          <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView contentInsetAdjustmentBehavior="automatic">
            <TouchableOpacity
              onPress={() => this._discoveryServices()}
              style={{
                height: 50,
                width: 50,
                margin: 5,
                backgroundColor: 'grey',
              }}
            />
            <TouchableOpacity
              onPress={() => this._read()}
              style={{height: 50, width: 50, margin: 5, backgroundColor: 'red'}}
            />
          </ScrollView>
        </SafeAreaView>
      </>
    );
  }
}



// My package-json
{
  "name": "miBand4",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.2",
    "react-native-ble-manager": "^6.6.10",
    "react-native-ble-plx": "^1.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/runtime": "^7.6.3",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

我希望能够像mi fit应用程序那样对设备进行配对并读取和写入数据,但是我没有得到它,并且在尝试这样做时遇到了描述的错误。

0 个答案:

没有答案