热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

微信小程序Ble蓝牙

本文主要介绍了微信小程序--Ble蓝牙的实现方法。文中附上源码下载,具有很好的参考价值。下面跟着小编一起来看下吧
本文主要介绍了微信小程序--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蓝牙的详细内容,更多请关注其它相关文章!


推荐阅读
  • 本文介绍了Oracle存储过程的基本语法和写法示例,同时还介绍了已命名的系统异常的产生原因。 ... [详细]
  • MySQL多表数据库操作方法及子查询详解
    本文详细介绍了MySQL数据库的多表操作方法,包括增删改和单表查询,同时还解释了子查询的概念和用法。文章通过示例和步骤说明了如何进行数据的插入、删除和更新操作,以及如何执行单表查询和使用聚合函数进行统计。对于需要对MySQL数据库进行操作的读者来说,本文是一个非常实用的参考资料。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • 本文介绍了一些Java开发项目管理工具及其配置教程,包括团队协同工具worktil,版本管理工具GitLab,自动化构建工具Jenkins,项目管理工具Maven和Maven私服Nexus,以及Mybatis的安装和代码自动生成工具。提供了相关链接供读者参考。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文介绍了在Linux下安装Perl的步骤,并提供了一个简单的Perl程序示例。同时,还展示了运行该程序的结果。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 解决VS写C#项目导入MySQL数据源报错“You have a usable connection already”问题的正确方法
    本文介绍了在VS写C#项目导入MySQL数据源时出现报错“You have a usable connection already”的问题,并给出了正确的解决方法。详细描述了问题的出现情况和报错信息,并提供了解决该问题的步骤和注意事项。 ... [详细]
  • 本文详细介绍了MySQL表分区的创建、增加和删除方法,包括查看分区数据量和全库数据量的方法。欢迎大家阅读并给予点评。 ... [详细]
  • 文件路径的生成及其在文件操作中的应用
    本文介绍了文件路径的生成方法及其在文件操作中的应用。在进行文件操作时,需要知道文件的具体位置才能打开文件。文件的位置有绝对路径和相对路径之分。绝对路径通常只在特定电脑上有效,不同电脑上的文件存放路径可能不同,导致程序报错。相对路径是解决这个问题的最好方式,它不依赖于文件的具体存放位置,只需要按照统一的规范进行文件存放即可。使用相对路径可以避免冗余和麻烦,特别适用于大项目和团队维护代码的情况。 ... [详细]
author-avatar
-依小冷_217
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有