首頁 微信小程式 小程式開發 微信小程式--Ble藍牙

微信小程式--Ble藍牙

May 10, 2018 pm 03:13 PM
微信小程式 藍牙

本文主要介紹了微信小程式--Ble藍牙的實作方法。文中附上原始碼下載,具有很好的參考價值。下面跟著小編一起來看吧

有一段時間沒有。沒有寫關於小程式的文章了。 3月28日,微信的api又一次新的更新。期待已久的藍牙api更新。就開始擼一番。

原始碼位址

1.簡述

藍牙適配器介面是基礎庫版本 1.1.0 開始支援。

iOS 微信客戶端 6.5.6 版本開始支持,Android 用戶端暫不支援

藍牙總共增加了18個api介面。

2.Api分類

搜尋類別

連接類別

通訊類別

3 .API的具體使用

詳細見官網:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxgetconnectedbluethoothdevicesobject

4. 案例實作

4.1 搜尋藍牙裝置

/**
 * 搜索设备界面
 */
Page({
 data: {
 logs: [],
 list:[],
 },
 onLoad: function () {
 console.log('onLoad')
var that = this;
// const SDKVersion = wx.getSystemInfoSync().SDKVersion || '1.0.0'
// const [MAJOR, MINOR, PATCH] = SDKVersion.split('.').map(Number)
// console.log(SDKVersion);
// console.log(MAJOR);
// console.log(MINOR);
// console.log(PATCH);

// const canIUse = apiName => {
// if (apiName === 'showModal.cancel') {
//  return MAJOR >= 1 && MINOR >= 1
// }
// return true
// }

// wx.showModal({
// success: function(res) {
//  if (canIUse('showModal.cancel')) {
//  console.log(res.cancel)
//  }
// }
// })
  //获取适配器
  wx.openBluetoothAdapter({
  success: function(res){
  // success
  console.log("-----success----------");
   console.log(res);
   //开始搜索
  wx.startBluetoothDevicesDiscovery({
 services: [],
 success: function(res){
 // success
  console.log("-----startBluetoothDevicesDiscovery--success----------");
  console.log(res);
 },
 fail: function(res) {
 // fail
  console.log(res);
 },
 complete: function(res) {
 // complete
  console.log(res);
 }
})

  },
  fail: function(res) {
   console.log("-----fail----------");
  // fail
   console.log(res);
  },
  complete: function(res) {
  // complete
   console.log("-----complete----------");
   console.log(res);
  }
 })

  wx.getBluetoothDevices({
  success: function(res){
   // success
   //{devices: Array[11], errMsg: "getBluetoothDevices:ok"}
   console.log("getBluetoothDevices");
   console.log(res);
   that.setData({
   list:res.devices
   });
   console.log(that.data.list);
  },
  fail: function(res) {
   // fail
  },
  complete: function(res) {
   // complete
  }
  })

 },
 onShow:function(){

 },
 //点击事件处理
 bindViewTap: function(e) {
  console.log(e.currentTarget.dataset.title);
  console.log(e.currentTarget.dataset.name);
  console.log(e.currentTarget.dataset.advertisData);

 var title = e.currentTarget.dataset.title;
 var name = e.currentTarget.dataset.name;
  wx.redirectTo({
  url: '../conn/conn?deviceId='+title+'&name='+name,
  success: function(res){
   // success
  },
  fail: function(res) {
   // fail
  },
  complete: function(res) {
   // complete
  }
  })
 },
})
登入後複製

4.2連線取得資料

/**
 * 连接设备。获取数据
 */
