热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

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

这篇文章主要介绍了微信小程序蓝牙的实现实例代码的相关资料,需要的朋友可以参考下
这篇文章主要介绍了微信小程序 蓝牙的实现实例代码的相关资料,需要的朋友可以参考下

微信小程序 蓝牙的实现实例代码

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

以上就是微信小程序如何实现蓝牙的实例分享的详细内容,更多请关注其它相关文章!


推荐阅读
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
author-avatar
偽愛拋棄_514
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有