state = { scanning: false, }
initDevInfo = ()=>{ BleManager.enableBluetooth() .then(() => { console.log('开启成功'); }) .catch((error) => { console.log('The user refuse to enable bluetooth'); }); BleManager.start({ showAlert: false }).then(() => { console.log('开始了') }); this.onCheckLocation();
this.handlerDiscover = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral); this.handlerStop = bleManagerEmitter.addListener('BleManagerStopScan', this.handleStopScan); } onCheckLocation =()=>{ if(Platform.OS === 'ios'){ return false; } const granted =PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION)
granted.then((data)=>{ if(!data){ this.requestLocationPermission() } }).catch((err)=>{ console.log('err---------',err.toString()) }) } async requestLocationPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION, { 'title': '是否允许地址查询权限', 'message': '此权限会造成系统异常,请允许', buttonNeutral: '等会再问我', buttonNegative: '不行', buttonPositive: '好的', } )
if (granted === PermissionsAndroid.RESULTS.GRANTED) { showMsg("你已获取了定位权限") } else { showMsg("获取定位权限失败,会造成系统异常") } } catch (err) { showMsg(err.toString()) } }
compomentDidMount(){ this.initDevInfo() this.startScan() } handleStopScan = () => { console.log('停止扫描') }
handleDiscoverPeripheral = (peripheral) => { const {record:{mqttData,realHeartData},dispatch } = this.props; console.log('扫描到的外围设备---', peripheral); let devName = peripheral.name
if (mqttData.deviceCode == peripheral.name) { let before = peripheral.advertising.serviceUUIDs[1].replace(/-/g, "");
let type1 = before.substr(16, 2); let type2 = before.substr(24, 2); let analysis = { "id": before.substr(0, 10), "battery": parseInt(before.substr(14, 2), 16), "heartRate": type1 === "31" ? parseInt(before.substr(18, 6), 16) : null, "stepCount": type2 === "32" ? parseInt(before.substr(26, 6), 16) : null }; console.log(analysis,'analysis') if(analysis.heartRate !=null && analysis.heartRate>0) { mqttData.sportData.tmp.push({ time: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), heart: analysis.heartRate, steps: analysis.stepCount || 0 })
realHeartData.push({ time: new Date().getTime(), value: analysis.heartRate }) }
dispatch({ type: 'record/save', payload: { mqttData, realHeartData } }) } }
startScan = ()=>{ if(bleScanTimer) clearInterval(bleScanTimer);
bleScanTimer = setInterval(()=>{ BleManager.scan(["180d"], 8, false, { "scanMode": 2, "numberOfMatches": 3 }).then((results) => { console.log('开始扫描') if(!this.state.scanning) { this.setState({ scanning: true }); } }); }, timerHeartInterval) } stopScan = ()=>{ if(bleScanTimer) clearInterval(bleScanTimer); this.setState({ scanning: false }); }
|