Page({
 data: {
  motto: 'Hello World',
  userInfo: {},
  deviceId: '',
  name: '',
  serviceId: '',
  services: [],
  cd20: '',
  cd01: '',
  cd02: '',
  cd03: '',
  cd04: '',
  characteristics20: null,
  characteristics01: null,
  characteristics02: null,
  characteristics03: null,
  characteristics04: null,
  result,

 },
 onLoad: function (opt) {
  var that = this;
  console.log("onLoad");
  console.log('deviceId=' + opt.deviceId);
  console.log('name=' + opt.name);
  that.setData({ deviceId: opt.deviceId });
  /**
   * 监听设备的连接状态
   */
  wx.onBLEConnectionStateChanged(function (res) {
   console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
  })
  /**
   * 连接设备
   */
  wx.createBLEConnection({
   deviceId: that.data.deviceId,
   success: function (res) {
    // success
    console.log(res);
    /**
     * 连接成功,后开始获取设备的服务列表
     */
    wx.getBLEDeviceServices({
     // 这里的 deviceId 需要在上面的 getBluetoothDevices中获取
     deviceId: that.data.deviceId,
     success: function (res) {
      console.log('device services:', res.services)
      that.setData({ services: res.services });
      console.log('device services:', that.data.services[1].uuid);
      that.setData({ serviceId: that.data.services[1].uuid });
      console.log('--------------------------------------');
      console.log('device设备的id:', that.data.deviceId);
      console.log('device设备的服务id:', that.data.serviceId);
      /**
       * 延迟3秒,根据服务获取特征 
       */
      setTimeout(function () {
       wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要在上面的 getBluetoothDevices
        deviceId: that.data.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: that.data.serviceId,
        success: function (res) {
         console.log('000000000000' + that.data.serviceId);
         console.log('device getBLEDeviceCharacteristics:', res.characteristics)
         for (var i = 0; i < 5; i++) {
          if (res.characteristics[i].uuid.indexOf("cd20") != -1) {
           that.setData({
            cd20: res.characteristics[i].uuid,
            characteristics20: res.characteristics[i]
           });
          }
          if (res.characteristics[i].uuid.indexOf("cd01") != -1) {
           that.setData({
            cd01: res.characteristics[i].uuid,
            characteristics01: res.characteristics[i]
           });
          }
          if (res.characteristics[i].uuid.indexOf("cd02") != -1) {
           that.setData({
            cd02: res.characteristics[i].uuid,
            characteristics02: res.characteristics[i]
           });
          } if (res.characteristics[i].uuid.indexOf("cd03") != -1) {
           that.setData({
            cd03: res.characteristics[i].uuid,
            characteristics03: res.characteristics[i]
           });
          }
          if (res.characteristics[i].uuid.indexOf("cd04") != -1) {
           that.setData({
            cd04: res.characteristics[i].uuid,
            characteristics04: res.characteristics[i]
           });
          }
         }
         console.log(&#39;cd01= &#39; + that.data.cd01 + &#39;cd02= &#39; + that.data.cd02 + &#39;cd03= &#39; + that.data.cd03 + &#39;cd04= &#39; + that.data.cd04 + &#39;cd20= &#39; + that.data.cd20);
         /**
          * 回调获取 设备发过来的数据
          */
         wx.onBLECharacteristicValueChange(function (characteristic) {
          console.log(&#39;characteristic value comed:&#39;, characteristic.value)
          //{value: ArrayBuffer, deviceId: "D8:00:D2:4F:24:17", serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240", characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"}
          /**
           * 监听cd04cd04中的结果
           */
          if (characteristic.characteristicId.indexOf("cd01") != -1) {
           const result = characteristic.value;
           const hex = that.buf2hex(result);
           console.log(hex);
          }
          if (characteristic.characteristicId.indexOf("cd04") != -1) {
           const result = characteristic.value;
           const hex = that.buf2hex(result);
           console.log(hex);
           that.setData({ result: hex });
          }

         })
         /**
          * 顺序开发设备特征notifiy
          */
         wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd01,
          state: true,
          success: function (res) {
           // success
           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);
          },
          fail: function (res) {
           // fail
          },
          complete: function (res) {
           // complete
          }
         })
         wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd02,
          state: true,
          success: function (res) {
           // success
           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);
          },
          fail: function (res) {
           // fail
          },
          complete: function (res) {
           // complete
          }
         })
         wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd03,
          state: true,
          success: function (res) {
           // success
           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res);
          },
          fail: function (res) {
           // fail
          },
          complete: function (res) {
           // complete
          }
         })

         wx.notifyBLECharacteristicValueChanged({
          // 启用 notify 功能
          // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd04,
          state: true,
          success: function (res) {
           console.log(&#39;notifyBLECharacteristicValueChanged success&#39;, res)
          }
         })

        }, fail: function (res) {
         console.log(res);
        }
       })
      }
       , 1500);
     }
    })
   },
   fail: function (res) {
    // fail
   },
   complete: function (res) {
    // complete
   }
  })
 },

 /**
  * 发送 数据到设备中
  */
 bindViewTap: function () {
  var that = this;
  var hex = &#39;AA5504B10000B5&#39;
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
   return parseInt(h, 16)
  }))
  console.log(typedArray)
  console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])
  var buffer1 = typedArray.buffer
  console.log(buffer1)
  wx.writeBLECharacteristicValue({
   deviceId: that.data.deviceId,
   serviceId: that.data.serviceId,
   characteristicId: that.data.cd20,
   value: buffer1,
   success: function (res) {
    // success
    console.log("success 指令发送成功");
    console.log(res);
   },
   fail: function (res) {
    // fail
    console.log(res);
   },
   complete: function (res) {
    // complete
   }
  })

 },
 /**
  * ArrayBuffer 转换为 Hex
  */
 buf2hex: function (buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => (&#39;00&#39; + x.toString(16)).slice(-2)).join(&#39;&#39;);
 }
})
登入後複製


