微信小程序 蓝牙设备连接,控制开关灯

1.前言

微信小程序中连接蓝牙设备,信息写入流程
1、检测当前使用设备(如自己的手机)是否支持蓝牙/蓝牙开启状态
wx:openBluetoothAdapter({})
2、如蓝牙已开启状态,检查蓝牙适配器的状态
wx.getBluetoothAdapterState({})
3、添加监听蓝牙适配器状态变化
wx.onBluetoothAdapterStateChange({})
4、搜索附近蓝牙设备
wx.startBluetoothDevicesDiscovery({})
5、监听搜索的到设备
wx.onBluetoothDeviceFound({})
遍历设备列表找到和macAddr(看自己家的蓝牙装置的物理地址)匹配的设备的deviceId
6、连接想要连接的切匹配成功的设备
wx.createBLEConnection({})
7、获取连接成功的设备的设备服务servicesID
wx.getBLEDeviceServices({})
8、获取设备特征id
wx.getBLEDeviceCharacteristics({})
9、向设备写入指令
wx.writeBLECharacteristicValue({})

以下是代码重点,本人亲测有效,集官网和百家之所长,汇聚之大成,入我门来,使君不负观赏

#2. 小程序前端index.wxml

<wxs module="utils">
module.exports.max = function(n1, n2) {
  return Math.max(n1, n2)
}
module.exports.len = function(arr) {
  arr = arr || []
  return arr.length
}
</wxs>
<button bindtap="openBluetoothAdapter"   class="primary-btn" >开始扫描</button>
<button bindtap="closeBLEConnection"  class="default-btn" >断开连接</button>
<button bindtap="opendeng"   class="sumit-btn" >开灯</button>
<button bindtap="guandeng"   class="warn-btn" >关灯</button>

<view class="devices_summary">已发现 {{devices.length}} 个外围设备:</view>
<scroll-view class="device_list" scroll-y scroll-with-animation>
  <view wx:for="{{devices}}" wx:key="index"
   data-device-id="{{item.deviceId}}"
   data-name="{{item.name || item.localName}}"
   bindtap="createBLEConnection" 
   class="device_item"
   hover-class="device_item_hover">
    <view style="font-size: 16px; color: #333;">{{item.name}}</view>
    <view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{utils.max(0, item.RSSI + 100)}}%)</view>
    <view style="font-size: 10px">UUID: {{item.deviceId}}</view>
    <view style="font-size: 10px">Service数量: {{utils.len(item.advertisServiceUUIDs)}}</view>
  </view>
</scroll-view>

<view class="connected_info" wx:if="{{connected}}">
   <view>
    <icon class="icon-box-img" type="success" size="33"></icon>
    <view class="icon-box-text"> {{name}}连接成功!!!</view>
   </view> 
 
</view>

3.小程序index.wxss


page {
  color: #333;
}
.icon-box-img{
  height: 20px;
 float: left;
 margin-left: 20%;
}
.icon-box-text{
  height: 30px;
   line-height: 30px;
  margin-left:5px;
 float: left;
}

.primary-btn{
  margin-top: 30rpx;
  /* border: rgb(7, 80, 68) 1px solid; */
  color: rgb(241, 238, 238);
  background-color: rgb(14, 207, 46);
}
.default-btn{
  margin-top: 30rpx;
  /* border: #333 1px solid; */
  color: rgb(243, 236, 236);
  background-color: rgb(189, 112, 25);
}

.warn-btn{
  margin-top: 30rpx;
  /* border: #333 1px solid; */
  color: rgb(240, 231, 231);
  background-color: rgb(235, 10, 10);
}
.sumit-btn{
  margin-top: 30px;
  width: 60px;
  color: rgb(240, 231, 231);
  background-color: rgb(10, 100, 235);
}

