中文字幕理论片,69视频免费在线观看,亚洲成人app,国产1级毛片,刘涛最大尺度戏视频,欧美亚洲美女视频,2021韩国美女仙女屋vip视频

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費(fèi)電子書(shū)等14項(xiàng)超值服

開(kāi)通VIP
微信小程序藍(lán)牙API使用詳解,完整版

本文作者:IMWeb dujingya 原文出處:IMWeb社區(qū) 

github地址:https://github.com/dujingya/blueDevice/blob/master/blueDevice.md

使用mpvue 開(kāi)發(fā)小程序過(guò)程中 簡(jiǎn)單介紹一下微信小程序藍(lán)牙連接過(guò)程

在藍(lán)牙連接的過(guò)程中部分api需要加定時(shí)器延時(shí)1秒到2秒左右再執(zhí)行,原因?yàn)楹尾恢?,小程序有這樣的要求

1.首先是要初始化藍(lán)牙:openBluetoothAdapter()

if (wx.openBluetoothAdapter) { wx.openBluetoothAdapter({ success: function(res) { /* 獲取本機(jī)的藍(lán)牙狀態(tài) */ setTimeout(() => { getBluetoothAdapterState() }, 1000) }, fail: function(err) { // 初始化失敗 } })} else {}

2.檢測(cè)本機(jī)藍(lán)牙是否可用:

要在上述的初始化藍(lán)牙成功之后回調(diào)里調(diào)用

getBluetoothAdapterState() {    var that = this;    that.toastTitle = '檢查藍(lán)牙狀態(tài)'    wx.getBluetoothAdapterState({        success: function(res) {           startBluetoothDevicesDiscovery()        },        fail(res) {            console.log(res)        }    })}

3. 開(kāi)始搜索藍(lán)牙設(shè)備:

startBluetoothDevicesDiscovery() { var that = this; setTimeout(() => { wx.startBluetoothDevicesDiscovery({ success: function(res) { /* 獲取藍(lán)牙設(shè)備列表 */ that.getBluetoothDevices() }, fail(res) { } }) }, 1000)}

4. 獲取搜索到的藍(lán)牙設(shè)備列表

/ that.deviceName 是獲取到的藍(lán)牙設(shè)備的名稱, 因?yàn)樗{(lán)牙設(shè)備在安卓和蘋(píng)果手機(jī)上搜到的藍(lán)牙地址顯示是不一樣的,所以根據(jù)設(shè)備名稱匹配藍(lán)牙/

getBluetoothDevices() {    var that = this;    setTimeout(() => {        wx.getBluetoothDevices({            services: [],            allowDuplicatesKey: false,            interval: 0,            success: function(res) {                if (res.devices.length > 0) {                    if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {                        for (let i = 0; i < res.devices.length; i++) {                            if (that.deviceName === res.devices[i].name) {                                /* 根據(jù)指定的藍(lán)牙設(shè)備名稱匹配到deviceId */                                that.deviceId = that.devices[i].deviceId;                                setTimeout(() => {                                    that.connectTO();                                }, 2000);                            };                        };                    } else {                    }                } else {                }            },            fail(res) {                console.log(res, '獲取藍(lán)牙設(shè)備列表失敗=====')            }        })    }, 2000)},

5.連接藍(lán)牙

匹配到的藍(lán)牙設(shè)備ID 發(fā)送連接藍(lán)牙的請(qǐng)求, 連接成功之后 應(yīng)該斷開(kāi)藍(lán)牙搜索的api,然后去獲取所連接藍(lán)牙設(shè)備的service服務(wù)

connectTO() { wx.createBLEConnection({ deviceId: deviceId, success: function(res) { that.connectedDeviceId = deviceId; /* 4.獲取連接設(shè)備的service服務(wù) */ that.getBLEDeviceServices(); wx.stopBluetoothDevicesDiscovery({ success: function(res) { console.log(res, '停止搜索') }, fail(res) { } }) }, fail: function(res) { } })}

6. 獲取藍(lán)牙設(shè)備的service服務(wù),獲取的serviceId有多個(gè)要試著連接最終確定哪個(gè)是穩(wěn)定版本的service 獲取服務(wù)完后獲取設(shè)備特征值

getBLEDeviceServices() {    setTimeout(() => {        wx.getBLEDeviceServices({            deviceId: that.connectedDeviceId,            success: function(res) {                that.services = res.services                /* 獲取連接設(shè)備的所有特征值 */                that.getBLEDeviceCharacteristics()            },            fail: (res) => {            }        })    }, 2000)},

7.獲取藍(lán)牙設(shè)備特征值

獲取到的特征值有多個(gè),最后要用的事能讀,能寫(xiě),能監(jiān)聽(tīng)的那個(gè)值的uuid作為特征值id,

getBLEDeviceCharacteristics() { setTimeout(() => { wx.getBLEDeviceCharacteristics({ deviceId: connectedDeviceId, serviceId: services[2].uuid, success: function(res) { for (var i = 0; i < res.characteristics.length; i++) { if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) && (res.characteristics[i].properties.read && res.characteristics[i].properties.write)) { console.log(res.characteristics[i].uuid, '藍(lán)牙特征值 ==========') /* 獲取藍(lán)牙特征值 */ that.notifyCharacteristicsId = res.characteristics[i].uuid // 啟用低功耗藍(lán)牙設(shè)備特征值變化時(shí)的 notify 功能 that.notifyBLECharacteristicValueChange() } } }, fail: function(res) { } }) }, 1000) },

8.啟動(dòng)notify 藍(lán)牙監(jiān)聽(tīng)功能 然后使用 wx.onBLECharacteristicValueChange用來(lái)監(jiān)聽(tīng)藍(lán)牙設(shè)備傳遞數(shù)據(jù)

接收到的數(shù)據(jù)和發(fā)送的數(shù)據(jù)必須是二級(jí)制數(shù)據(jù), 頁(yè)面展示的時(shí)候需要進(jìn)行轉(zhuǎn)換

        notifyBLECharacteristicValueChange() { // 啟用低功耗藍(lán)牙設(shè)備特征值變化時(shí)的 notify 功能            var that = this;            console.log('6.啟用低功耗藍(lán)牙設(shè)備特征值變化時(shí)的 notify 功能')            wx.notifyBLECharacteristicValueChange({                state: true,                deviceId: that.connectedDeviceId,                serviceId: that.notifyServicweId,                characteristicId: that.notifyCharacteristicsId,                complete(res) {                    /*用來(lái)監(jiān)聽(tīng)手機(jī)藍(lán)牙設(shè)備的數(shù)據(jù)變化*/                    wx.onBLECharacteristicValueChange(function(res) {                        /**/                        that.balanceData += that.buf2string(res.value)                        that.hexstr += that.receiveData(res.value)                    })                },                fail(res) {                    console.log(res, '啟用低功耗藍(lán)牙設(shè)備監(jiān)聽(tīng)失敗')                    that.measuringTip(res)                }            })        },        /*轉(zhuǎn)換成需要的格式*/         buf2string(buffer) {                    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)                    return arr.map((char, i) => {                        return String.fromCharCode(char);                    }).join('');        },          receiveData(buf) {                    return this.hexCharCodeToStr(this.ab2hex(buf))          },          /*轉(zhuǎn)成二進(jìn)制*/           ab2hex (buffer) {              var hexArr = Array.prototype.map.call(                  new Uint8Array(buffer), function (bit) {                      return ('00' + bit.toString(16)).slice(-2)                  }              )              return hexArr.join('')          },          /*轉(zhuǎn)成可展會(huì)的文字*/          hexCharCodeToStr(hexCharCodeStr) {              var trimedStr = hexCharCodeStr.trim();              var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;              var len = rawStr.length;              var curCharCode;              var resultStr = [];              for (var i = 0; i < len; i = i + 2) {                  curCharCode = parseInt(rawStr.substr(i, 2), 16);                  resultStr.push(String.fromCharCode(curCharCode));              }              return resultStr.join('');          },

向藍(lán)牙設(shè)備發(fā)送數(shù)據(jù)

sendData(str) { let that = this; let dataBuffer = new ArrayBuffer(str.length) let dataView = new DataView(dataBuffer) for (var i = 0; i < str.length; i++) { dataView.setUint8(i, str.charAt(i).charCodeAt()) } let dataHex = that.ab2hex(dataBuffer); this.writeDatas = that.hexCharCodeToStr(dataHex); wx.writeBLECharacteristicValue({ deviceId: that.connectedDeviceId, serviceId: that.notifyServicweId, characteristicId: that.notifyCharacteristicsId, value: dataBuffer, success: function (res) { console.log('發(fā)送的數(shù)據(jù):' + that.writeDatas) console.log('message發(fā)送成功') }, fail: function (res) { }, complete: function (res) { } }) },

當(dāng)不需要連接藍(lán)牙了后就要關(guān)閉藍(lán)牙,并關(guān)閉藍(lán)牙模塊

 // 斷開(kāi)設(shè)備連接closeConnect() {    if (that.connectedDeviceId) {        wx.closeBLEConnection({            deviceId: that.connectedDeviceId,            success: function(res) {                that.closeBluetoothAdapter()            },            fail(res) {            }        })    } else {        that.closeBluetoothAdapter()    }},// 關(guān)閉藍(lán)牙模塊closeBluetoothAdapter() {    wx.closeBluetoothAdapter({        success: function(res) {        },        fail: function(err) {        }    })},

在向藍(lán)牙設(shè)備傳遞數(shù)據(jù)和接收數(shù)據(jù)的過(guò)程中,并未使用到read的API 不知道有沒(méi)有潛在的問(wèn)題,目前線上運(yùn)行為發(fā)現(xiàn)任何的問(wèn)題

今天的藍(lán)牙使用心得到此結(jié)束,謝謝

本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)
打開(kāi)APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
微信小程序|API掃碼及藍(lán)牙的使用
小程序背景音樂(lè)
從ESP32 BLE應(yīng)用理解GATT
iOS藍(lán)牙知識(shí)快速入門(mén)(詳盡版)
小米手環(huán)iOS開(kāi)發(fā)實(shí)戰(zhàn)(一):iOS藍(lán)牙框架CoreBluetooth
uni-app調(diào)用wifi接口
更多類似文章 >>
生活服務(wù)
熱點(diǎn)新聞
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服