#5.效果展示

微信小程式--Ble藍牙


微信小程式--Ble藍牙

#################### #發送校驗指令。取得結果###############

以上是微信小程式--Ble藍牙的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

解決win11同時播放耳機與音響的問題 解決win11同時播放耳機與音響的問題 Jan 06, 2024 am 08:50 AM

一般來說,我們只需要同時使用耳機或音響的其中一個設備,但是有些朋友反映在win11系統中,遇到了耳機和音響一起響的問題,其實我們可以在realtek面板中將它關閉,就可以了,下面一起來看一下吧。 win11耳機和音響一起響怎麼辦1、先在桌面上找到並打開“控制面板”2、進入控制面板,在其中找到並打開“硬體和聲音”3、然後再找到一個喇叭圖標的“Realtek高清晰音訊管理器”4、選擇“揚聲器”再點擊“後面板”進入揚聲器設定。 5.打開之後我們可以看到設備類型,如果要關閉耳機就取消勾選“耳機”,如果要

vivo手機中開啟藍牙的方法 vivo手機中開啟藍牙的方法 Mar 23, 2024 pm 04:26 PM

1.在螢幕底端向上滑,調出控制中心,如下圖,點擊藍牙開關即可開啟藍牙。 2.我們就可以連接其他配對過的藍牙設備或點擊【搜尋藍牙設備】來和新的藍牙設備進行連接,想要其他小夥伴搜到自己的手機來連接藍牙時記得要打開【可檢測性】開關哦。方法二、1、進入手機桌面,找到並開啟設定。 2.在【設定】目錄下拉找到【更多設定】,點選進入,3、點選開啟【藍牙】,將藍牙開關開啟即可開啟藍牙啦。

閒魚微信小程式正式上線 閒魚微信小程式正式上線 Feb 10, 2024 pm 10:39 PM

閒魚官方微信小程式悄悄上線,在小程式中可以發布閒置與買家/賣家私訊交流、查看個人資料及訂單、搜尋物品等,有用好奇閒魚微信小程式叫什麼,現在快來看一下。閒魚微信小程式叫什麼答案:閒魚,閒置交易二手買賣估價回收。 1、在小程式中可以發布閒置、與買家/賣家私訊交流、查看個人資料及訂單、搜尋指定物品等功能;2、在小程式的頁面中有首頁、附近、發閒置、訊息、我的5項功能;3、想要使用的話必要要開通微信支付才可以購買;

win11系統裝置管理員沒有藍牙模組 win11系統裝置管理員沒有藍牙模組 Mar 02, 2024 am 08:01 AM