.devices_summary {
  margin-top: 30px;
  padding: 10px;
  font-size: 16px;
}
.device_list {
  height: 300px;
  margin: 50px 5px;
  margin-top: 0;
  border: 1px solid #EEE;
  border-radius: 5px;
  width: auto;
}
.device_item {
  border-bottom: 1px solid #EEE;
  padding: 10px;
  color: #666;
}
.device_item_hover {
  background-color: rgba(0, 0, 0, .1);
}
.connected_info {
  position: fixed;
    bottom: 10px;
    width: 80%;
    margin-left: 6%;
    background-color: #F0F0F0;
    padding: 10px;
    padding-bottom: 20px;
    margin-bottom: env(safe-area-inset-bottom);
    font-size: 18px;
    /* line-height: 20px; */
    color: #1da54d;
    text-align: center;
    /* height: 20px; */
    box-shadow: 0px 0px 3px 0px;
}
.connected_info .operation {
  position: absolute;
  display: inline-block;
  right: 30px;
}


4.小程序 index.ts


const app = getApp()

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
  },
  getCeshi() {
    wx.navigateTo({
      url: '/pages/main/main',
    })
  },
  // 搜寻周边蓝牙
  openBluetoothAdapter() {
    //console.log('openBluetoothAdapter success')
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  // 停止搜寻周边蓝牙
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  // 开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  //停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  //监听搜索到新设备的事件
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  //连接蓝牙低功耗设备。
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  //获取蓝牙低功耗设备所有服务。
  getBLEDeviceServices(deviceId) {
    console.log('deviceId ========', deviceId)
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          //获取通过设备id多个特性服务serviceid (包含 读、写、通知、等特性服务)
         //   console.log('serviceId ========', res.services[2].uuid)
          
         // 通过上边注释解封,排查到判断服务id 中第三个服务id  代表写入服务
        //  isPrimary代表 :判断服务id是否为主服务
         // if (res.services[2].isPrimary) {
         //  this.getBLEDeviceCharacteristics(deviceId, res.services[2].uuid)
        //  }
           //判断通过(设备id获取的多个特性服务)中是否有与(蓝牙助手获取的写入特性服务),相一致的serviceid
          if (res.services[i].uuid=="0000FFE0-0000-1000-8000-00805F9B34FB") {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid) 
          }
        }
      }
    })
  },
  //获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    console.info("蓝牙的deviceId====" + deviceId);
    console.info("蓝牙服务的serviceId====" + serviceId);
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid

            console.info("写入(第一步)的characteristicId====" + item.uuid);
            //初始化调用 写入信息的方法  1:代表开灯
            this.writeBLECharacteristicValue("1")
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听,保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
     
      this.setData(data)
    })
  },
  
/**
 * 写入的数据 格式转换
 * @param str
 * @returns 字符串 转 ArrayBuffer
 */
hex2buffer(str) {
  console.info("写入的数据====" + str);
  //字符串 转 十六进制
  var val = "";
  for (var i = 0; i < str.length; i++) {
      if (val == "")
          val = str.charCodeAt(i).toString(16);
      else
          val += "," + str.charCodeAt(i).toString(16);
  }
  //十六进制 转 ArrayBuffer
  var buffer = new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
  })).buffer;

  return buffer;
},
//开灯
opendeng() {
  
  // 调用写入信息的方法 向蓝牙设备发送一个开灯的参数数据 ,  1:代表开灯
  var writeValue ="1";
  this.writeBLECharacteristicValue(writeValue)
 
},
//关灯
guandeng() {

    // 调用写入信息的方法 向蓝牙设备发送一个关灯的参数数据 ,  0:代表关灯
     var writeValue ="0";
     this.writeBLECharacteristicValue(writeValue)
    
},
writeBLECharacteristicValue(writeValue) {
  // 向蓝牙设备发送一个0x00的16进制数据
 // let buffer = new ArrayBuffer(1)
 // let dataView = new DataView(buffer)
 //  dataView.setUint8(0, 0)
 //调用hex2buffer()方法,转化成ArrayBuffer格式
 console.log('获取传递参数writeValue的数据为=====',writeValue)
 var buffer =this.hex2buffer(writeValue);
  console.log('获取二进制数据',buffer)
  //向低功耗蓝牙设备特征值中写入二进制数据。
  wx.writeBLECharacteristicValue({
    deviceId: this._deviceId,
    serviceId: this._serviceId,
    characteristicId: this._characteristicId,
    value: buffer,
    success (res) {
      console.log('成功写数据writeBLECharacteristicValue success', res)
      //如果 uni.writeBLECharacteristicValue 走 success ,证明你已经把数据向外成功发送了,但不代表设备一定就收到了。通常设备收到你发送过去的信息,会返回一条消息给你,而这个回调消息会在 uni.onBLECharacteristicValueChange 触发
    },
     fail(res) {
      console.error('失败写数据getBLEDeviceCharacteristics', res)
    }
  })
},
//断开与蓝牙低功耗设备的连接。
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
})



5.疑难点

1.如果你不确定写入的特性服务值

可以通过(安卓)蓝牙助手获取特性值 deviceId(mac地址)、serviceId、characteristicId

(苹果手机)蓝牙助手获得特性值deviceId(uuid地址)、serviceId、characteristicId  
 

注意:手机品类不同获取的deviceId的名称不同,但serviceId、characteristicId,是相同的

1.安卓手机(蓝牙助手获取的信息)
在这里插入图片描述
在这里插入图片描述

2.苹果手机(蓝牙助手)获取的信息

在这里插入图片描述
在这里插入图片描述

FFF0代表的serviceId全称:0000FFF0-0000-1000-8000-00805F9B34FB

FFF3代表的characteristicId全称:0000FFF3-0000-1000-8000-00805F9B34FB

最后:

祝愿你能一次成功
(代码直接复制粘贴到你的小程序中,替换下你自己设备的写入特性serviceId值),
就可以测试了
最后如果还满意,记得点下赞、收藏加关注、我也好回关,相互进步!!!!!!!!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/78615.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【先进PID控制算法(ADRC,TD,ESO)加入永磁同步电机发电控制仿真模型研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

Kafka第三课

Flume 由三部分 Source Channel Sink 可以通过配置拦截器和Channel选择器,来实现对数据的分流, 可以通过对channel的2个存储容量的的设置,来实现对流速的控制 Kafka 同样由三大部分组成 生产者 服务器 消费者 生产者负责发送数据给服务器 服务器存储数据 消费者通过从服务器取…

负载均衡搭建

LVS-DR部署 [客户端] node1 192.168.157.148 [lvs] node2 192.168.157.142 [web服务器] node3 192.168.157.145 node4 192.168.157.146&#xff08;1&#xff09;[lvs] yum install -y ipvsadm.x86_64 配置LVS负载均衡服务 &#xff08;1&#xff09;手动添加LVS转发1&#xff…

Vue3 使用json编辑器

安装 npm install json-editor-vue3 main中引入 main.js 中加入下面代码 import "jsoneditor";不然会有报错&#xff0c;如jsoneditor does not provide an export named ‘default’。 图片信息来源-github 代码示例 <template><json-editor-vue class…

一个DW的计算

一个DW的计算 1- 题目: 已知一个DW1.1 要求: 从DW中取出指定的位的值1.1.1 分析1.1.2 实现1.1.3 简化实现1.1.4 验证 2- 题目: 已知一个DW2.1 要求: 从DW中的指定的P和S,取出指定的位的值2.1.1 分析2.1.2 实现 1- 题目: 已知一个DW 有图中所示一行信息&#xff0c;表示一个DW(…

【实用黑科技】如何 把b站的缓存视频弄到本地——数据恢复软件WinHex 和 音视频转码程序FFmpeg

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;效率…

uniapp编写微信小程序遇到的坑总结

1、阻止事件冒泡 使用uniapp开发微信小程序的时候&#xff0c;发现使用click.stop来阻止事件冒泡没有作用&#xff0c;点击了之后发现仍然会触发父组件或者祖先组件的事件。 在网上查阅&#xff0c;发现使用tap.stop才能阻止事件冒泡。 2、二维码生成 在网上找了很多&…

问题:【IntelliJ IDEA】解决idea自动声明变量加finall修饰符问题

问题:【IntelliJ IDEA】解决idea自动声明变量加finall修饰符问题 场景复现 1 new String() 2 快捷方式生成变量 final修饰的 final String s new String();步骤一&#xff1a;确保settings配置信息 settings-----》Editor------》Code Style--------》java下的这两个选项不…

〔013〕Stable Diffusion 之 图片自动评分和不健康内容过滤器 篇

✨ 目录 &#x1f388; 下载咖啡美学评价插件&#x1f388; 咖啡美学评价使用&#x1f388; 不健康内容过滤器插件 &#x1f388; 下载咖啡美学评价插件 想让系统帮你的图片作品打分评价&#xff0c;可以下载咖啡美学自动评价插件插件地址&#xff1a;https://github.com/p1at…

stack和queue的模拟实现

stack和queue的模拟实现 容器适配器什么是适配器STL标准库中stack和queue的底层结构deque的简单介绍deque的缺陷 stack模拟实现queue模拟实现priority_queuepriority_queue的使用priority_queue的模拟实现 容器适配器 什么是适配器 适配器是一种设计模式(设计模式是一套被反复…

稀疏感知图像和体数据恢复的系统对象研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

爬虫逆向实战(十二)--某交易所登录

一、数据接口分析 主页地址&#xff1a;某交易所 1、抓包 通过抓包可以发现登录是通过表单提交的 2、判断是否有加密参数 请求参数是否加密&#xff1f; 通过查看“载荷”模块&#xff0c;可以发现有两个加密参数password和execution 请求头是否加密&#xff1f; 无响应是…

中国乡村振兴战略下传统村落文化旅游设计日

中国乡村振兴战略下传统村落文化旅游设计日

unity Dropdown默认选择不选择任何选项

当我们使用Dropdown下拉框时&#xff0c;有时不需要有默认选项&#xff0c;把 value设置为-1就可以了&#xff0c; 但是用代码设置value-1是没有效果的&#xff0c;

AI 绘画Stable Diffusion 研究(九)sd图生图功能详解-老照片高清修复放大

大家好&#xff0c;我是风雨无阻。 通过前面几篇文章的介绍&#xff0c;相信各位小伙伴&#xff0c;对 Stable Diffusion 这款强大的AI 绘图系统有了全新的认知。我们见识到了借助 Stable Diffusion的文生图功能&#xff0c;利用简单的几个单词&#xff0c;就可以生成完美的图片…

运行软件mfc140u.dll丢失怎么办?mfc140u.dll的三个修复方法

最近我在使用一款软件时遇到了一个问题&#xff0c;提示缺少mfc140u.dll文件。。这个文件是我在使用某个应用程序时所需要的&#xff0c;但是由于某种原因&#xff0c;它变得无法正常使用了。经过一番搜索和了解&#xff0c;我了解到mfc140u.dll是Microsoft Visual Studio 2015…

【JVM】JVM中的分代回收

文章目录 分代收集算法什么是分代分代收集算法-工作机制MinorGC、 Mixed GC 、 FullGC的区别是什么 分代收集算法 什么是分代 在java8时&#xff0c;堆被分为了两份&#xff1a; 新生代和老年代【1&#xff1a;2】 其中&#xff1a; 对于新生代&#xff0c;内部又被分为了三…

拒绝摆烂!C语言练习打卡第三天

&#x1f525;博客主页&#xff1a;小王又困了 &#x1f4da;系列专栏&#xff1a;每日一练 &#x1f31f;人之为学&#xff0c;不日近则日退 ❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 目录 一、选择题 &#x1f4dd;1.第一题 &#x1f4dd;2.第二题 &#x1f4…

Docker:Windows container和Linux container

点击"Switch to Windows containers"菜单时&#xff1a; 提示 然后 实际上是运行&#xff1a;com.docker.admin.exe start-service

【广州华锐视点】帆船航行VR模拟实操系统

帆船航行VR模拟实操系统由广州华锐视点开发&#xff0c;是一种创新的教学工具&#xff0c;它利用虚拟现实技术&#xff0c;为学生提供了一个沉浸式的学习环境。通过这种系统&#xff0c;学生可以在虚拟的环境中进行帆船航行的实训&#xff0c;从而更好地理解和掌握帆船航行的技…
最新文章