首頁 微信小程式 小程式開發 微信小程式如何實現藍牙的實例分享

微信小程式如何實現藍牙的實例分享

May 22, 2018 pm 04:30 PM
實例 小程式 藍牙

這篇文章主要介紹了微信小程式藍牙的實作實例程式碼的相關資料,需要的朋友可以參考下

微信小程式藍牙的實作實例程式碼

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.效果展示

傳送校驗指令。取得結果

#

以上是微信小程式如何實現藍牙的實例分享的詳細內容。更多資訊請關注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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 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)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
解決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、點選開啟【藍牙】,將藍牙開關開啟即可開啟藍牙啦。

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不閃爍

實作微信小程式中的卡片翻轉特效 實作微信小程式中的卡片翻轉特效 Nov 21, 2023 am 10:55 AM

實作微信小程式中的卡片翻轉特效在微信小程式中,實現卡片翻轉特效是一種常見的動畫效果,可以提升使用者體驗和介面互動的吸引力。以下將具體介紹如何在微信小程式中實現卡片翻轉的特效,並提供相關程式碼範例。首先,需要在小程式的頁面佈局檔案中定義兩個卡片元素,一個用於顯示正面內容,一個用於顯示背面內容,具體範例程式碼如下:&lt;!--index.wxml--&gt;&l

三星為多款 Galaxy 手機、平板帶來藍牙 Auracast 廣播音訊功能 三星為多款 Galaxy 手機、平板帶來藍牙 Auracast 廣播音訊功能 Feb 21, 2024 pm 01:50 PM

2月21日消息,三星公司今天發佈公告,宣佈為已升級OneUI6.1及更高版本的GalaxyS23系列、ZFold5、ZFlip5手機,以及GalaxyTabS9系列平板,帶來藍牙Auracast音訊廣播功能。三星於去年開始,已陸續在GalaxyBuds2Pro耳機、三星智慧電視上添加對藍牙Auracast音訊廣播功能的支持,運行OneUI6.1的GalaxyS24系列手機已添加支援。符合適配升級至OneUI6.1的三星設備,可開啟「設定」>「藍牙」>「三點選單」>「使用Auracast廣播聲音

See all articles