Commit a336a7f7 by lirandong

添加 蓝牙通讯功能

parent 940d4592
...@@ -88,6 +88,15 @@ export function onBLECharacteristicValueChange( ...@@ -88,6 +88,15 @@ export function onBLECharacteristicValueChange(
} }
/** /**
* 向低功耗蓝牙设备特征值中写入二进制数据。
* 注意:必须设备的特征值支持`write`才可以成功调用,
* 具体参照 characteristic 的 properties 属性
*/
export function writeBLECharacteristicValue(OBJECT: Taro.writeBLECharacteristicValue.Param) {
return Taro.writeBLECharacteristicValue(OBJECT)
}
/**
* 停止搜寻附近的蓝牙外围设备。 * 停止搜寻附近的蓝牙外围设备。
* 若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。 * 若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
*/ */
...@@ -106,5 +115,6 @@ export const bluetooth = { ...@@ -106,5 +115,6 @@ export const bluetooth = {
readBLECharacteristicValue, readBLECharacteristicValue,
notifyBLECharacteristicValueChange, notifyBLECharacteristicValueChange,
onBLECharacteristicValueChange, onBLECharacteristicValueChange,
writeBLECharacteristicValue,
stopBluetoothDevicesDiscovery stopBluetoothDevicesDiscovery
} }
...@@ -55,3 +55,13 @@ export function ArrayBufferToString(buffer: ArrayBuffer) { ...@@ -55,3 +55,13 @@ export function ArrayBufferToString(buffer: ArrayBuffer) {
}) })
return hexArr.join('') return hexArr.join('')
} }
/** 解析蓝牙接收到的 十六进制 状态 */
export function getBLEState(buffer: ArrayBuffer) {
return new Uint8Array(buffer)[0]
}
/** 解析蓝牙接收到的数据 */
export function getBLEData(buffer: ArrayBuffer): string {
return String.fromCharCode.apply(null, new Uint8Array(buffer.slice(1, buffer.byteLength)))
}
import api from '@/api/index' import api from '@/api/index'
import { ComponentClass } from 'react' import { ComponentClass } from 'react'
import { AtSwipeAction } from 'taro-ui' import { AtSwipeAction } from 'taro-ui'
import { showMyToast, ArrayBufferToString } from '@/common/utils' import { connect } from '@tarojs/redux'
import { bluetooth } from '@/common/adapter'
import ListView from '@/conpoments/list_view'
import Taro, { Component } from '@tarojs/taro' import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import DeviceItem from '@/conpoments/device_item' import DeviceItem from '@/conpoments/device_item'
import { getFilmList } from '@/actions/asyncCounter' import { getFilmList } from '@/actions/asyncCounter'
import { View, Text, ScrollView } from '@tarojs/components'
import { bluetooth } from '@/common/adapter'
import ListView from '@/conpoments/list_view'
import { connect } from '@tarojs/redux'
import { WIFI_CHARACTERISTIC_ID, BLE_SERVICE_ID } from '@/common' import { WIFI_CHARACTERISTIC_ID, BLE_SERVICE_ID } from '@/common'
import { showMyToast, getBLEState, getBLEData } from '@/common/utils'
import './index.scss' import './index.scss'
export interface IDeviceItem { export interface IDeviceItem {
...@@ -25,7 +24,7 @@ export interface IDeviceItem { ...@@ -25,7 +24,7 @@ export interface IDeviceItem {
} }
export interface IBluetoothServerListItem { export interface IBluetoothServerListItem {
deviceId: string serviceId: string
characteristics: Taro.getBLEDeviceCharacteristics.PromisedPropCharacteristics characteristics: Taro.getBLEDeviceCharacteristics.PromisedPropCharacteristics
} }
...@@ -44,11 +43,9 @@ type PageOwnProps = { ...@@ -44,11 +43,9 @@ type PageOwnProps = {
type PageState = { type PageState = {
count: number count: number
deviceId: string
deviceCode: string deviceCode: string
showModal: boolean showModal: boolean
deviceList: IDeviceItem[] deviceList: IDeviceItem[]
bluetoothServerList: IBluetoothServerListItem[]
} }
type IProps = PageStateProps & PageDispatchProps & PageOwnProps type IProps = PageStateProps & PageDispatchProps & PageOwnProps
...@@ -71,15 +68,15 @@ interface MyDevice { ...@@ -71,15 +68,15 @@ interface MyDevice {
) )
class MyDevice extends Component { class MyDevice extends Component {
protected page = 1 protected page = 1
protected deviceId = ''
protected bluetoothServerList: IBluetoothServerListItem[] = []
constructor(props) { constructor(props) {
super(props) super(props)
this.state = { this.state = {
count: 0, count: 0,
deviceId: '',
deviceCode: '', deviceCode: '',
deviceList: [], deviceList: [],
showModal: false, showModal: false
bluetoothServerList: []
} }
this.scanCode = this.scanCode.bind(this) this.scanCode = this.scanCode.bind(this)
this.cancelModal = this.cancelModal.bind(this) this.cancelModal = this.cancelModal.bind(this)
...@@ -178,16 +175,14 @@ class MyDevice extends Component { ...@@ -178,16 +175,14 @@ class MyDevice extends Component {
await bluetooth.createBLEConnection({ deviceId }) await bluetooth.createBLEConnection({ deviceId })
bluetooth.stopBluetoothDevicesDiscovery() bluetooth.stopBluetoothDevicesDiscovery()
showMyToast({ title: '蓝牙连接成功~' }) showMyToast({ title: '蓝牙连接成功~' })
this.setState({ deviceId }) this.deviceId = deviceId
setTimeout(() => {
this.getWiFiList() this.getWiFiList()
}, 0)
} }
/** 获取蓝牙服务列表 */ /** 获取蓝牙服务列表 */
async getBLEDeviceServices() { async getBLEDeviceServices() {
Taro.showLoading({ title: '获取蓝牙参数...' }) Taro.showLoading({ title: '获取蓝牙参数...' })
const { deviceId } = this.state const { deviceId } = this
const { services } = await bluetooth.getBLEDeviceServices({ deviceId }) // 获取服务列表 const { services } = await bluetooth.getBLEDeviceServices({ deviceId }) // 获取服务列表
Taro.showLoading({ title: '获取特征值...' }) Taro.showLoading({ title: '获取特征值...' })
const serveList: Array<Promise<Taro.getBLEDeviceCharacteristics.Promised>> = [] const serveList: Array<Promise<Taro.getBLEDeviceCharacteristics.Promised>> = []
...@@ -200,26 +195,63 @@ class MyDevice extends Component { ...@@ -200,26 +195,63 @@ class MyDevice extends Component {
} }
const serveListRes = await Promise.all(serveList) const serveListRes = await Promise.all(serveList)
const bluetoothServerList = serveListRes.map(i => i.characteristics) serveListRes.forEach(({ characteristics }, index) => {
this.bluetoothServerList.push({
characteristics,
serviceId: services[index].uuid
})
})
Taro.hideLoading() Taro.hideLoading()
this.setState({ bluetoothServerList })
setTimeout(() => {
this.getWiFiList()
}, 0)
} }
async getWiFiList() { async getWiFiList() {
try { try {
const { deviceId } = this.state const { deviceId } = this
// 开启通讯
await bluetooth.notifyBLECharacteristicValueChange({ await bluetooth.notifyBLECharacteristicValueChange({
deviceId, deviceId,
state: true, state: true,
serviceId: BLE_SERVICE_ID, serviceId: BLE_SERVICE_ID,
characteristicId: WIFI_CHARACTERISTIC_ID characteristicId: WIFI_CHARACTERISTIC_ID
}) })
bluetooth.onBLECharacteristicValueChange(({ value }) => {
const str1 = ArrayBufferToString(value) // 来自设备端的通知
console.log({ str1 }) bluetooth.onBLECharacteristicValueChange(async ({ value }) => {
const state = getBLEState(value) // 获取蓝牙状态
let advertisData = ''
let page = 0
// 判断第8位数是否是 1
if ((state & 0x80) !== 0) {
// 第8位数为 1, 设备端发送资源包
// 获取当前页
page = state & 0x3f
// 判断第8位数是否是 1
if ((state & 0x40) !== 0) {
// 新包
advertisData = getBLEData(value)
} else {
// 累加包
advertisData += getBLEData(value)
}
await bluetooth.writeBLECharacteristicValue({
deviceId,
serviceId: BLE_SERVICE_ID,
value: new Uint8Array([page]).buffer,
characteristicId: WIFI_CHARACTERISTIC_ID
})
// console.log({ page })
// console.log(page === 0)
// console.log({ advertisData })
if (page === 0) {
// 数据传输完毕
console.log(JSON.parse(advertisData))
}
} else {
// 第8位数为 0, 普通响应
console.log('第8位数为 0, 普通响应')
}
}) })
} catch (error) { } catch (error) {
console.error(error) console.error(error)
......
...@@ -68,6 +68,7 @@ ...@@ -68,6 +68,7 @@
"curly": false, "curly": false,
"no-unused-expression": false, "no-unused-expression": false,
"no-string-literal": false, "no-string-literal": false,
"object-literal-key-quotes": false "object-literal-key-quotes": false,
"no-bitwise": false
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment