微信小程序:蓝牙通讯,搜索、发送与接收
生活随笔
收集整理的這篇文章主要介紹了
微信小程序:蓝牙通讯,搜索、发送与接收
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求背景
使用微信小程序,通過藍牙與硬件設備產品進行交互
參考文檔
微信小程序藍牙通訊
開始
1.初始化藍牙
initBlue: function () {var that = thiswx.openBluetoothAdapter({success: function (res) {that.findBlue()},fail: function (res) {wx.showToast({title: '請打開手機藍牙!',icon: 'none',duration: 2000})}})}2.查找藍牙
findBlue() {var that = thiswx.startBluetoothDevicesDiscovery({allowDuplicatesKey: false,interval: 0,success: function (res) {that.getBlue()}})},getBlue() {var that = thisvar searchResult = falsevar index = 0wx.showLoading({title: '搜索設備...',})//定時搜索var interval = setInterval(function () {wx.getBluetoothDevices({success: function (res) {index = index + 1if (!searchResult) {for (var i = 0; i < res.devices.length; i++) {//根據設備名稱匹配 這里的meterId是需要匹配的設備名稱if ((res.devices[i].name + "").substr(0, 16) == that.data.meterId ||(res.devices[i].localName + "").substr(0, 16) == that.data.meterId) {that.setData({//獲取藍牙設備的deviceIddeviceId: res.devices[i].deviceId,})searchResult = trueif (searchResult) {clearInterval(interval)}//連接藍牙that.connetBlue(res.devices[i].deviceId)return}}}if (index > 20) {clearInterval(interval)wx.hideLoading()wx.showToast({title: '未找到設備,請重試!',icon: 'none',duration: 2000})wx.stopBluetoothDevicesDiscovery() //關閉藍牙搜索}}})}, 500)}3.連接藍牙設備
connetBlue(deviceId) {var that = thiswx.hideLoading()wx.showLoading({title: '連接設備...',})wx.createBLEConnection({deviceId: deviceId,success: function (res) {wx.stopBluetoothDevicesDiscovery() //關閉藍牙搜索that.getServiceId() //獲取服務ID},fail: function () {wx.hideLoading()wx.showToast({title: '連接設備失敗!',icon: 'none',duration: 2000})wx.stopBluetoothDevicesDiscovery() //關閉藍牙搜索}})},getServiceId() {var that = thiswx.getBLEDeviceServices({deviceId: that.data.deviceId,success: function (res) {var model = res.services[0]that.setData({serviceId: model.uuid})that.getCharacteId()}})},getCharacteId() {var that = thiswx.getBLEDeviceCharacteristics({deviceId: that.data.deviceId,serviceId: that.data.serviceId,success: function (res) {for (var i = 0; i < res.characteristics.length; i++) {var model = res.characteristics[i]if (model.properties.notify == true) {that.setData({notifyId: model.uuid})//重點:開啟監聽服務。監聽設備數據變化that.startNotice(model.uuid)}if (model.properties.write == true) {that.setData({writeId: model.uuid})}}//有可寫權限if (that.data.writeId != '') {wx.hideLoading()wx.showLoading({title: '通訊中...',})//這里可以完成需要下發到設備上的指令的生成that.sendCmd(value)} else {wx.showToast({title: '失敗: 設備無寫入權限!',icon: 'none',duration: 2000})}}})}4.發送數據
sendCmd(cmdValue) {var that = thisif (cmdValue != '' && cmdValue != null && cmdValue != undefined) {that.writeCharacterToDevice(util.stringToArrayBuffer(cmdValue))} else {wx.showToast({title: '獲取設備指令失敗',icon: 'none',duration: 2000})}}writeCharacterToDevice(buffer) {var that = thiswx.writeBLECharacteristicValue({deviceId: that.data.deviceId,serviceId: that.data.serviceId,characteristicId: that.data.writeId,value: buffer,fail: function () {wx.showToast({title: '寫入設備數據失敗!',icon: 'none',duration: 2000})},success: function () {wx.showLoading({title: '指令發送成功',duration: 2000})}})}5.工具函數
function stringToArrayBuffer(str) {var bytes = new Array();var len, c;len = str.length;for (var i = 0; i < len; i++) {c = str.charCodeAt(i);if (c >= 0x010000 && c <= 0x10FFFF) {bytes.push(((c >> 18) & 0x07) | 0xF0);bytes.push(((c >> 12) & 0x3F) | 0x80);bytes.push(((c >> 6) & 0x3F) | 0x80);bytes.push((c & 0x3F) | 0x80);} else if (c >= 0x000800 && c <= 0x00FFFF) {bytes.push(((c >> 12) & 0x0F) | 0xE0);bytes.push(((c >> 6) & 0x3F) | 0x80);bytes.push((c & 0x3F) | 0x80);} else if (c >= 0x000080 && c <= 0x0007FF) {bytes.push(((c >> 6) & 0x1F) | 0xC0);bytes.push((c & 0x3F) | 0x80);} else {bytes.push(c & 0xFF);}}var array = new Int8Array(bytes.length);for (var i in bytes) {array[i] = bytes[i];}return array.buffer; }function arrayBufferToString(arr) {if (typeof arr === 'string') {return arr;}var dataview = new DataView(arr);var ints = new Uint8Array(arr.byteLength);for (var i = 0; i < ints.length; i++) {ints[i] = dataview.getUint8(i);}arr = ints;var str = '',_arr = arr;for (var i = 0; i < _arr.length; i++) {var one = _arr[i].toString(2),v = one.match(/^1+?(?=0)/);if (v && one.length == 8) {var bytesLength = v[0].length;var store = _arr[i].toString(2).slice(7 - bytesLength);for (var st = 1; st < bytesLength; st++) {store += _arr[st + i].toString(2).slice(2);}str += String.fromCharCode(parseInt(store, 2));i += bytesLength - 1;} else {str += String.fromCharCode(_arr[i]);}}return str; }6.開啟事件監聽
/*** 監聽水表數據變化* @param {水表ID} uuid */startNotice(uuid) {var that = thiswx.notifyBLECharacteristicValueChange({state: true, // 啟用 notify 功能deviceId: that.data.deviceId,serviceId: that.data.serviceId,characteristicId: uuid,success: function (res) {var deviceResult = ''//特征數據變化wx.onBLECharacteristicValueChange(function (res) {deviceResult = deviceResult + util.arrayBufferToString(res.value) //應答數據比較長,會觸發多次//如果應答幀總長度大于數據包長度,并且包含“16”,則說明是完整的應答幀if (deviceResult.lastIndexOf('16') >= (deviceResult.length - 8) && deviceResult.indexOf('68') >= 0) {//解析應答幀 這里開始對設備應答數據進行處理了deviceResult = ''}})}})},設備應答數據也可以發送到后臺服務進行處理,根據具體業務而定
總結
以上是生活随笔為你收集整理的微信小程序:蓝牙通讯,搜索、发送与接收的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 友达光电(昆山)第六代LTPS液晶面板厂
- 下一篇: php 401认证,给phpMyAdmi