首页 微信小程序 小程序开发 微信小程序如何实现蓝牙的实例分享

微信小程序如何实现蓝牙的实例分享

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脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
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、点击打开【蓝牙】,将蓝牙开关打开即可打开蓝牙啦。

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系统的推出,许多用户都迫不及待地升级了他们的电脑。然而,一些用户在升级后遇到了一个常见的问题:蓝牙无法使用。这对于那些依赖蓝牙设备的用户来说是一个令人沮丧的问题。幸运的是,有一些简单的解决方法可以帮助您解决这个问题。首先,您可以尝试重新启动您的电脑。有时候,只需简单地重新启动系统就可以解决一些问题,包括蓝牙无法使用的问题。在重新启动后,检查蓝牙是否正常工作。如果重新启动没有解决问题,那么您可以尝试更新蓝牙驱动程序。有时候,旧的或损坏的驱动程序可能会导

三星为多款 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