1. 程式人生 > 其它 >web連線低功耗藍芽裝置(BLE)

web連線低功耗藍芽裝置(BLE)

前言:

最近正在開發一個專案,專案的需求如下:
在H5(基於vue框架)頁面上,通過js呼叫webbluetooth介面,讀取某個藍芽裝置傳輸的資料,並返回顯示。

使用條件:

開發版本:無特殊要求

 正式版本:需要HTTPS證書

在手機上面測試:推薦使用Edge瀏覽器或者谷歌瀏覽器(其他瀏覽器我測不行,你們可以測試哈,如還有支援的,希望能給我說一聲 Thanks♪(・ω・)ノ)

程式碼:

1、連線藍芽

        navigator.bluetooth.requestDevice({
          optionalServices:['藍芽裝置服務ID'],
          acceptAllDevices:
true }).then(async (device) => { that.unCharDevice = device; let server = await device.gatt.connect(); let service = await server.getPrimaryService('藍芽裝置服務ID') let characteristic = await service.getCharacteristic('裝置主動上報狀態ID') let unCharacteristic
= await service.getCharacteristic('向裝置寫入命令ID') characteristic.readValue();//讀取命令 characteristic.startNotifications();//監聽命令下發後的返回值 //監聽藍芽裝置命令下發後的返回值
       characteristic.addEventListener('characteristicvaluechanged',item => {
console.log(item) }) }) .
catch(error => { alert('報錯'+error) })

2、下發命令

        unCharacteristic.writeValue(
          new Uint8Array('下發的命令byte陣列')
        )

3、斷開連線

  that.unCharDevice.addEventListener('gattserverdisconnected', event => {
  const device = event.target;
  console.log(`Device ${device.name} is disconnected.`);
});
  return device.gatt.connect();

參考文案:

https://blog.csdn.net/qq_44628595/article/details/117028837

https://zhuanlan.zhihu.com/p/20657057

https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API