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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM