1. 程式人生 > >mpvue開發微信小程式藍芽功能

mpvue開發微信小程式藍芽功能

github地址:https://github.com/dujingya/blueDevice/blob/master/blueDevice.md
@[T#使用mpvue 開發小程式過程中 簡單介紹一下微信小程式藍芽連線過程
#在藍芽連線的過程中部分api需要加定時器延時1秒到2秒左右再執行,原因為何不知道,小程式有這樣的要求
#1.首先是要初始化藍芽:openBluetoothAdapter()

if (wx.openBluetoothAdapter) {
    wx.openBluetoothAdapter({
        success: function(res) {
            /* 獲取本機的藍芽狀態 */
setTimeout(() => { getBluetoothAdapterState() }, 1000) }, fail: function(err) { // 初始化失敗 } }) } else { }

#2.檢測本機藍芽是否可用:

要在上述的初始化藍芽成功之後回撥裡呼叫

getBluetoothAdapterState() {
    var that = this;
    that.toastTitle = '檢查藍芽狀態'
wx.getBluetoothAdapterState({ success: function(res) { startBluetoothDevicesDiscovery() }, fail(res) { console.log(res) } }) }

#3. 開始搜尋藍芽裝置:

startBluetoothDevicesDiscovery() {
    var that = this;
    setTimeout(() => {
        wx.startBluetoothDevicesDiscovery
({ success: function(res) { /* 獲取藍芽裝置列表 */ that.getBluetoothDevices() }, fail(res) { } }) }, 1000) }

#4. 獲取搜尋到的藍芽裝置列表

/* that.deviceName 是獲取到的藍芽裝置的名稱, 因為藍芽裝置在安卓和蘋果手機上搜到的藍芽地址顯示是不一樣的,所以根據裝置名稱匹配藍芽*/

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) {
                                /* 根據指定的藍芽裝置名稱匹配到deviceId */
                                that.deviceId = that.devices[i].deviceId;
                                setTimeout(() => {
                                    that.connectTO();
                                }, 2000);
                            };
                        };
                    } else {
                    }
                } else {
                }
            },
            fail(res) {
                console.log(res, '獲取藍芽裝置列表失敗=====')
            }
        })
    }, 2000)
},

#5.連線藍芽

匹配到的藍芽裝置ID 傳送連線藍芽的請求, 連線成功之後 應該斷開藍芽搜尋的api,然後去獲取所連線藍芽裝置的service服務

connectTO() {
    wx.createBLEConnection({
        deviceId: deviceId,
        success: function(res) {
            that.connectedDeviceId = deviceId;
            /* 4.獲取連線裝置的service服務 */
            that.getBLEDeviceServices();
            wx.stopBluetoothDevicesDiscovery({
                success: function(res) {
                    console.log(res, '停止搜尋')
                },
                fail(res) {
                }
            })
        },
        fail: function(res) {
        }
    })
}

#6. 獲取藍芽裝置的service服務,獲取的serviceId有多個要試著連線最終確定哪個是穩定版本的service 獲取服務完後獲取裝置特徵值

getBLEDeviceServices() {
    setTimeout(() => {
        wx.getBLEDeviceServices({
            deviceId: that.connectedDeviceId,
            success: function(res) {
                that.services = res.services
                /* 獲取連線裝置的所有特徵值 */
                that.getBLEDeviceCharacteristics()
            },
            fail: (res) => {
            }
        })
    }, 2000)
},

#7.獲取藍芽裝置特徵值

獲取到的特徵值有多個,最後要用的事能讀,能寫,能監聽的那個值的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, '藍芽特徵值 ==========')
                                /* 獲取藍芽特徵值 */
                                that.notifyCharacteristicsId = res.characteristics[i].uuid
                                // 啟用低功耗藍芽裝置特徵值變化時的 notify 功能
                                that.notifyBLECharacteristicValueChange()
                            }
                        }
                    },
                    fail: function(res) {
                    }
                })
            }, 1000)
        },

#8.啟動notify 藍芽監聽功能 然後使用 wx.onBLECharacteristicValueChange用來監聽藍芽裝置傳遞資料
#接收到的資料和傳送的資料必須是二級制資料, 頁面展示的時候需要進行轉換

        notifyBLECharacteristicValueChange() { // 啟用低功耗藍芽裝置特徵值變化時的 notify 功能
            var that = this;
            console.log('6.啟用低功耗藍芽裝置特徵值變化時的 notify 功能')
            wx.notifyBLECharacteristicValueChange({
                state: true,
                deviceId: that.connectedDeviceId,
                serviceId: that.notifyServicweId,
                characteristicId: that.notifyCharacteristicsId,
                complete(res) {
                    /*用來監聽手機藍芽裝置的資料變化*/
                    wx.onBLECharacteristicValueChange(function(res) {
                        /**/
                        that.balanceData += that.buf2string(res.value)
                        that.hexstr += that.receiveData(res.value)
                    })
                },
                fail(res) {
                    console.log(res, '啟用低功耗藍芽裝置監聽失敗')
                    that.measuringTip(res)
                }
            })
        },
        
        /*轉換成需要的格式*/
         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))
          },
          /*轉成二進位制*/
           ab2hex (buffer) {
              var hexArr = Array.prototype.map.call(
                  new Uint8Array(buffer), function (bit) {
                      return ('00' + bit.toString(16)).slice(-2)
                  }
              )
              return hexArr.join('')
          },
          /*轉成可展會的文字*/
          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('');
          },

向藍芽裝置傳送資料

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('傳送的資料:' + that.writeDatas)
            console.log('message傳送成功')
        },
        fail: function (res) {
        },
        complete: function (res) {
        }
    })
    },

當不需要連線藍芽了後就要關閉藍芽,並關閉藍芽模組

 // 斷開裝置連線
closeConnect() {
    if (that.connectedDeviceId) {
        wx.closeBLEConnection({
            deviceId: that.connectedDeviceId,
            success: function(res) {
                that.closeBluetoothAdapter()
            },
            fail(res) {
            }
        })
    } else {
        that.closeBluetoothAdapter()
    }
},
// 關閉藍芽模組
closeBluetoothAdapter() {
    wx.closeBluetoothAdapter({
        success: function(res) {
        },
        fail: function(err) {
        }
    })
},

#在向藍芽裝置傳遞資料和接收資料的過程中,並未使用到read的API 不知道有沒有潛在的問題,目前線上執行為發現任何的問題
#今天的藍芽使用心得到此結束,謝謝