win11系統裝置管理員沒有藍牙模組在使用Windows11系統時,有時候會遇到裝置管理員中沒有藍牙模組的情況。這可能會對我們的日常使用造成不便,因為藍牙技術在現代社會中已經變得非常普遍,我們經常需要使用它來連接無線設備。如果你在裝置管理員中找不到藍牙模組,別擔心,以下將為你介紹一些可能的解決方法:1.檢查硬體連接:首先要確保你的電腦或筆記型電腦上確實有藍牙模組。有些裝置可能不會自備藍牙功能,這時你需要購買外部的藍牙轉接器來連接。 2.更新驅動程式:有時候裝置管理員中沒有藍牙模組是因為驅動程

哈利波特魔咒互換用不了藍牙解決方法 哈利波特魔咒互換用不了藍牙解決方法 Mar 21, 2024 pm 04:30 PM

哈利波特魔法覺醒中最近新增了一個魔咒互換功能,需要玩家使用藍牙或WiFi來互換魔咒,有些玩家發現自己使用不了藍牙互換,那麼怎麼才能使用藍牙互換魔咒呢?接下來小編就為大家帶來了哈利波特魔咒互換用不了藍牙解決方法,希望能夠幫助大家。哈利波特魔咒互換用不了藍牙解決方法1、首先玩家需要在圖書館中找到魔咒互換,就可以使用藍牙或WiFi進行互換了。 2.點選使用藍牙,提示需要下載新的安裝包,但之前已經下載過了,有些玩家就開始犯糊塗了。 3.其實新的安裝包玩家去商店即可下載,ios就去蘋果商店更新,安卓

藍牙5.3要求手機支援嗎?詳細資訊請看 藍牙5.3要求手機支援嗎?詳細資訊請看 Jan 14, 2024 pm 04:57 PM

我們在買手機的時候,會看到手機參數裡有一個支援藍牙選項,有時候就會遇到購買的藍牙耳機和手機不匹配的情況,那麼藍牙5.3需要手機支援嗎,其實是不需要的。藍牙5.3需要手機支援嗎:答:藍牙5.3需要手機支援。不過只要支援藍牙的手機就可以使用。 1.藍牙是向下相容的,不過要使用對應版本就需要手機支援。 2.舉例來說,如果我們購買了一款使用藍牙5.3的無線藍牙耳機。 3.那麼,如果我們的手機只支援藍牙5.0,那麼在連線時使用的就是藍牙5.0。4、因此,我們依舊是可以使用這款手機連接耳機來聽歌的,但是速度不如藍

如何配對羅技鍵盤 [USB 接收器、藍牙、iPad] 如何配對羅技鍵盤 [USB 接收器、藍牙、iPad] Nov 18, 2023 pm 11:27 PM

在將新的無線鍵盤與PC一起使用之前,需要將其配對,在本指南中,我們將向您展示如何正確配對羅技鍵盤。這個過程非常簡單,只需點擊幾下,所以加入我們,我們將向您展示如何在您的PC上執行此操作。如何將羅技鍵盤置於配對模式?我們如何測試、審查和評分?在過去的6個月裡,我們一直在努力建立一個關於我們如何製作內容的新審查系統。使用它,我們隨後重做了大部分文章,以提供有關我們製作的指南的實際實踐專業知識。有關更多詳細信息,可以在WindowsReport上閱讀我們如何測試、審查和評分。打開鍵盤。如果LED不閃爍

Win11系統遇到藍牙無法連線問題的解決方法 Win11系統遇到藍牙無法連線問題的解決方法 Jan 29, 2024 pm 02:36 PM

Win11系統藍牙無法使用怎麼辦隨著Win11系統的推出,許多用戶都迫不及待地升級了他們的電腦。然而,一些用戶在升級後遇到了一個常見的問題:藍牙無法使用。這對於那些依賴藍牙設備的用戶來說是一個令人沮喪的問題。幸運的是,有一些簡單的解決方法可以幫助您解決這個問題。首先,您可以嘗試重新啟動您的電腦。有時候,只需簡單地重新啟動系統就可以解決一些問題,包括藍牙無法使用的問題。重新啟動後,檢查藍牙是否正常運作。如果重新啟動沒有解決問題,那麼您可以嘗試更新藍牙驅動程式。有時候,舊的或損壞的驅動程式可能會導

See all articles