小程序之蓝牙的使用
初始化藍(lán)牙
使用藍(lán)牙之前,首先要先初始化藍(lán)牙(openBluetoothAdapter),之后才能調(diào)用藍(lán)牙的各種api。初始化狀態(tài)分為兩種: 初始化成功:這時(shí)可以去搜索藍(lán)牙設(shè)備(startBluetoothDevicesDiscovery)。 初始化失敗:這個(gè)時(shí)候需要提示用戶打開藍(lán)牙,同時(shí)監(jiān)聽藍(lán)牙的狀態(tài)(onBluetoothAdapterStateChange),當(dāng)藍(lán)牙打開時(shí),去搜索設(shè)備。
openBluetoothAdapter() {const that = thiswx.openBluetoothAdapter({success: (res) => {console.log('openBluetoothAdapter success', res)// 初始化成功,去搜索設(shè)備this.startBluetoothDevicesDiscovery()},fail: (res) => {if (res.errCode === 10001) {// 藍(lán)牙未打開,監(jiān)聽藍(lán)牙狀態(tài)wx.onBluetoothAdapterStateChange(function (res) {console.log('onBluetoothAdapterStateChange', res)if (res.available) {that.startBluetoothDevicesDiscovery()}})}}})} 復(fù)制代碼搜索藍(lán)牙設(shè)備
開始搜索附近的藍(lán)牙設(shè)備(startBluetoothDevicesDiscovery),該操作比較耗費(fèi)資源,建議在連接到藍(lán)牙設(shè)備后,手動(dòng)停止搜索。
startBluetoothDevicesDiscovery() {if (this._discoveryStarted) {return}this._discoveryStarted = true// 開始搜索藍(lán)牙設(shè)備,allowDuplicatesKey,會(huì)重復(fù)搜索同一設(shè)備wx.startBluetoothDevicesDiscovery({allowDuplicatesKey: true,success: (res) => {console.log('startBluetoothDevicesDiscovery success', res)this.onBluetoothDeviceFound()},})} 復(fù)制代碼獲取藍(lán)牙設(shè)備
獲取藍(lán)牙設(shè)備有兩個(gè)api。
- onBluetoothDeviceFound:獲取新發(fā)現(xiàn)的設(shè)備,將startBluetoothDevicesDiscovery中的allowDuplicatesKey設(shè)置為true時(shí),該方法重復(fù)上報(bào)同一藍(lán)牙設(shè)備。
- getBluetoothDevices:獲取已經(jīng)發(fā)現(xiàn)的藍(lán)牙設(shè)備列表,該方法獲取的藍(lán)牙設(shè)備數(shù)量跟搜索時(shí)間有關(guān)系,一般在開始搜索藍(lán)牙設(shè)備后,延時(shí)一段時(shí)間在調(diào)用該方法。
連接藍(lán)牙設(shè)備
createBLEConnection:連接藍(lán)牙設(shè)備,基本上到這,藍(lán)牙設(shè)備就連接上了。為了避免一個(gè)設(shè)備多個(gè)連接實(shí)例,一般和closeBLEConnection成對調(diào)用。在連接成功后,一般需要調(diào)用stopBluetoothDevicesDiscovery,停止藍(lán)牙的搜索。
createBLEConnection(e) {const ds = e.currentTarget.datasetconst deviceId = ds.deviceIdconst name = ds.name// 開始連接藍(lán)牙設(shè)備wx.createBLEConnection({deviceId,success: (res) => {this.setData({connected: true,name,deviceId,})this.getBLEDeviceServices(deviceId)}})// 在連接藍(lán)牙設(shè)備后,停止搜索藍(lán)牙。this.stopBluetoothDevicesDiscovery()} 復(fù)制代碼停止搜索藍(lán)牙設(shè)備
stopBluetoothDevicesDiscovery: 在藍(lán)牙設(shè)備連接成功后,需要停止搜索藍(lán)牙設(shè)備。
stopBluetoothDevicesDiscovery() {wx.stopBluetoothDevicesDiscovery()} 復(fù)制代碼監(jiān)聽藍(lán)牙設(shè)備的連接狀態(tài)
onBLEConnectionStateChange:監(jiān)聽藍(lán)牙設(shè)備的連接狀態(tài),包括藍(lán)牙設(shè)備的丟失,斷開,可以在該方法中進(jìn)行處理這些連接后發(fā)生的異常情況。
wx.onBLEConnectionStateChange(function (res) {// 該方法回調(diào)中可以用于處理連接意外斷開等異常情況console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`) }) 復(fù)制代碼獲取藍(lán)牙設(shè)備服務(wù)
在連接上藍(lán)牙設(shè)備后,我們想要的還是跟藍(lán)牙進(jìn)行通信,或讀取藍(lán)牙設(shè)備的數(shù)據(jù),或?qū)憯?shù)據(jù)到藍(lán)牙設(shè)備。首先需要獲取藍(lán)牙設(shè)備的服務(wù)信息。
getBLEDeviceServices(deviceId) {// 獲取藍(lán)牙設(shè)備的服務(wù)信息。wx.getBLEDeviceServices({deviceId,success: (res) => {for (let i = 0; i < res.services.length; i++) {if (res.services[i].isPrimary) {// 獲取藍(lán)牙設(shè)備的特征值this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)return}}}})} 復(fù)制代碼獲取藍(lán)牙設(shè)備的特征值
getBLEDeviceCharacteristics:根據(jù)藍(lán)牙的服務(wù)信息,獲取可以跟藍(lán)牙進(jìn)行通信的特征值。一般使用notify或indicate為true、read或write為true的特征值。
啟用藍(lán)牙設(shè)備的通知功能
notifyBLECharacteristicValueChange: 啟用藍(lán)牙設(shè)備的通知功能,該方法需要藍(lán)牙設(shè)備的特征值 notify 或 indicate 為 true。只有在在藍(lán)牙設(shè)備啟用該功能,才能監(jiān)聽到藍(lán)牙設(shè)備的數(shù)據(jù)變化。
獲取藍(lán)牙設(shè)備的數(shù)據(jù)
onBLECharacteristicValueChange:監(jiān)聽藍(lán)牙設(shè)備的數(shù)據(jù)變化,當(dāng)藍(lán)牙設(shè)備的數(shù)據(jù)變化時(shí),可以獲取相應(yīng)變化后的數(shù)據(jù)。需要在啟用藍(lán)牙設(shè)備的通知功能后才能使用。
寫數(shù)據(jù)到藍(lán)牙設(shè)備
writeBLECharacteristicValue:寫數(shù)據(jù)到藍(lán)牙設(shè)備,需要特征值的write為true。
// 獲取藍(lán)牙設(shè)備的特征值getBLEDeviceCharacteristics(deviceId, serviceId) {wx.getBLEDeviceCharacteristics({deviceId,serviceId,success: (res) => {console.log('getBLEDeviceCharacteristics success', res.characteristics)for (let i = 0; i < res.characteristics.length; i++) {let item = res.characteristics[i]if (item.properties.read) {// 讀取藍(lán)牙設(shè)備的數(shù)據(jù)wx.readBLECharacteristicValue({deviceId,serviceId,characteristicId: item.uuid,})}if (item.properties.write) {this.setData({canWrite: true})this._deviceId = deviceIdthis._serviceId = serviceIdthis._characteristicId = item.uuid// 寫數(shù)據(jù)到藍(lán)牙設(shè)備this.writeBLECharacteristicValue()}if (item.properties.notify || item.properties.indicate) {// 啟用藍(lán)牙設(shè)備的通知功能,之后才能監(jiān)聽到藍(lán)牙數(shù)據(jù)的變化wx.notifyBLECharacteristicValueChange({deviceId,serviceId,characteristicId: item.uuid,state: true,})}}},fail(res) {console.error('getBLEDeviceCharacteristics', res)}})// 監(jiān)聽藍(lán)牙設(shè)備的數(shù)據(jù)變化wx.onBLECharacteristicValueChange((characteristic) => {const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)const data = {}if (idx === -1) {data[`chs[${this.data.chs.length}]`] = {uuid: characteristic.characteristicId,value: ab2hex(characteristic.value)}} else {data[`chs[${idx}]`] = {uuid: characteristic.characteristicId,value: ab2hex(characteristic.value)}}this.setData(data)})}// 寫數(shù)據(jù)到藍(lán)牙設(shè)備writeBLECharacteristicValue() {// 向藍(lán)牙設(shè)備發(fā)送一個(gè)0x00的16進(jìn)制數(shù)據(jù)let buffer = new ArrayBuffer(1)let dataView = new DataView(buffer)dataView.setUint8(0, Math.random() * 255 | 0)wx.writeBLECharacteristicValue({deviceId: this._deviceId,serviceId: this._serviceId,characteristicId: this._characteristicId,value: buffer,})} 復(fù)制代碼斷開藍(lán)牙設(shè)備的連接
closeBLEConnection:斷開與藍(lán)牙設(shè)備的連接
closeBLEConnection() {// 斷開藍(lán)牙設(shè)備的連接wx.closeBLEConnection({deviceId: this.data.deviceId})this.setData({connected: false,chs: [],canWrite: false,})} 復(fù)制代碼關(guān)閉藍(lán)牙模塊
closeBluetoothAdapter: 當(dāng)藍(lán)牙使用完成后,關(guān)閉藍(lán)牙模塊,釋放系統(tǒng)資源。
// 關(guān)閉藍(lán)牙模塊 wx.closeBluetoothAdapter({success(res) {console.log(res)} }) 復(fù)制代碼總結(jié)
- 上一篇: LeetCode每日一题: 最后一个单
- 下一篇: java B2B2C Springclo