微信小程序藍牙教程--完整版親測

#使用mpvue 開發(fā)小程序過程中 簡單介紹一下微信小程序藍牙連接過程

#在藍牙連接的過程中部分api需要加定時器延時1秒到2秒左右再執(zhí)行缴啡,原因為何不知道,小程序有這樣的要求

#1.首先是要初始化藍牙:openBluetoothAdapter()

```js

if (wx.openBluetoothAdapter) {

wx.openBluetoothAdapter({

? ? ? ? success: function(res) {

????????????/* 獲取本機的藍牙狀態(tài) */

? ? ? ? ? ? setTimeout(() => {

????????????????getBluetoothAdapterState()

????????????}, 1000)

????????},

? ? ? ? fail: function(err) {

????????????// 初始化失敗

????????}

????})

????} else {????

????}

```

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

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

```js

getBluetoothAdapterState() {

? ? var that= this;

? ? that.toastTitle= '檢查藍牙狀態(tài)'

wx.getBluetoothAdapterState({

? ? ? ? success: function(res) {

startBluetoothDevicesDiscovery()

},

? ? ? ? fail(res) {

? ? ? ? ? ? console.log(res)

}

})

}

```

#3. 開始搜索藍牙設(shè)備:

```js

startBluetoothDevicesDiscovery() {

? ? var that= this;

? ? setTimeout(() => {

wx.startBluetoothDevicesDiscovery({

? ? ? ? ? ? success: function(res) {

/* 獲取藍牙設(shè)備列表 */

? ? ? ? ? ? ? ? that.getBluetoothDevices()

},

? ? ? ? ? ? fail(res) {

}

})

}, 1000)

}

```

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

# /* that.deviceName 是獲取到的藍牙設(shè)備的名稱赁温, 因為藍牙設(shè)備在安卓和蘋果手機上搜到的藍牙地址顯示是不一樣的速兔,所以根據(jù)設(shè)備名稱匹配藍牙*/

```js

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ù)指定的藍牙設(shè)備名稱匹配到deviceId */

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? that.deviceId = that.devices[i].deviceId;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? setTimeout(() => {

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? that.connectTO();

}, 2000);

};

};

} else {

}

} else {

}

},

? ? ? ? ? ? fail(res) {

? ? ? ? ? ? ? ? console.log(res, '獲取藍牙設(shè)備列表失敗=====')

}

})

}, 2000)

},

```

#5.連接藍牙

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

```js

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. 獲取藍牙設(shè)備的service服務(wù),獲取的serviceId有多個要試著連接最終確定哪個是穩(wěn)定版本的service 獲取服務(wù)完后獲取設(shè)備特征值

```js

getBLEDeviceServices() {

? ? setTimeout(() => {

wx.getBLEDeviceServices({

? ? ? ? ? ? deviceId: that.connectedDeviceId,

? ? ? ? ? ? success: function(res) {

? ? ? ? ? ? ? ? that.services= res.services

/* 獲取連接設(shè)備的所有特征值 */

that.getBLEDeviceCharacteristics()

},

? ? ? ? ? ? fail: (res) => {

}

})

}, 2000)

},

```

#7.獲取藍牙設(shè)備特征值

# 獲取到的特征值有多個憨栽,最后要用的事能讀帜矾,能寫,能監(jiān)聽的那個值的uuid作為特征值id屑柔,

```js

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

// 啟用低功耗藍牙設(shè)備特征值變化時的 notify 功能

that.notifyBLECharacteristicValueChange()

}

}

},

? ? ? ? ? ? ? ? ? ? fail: function(res) {

}

})

}, 1000)

},

```

#8.啟動notify 藍牙監(jiān)聽功能 然后使用 wx.onBLECharacteristicValueChange用來監(jiān)聽藍牙設(shè)備傳遞數(shù)據(jù)

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

```js

notifyBLECharacteristicValueChange() { // 啟用低功耗藍牙設(shè)備特征值變化時的 notify 功能

? ? ? ? ? ? var that= this;

? ? ? ? ? ? console.log('6.啟用低功耗藍牙設(shè)備特征值變化時的 notify 功能')

wx.notifyBLECharacteristicValueChange({

? ? ? ? ? ? ? ? state: true,

? ? ? ? ? ? ? ? deviceId: that.connectedDeviceId,

? ? ? ? ? ? ? ? serviceId: that.notifyServicweId,

? ? ? ? ? ? ? ? characteristicId: that.notifyCharacteristicsId,

? ? ? ? ? ? ? ? complete(res) {

/*用來監(jiā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, '啟用低功耗藍牙設(shè)備監(jiān)聽失敗')

? ? ? ? ? ? ? ? ? ? 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)成二進制*/

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)成可展會的文字*/

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('');

},

```

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

```js

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)不需要連接藍牙了后就要關(guān)閉藍牙珍剑,并關(guān)閉藍牙模塊

```js

// 斷開設(shè)備連接

closeConnect() {

if (that.connectedDeviceId) {

wx.closeBLEConnection({

? ? ? ? ? ? deviceId: that.connectedDeviceId,

? ? ? ? ? ? success: function(res) {

that.closeBluetoothAdapter()

},

? ? ? ? ? ? fail(res) {

}

})

} else {

that.closeBluetoothAdapter()

}

},

// 關(guān)閉藍牙模塊

closeBluetoothAdapter() {

wx.closeBluetoothAdapter({

? ? ? ? success: function(res) {

},

? ? ? ? fail: function(err) {

}

})

},

```

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

#今天的藍牙使用心得到此結(jié)束招拙,謝謝

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末唧瘾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子别凤,更是在濱河造成了極大的恐慌饰序,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件规哪,死亡現(xiàn)場離奇詭異求豫,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進店門蝠嘉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蚤告,你說我怎么就攤上這事努酸。” “怎么了杜恰?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵获诈,是天一觀的道長。 經(jīng)常有香客問我心褐,道長舔涎,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任檬寂,我火速辦了婚禮终抽,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘桶至。我一直安慰自己昼伴,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著弦赖,像睡著了一般攘已。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上持舆,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天,我揣著相機與錄音伪窖,去河邊找鬼逸寓。 笑死,一個胖子當(dāng)著我的面吹牛覆山,可吹牛的內(nèi)容都是我干的竹伸。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼簇宽,長吁一口氣:“原來是場噩夢啊……” “哼勋篓!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起魏割,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤譬嚣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后钞它,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體拜银,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡殊鞭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了盐股。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片钱豁。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖疯汁,靈堂內(nèi)的尸體忽然破棺而出牲尺,到底是詐尸還是另有隱情,我是刑警寧澤幌蚊,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布谤碳,位于F島的核電站,受9級特大地震影響溢豆,放射性物質(zhì)發(fā)生泄漏蜒简。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一漩仙、第九天 我趴在偏房一處隱蔽的房頂上張望搓茬。 院中可真熱鬧,春花似錦队他、人聲如沸卷仑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽锡凝。三九已至,卻和暖如春垢啼,著一層夾襖步出監(jiān)牢的瞬間窜锯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工芭析, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留锚扎,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓馁启,卻偏偏與公主長得像工秩,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子进统,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容