微信小程序使用蓝牙连接硬件

目录

一、蓝牙官方api文档

二、蓝牙重要参数介绍

三、案例教程

1. 获取蓝牙权限(openBluetoothAdapter)

 2. 开始搜索蓝牙设备(startBluetoothDevicesDiscovery)

3. 监听搜索到新设备的事件(onBluetoothDeviceFound)

4.连接蓝牙设备(createBLEConnection)

5.获取蓝牙设备服务(getBLEDeviceServices) 

6.获取某个蓝牙服务特征(getBLEDeviceCharacteristics)

7.启动蓝牙服务值变化监听及监听特征值变化(notifyBLECharacteristicValueChange、onBLECharacteristicValueChange)

8.向蓝牙写入数据(writeBLECharacteristicValue)

9.string2buffer函数

四、扩展


一、蓝牙官方api文档

wx.startBluetoothDevicesDiscovery(Object object) | 微信开放文档微信开发者平台文档icon-default.png?t=N7T8https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth/wx.startBluetoothDevicesDiscovery.html

二、蓝牙重要参数介绍

1

deviceid

蓝牙设备的id 这个参数是蓝牙设备的唯一id
2

uuid

服务的id 这个是通过deviceid获取到的这个设备服务的uuid
3

characteristic

特性值 这个是通过deviceid、uuid获取到的特性值

重点:辅助理解这几个值的意思 

首先deviceid是比较清楚的,它是蓝牙设备的唯一标识它只有一个,它的用途在于找到蓝牙之后进行匹配蓝牙。其次是uuid它是通过deviced获得得到的,通过deviced就可以获取到它蓝牙的所有服务,服务就是蓝牙设置支持的某个能力例如开关led灯。还有服务嘛就是有很多,所以uuid不止有一个,使用哪个服务uuid看自己。下来就是特征值他是由devided和uuid得到的,它相当于是一个里面的功能而uuid是这个功能的门牌码,功能当然也有很多个,所以特性值也有好多个,一般使用写功能,遍历出来之后拿到写的特性值就行了。

三、案例教程

1. 获取蓝牙权限(openBluetoothAdapter)

initBlue:function(){
  var that = this;
  wx.openBluetoothAdapter({
    success: function (res) {
      wx.showToast({
        title: '初始化成功',
        icon: 'success',
        duration: 800
      })
      that.findBlue();//2.0
    },
    fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户
      wx.showToast({
        title: '请开启蓝牙',
        icon: 'fails',
        duration: 1000
      })
    }
  })
},

 2. 开始搜索蓝牙设备(startBluetoothDevicesDiscovery)

findBlue(){
  var that = this
  wx.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: true,
    interval: 0,
    powerLevel: 'high',
    success: function (res) {
     that.getBlue()//3.0
    }
  })
},

3. 监听搜索到新设备的事件(onBluetoothDeviceFound)

getBlue(){
  var that = this;
  wx.onBluetoothDeviceFound(function (devices) {
    
    if (devices.devices) {
      if(devices.devices[0].name=="这个要自己修改看要怎样的设备")
      {
        that.setData({
          deviceid: devices.devices[0].deviceId,
        })
        that.connetBlue();
      }
    }
  })
},

4.连接蓝牙设备(createBLEConnection)

connetBlue(){                    
  var that = this;
  var deviceid = that.data.deviceid;
  wx.createBLEConnection({
    // 这里的 deviceid 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId: deviceid,//设备id
    timeout: 10000, // 10s连接超时
    success: function (res) 
      wx.showToast({
        title: '连接成功',
        icon: 'fails',
        duration: 800
      })
      wx.stopBluetoothDevicesDiscovery()
      that.getServiceId()//5.0
      
    }
  })
},

5.获取蓝牙设备服务(getBLEDeviceServices) 

getServiceId(){
  var that = this
  wx.getBLEDeviceServices({
    // 这里的 deviceid 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId: that.data.deviceid,
    success: function (res) {
      var model = res.services[0].uuid
      that.getCharacteId()//6.0
    }
  })
},

6.获取某个蓝牙服务特征(getBLEDeviceCharacteristics)

getCharacteId(){
  var that = this 
  wx.getBLEDeviceCharacteristics({
    deviceId: that.data.deviceid,
    serviceId: that.data.services,
    success: function (res) {
          // 遍历特征值列表
    for (let i = 0; i < res.characteristics.length; i++) {
      let characteristic = res.characteristics[i];
      // 检查特征值是否具有 read 属性为 false
      if (!characteristic.properties.read) {
        // 当找到 read 属性为 false 的特征值时,设置 writeId 为该特征值的 UUID
        that.setData({
          writeId: characteristic.uuid
        });
        break; // 找到符合条件的特征值后,结束循环
      }
    }
  },
  fail: function (res) {
    // 处理获取特征值失败的情况
    console.log("失败的原因",res);
  }
  })
},

7.启动蓝牙服务值变化监听及监听特征值变化(notifyBLECharacteristicValueChange、onBLECharacteristicValueChange)

启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。注意:必须设备的特征支持 notify 或者 indicate 才可以成功调用。

另外,必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件

startNotice(uuid){
  var that = this;
  wx.notifyBLECharacteristicValueChange({
    state: true, // 启用 notify 功能
    deviceId: that.data.deviceid,
    serviceId: that.data.services,
    characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
    success: function (res) {
    wx.onBLECharacteristicValueChange(function (res) {
 
   // 这里面需要把回你的数据下转换格式
                })
  }
  })
},

8.向蓝牙写入数据(writeBLECharacteristicValue)

数据不能大于20字节,直接用就行,大于20字节则进行轮训发送(string2buffer函数在下面)

 sendmmm:function(sendData){
  var that = this;
    //向蓝牙发送数据
let buffer = that.string2buffer(sendData);//转16进制
let pos = 0;
let bytes = buffer.byteLength;
var result = ''
let tmpBuffer;
var sdtim= setInterval(function(){
  if (bytes > 20) {
    tmpBuffer = buffer.slice(pos, pos + 20);
    console.log('字节:');
    console.log(tmpBuffer);
    pos += 20;
    bytes -= 20;
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceid,
      serviceId: that.data.services,
      characteristicId: that.data.writeId,//第二步写入的特征值
      value: tmpBuffer,
      success(res) {
        console.log('发送成功!', res)
      }
 
    })
  } else {
    tmpBuffer = buffer.slice(pos, pos + bytes);
    console.log('字节:');
    console.log(tmpBuffer);
    pos += bytes;
    bytes -= bytes;
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceid,
      serviceId: that.data.services,
      characteristicId: that.data.writeId,//第二步写入的特征值
      value: tmpBuffer,
      success(res) {
        console.log('最后次发送', res)
        })
        clearInterval(sdtim);
      },
      fail: function (res) {
        console.log('发送失败', res)
      }
    })
  }
}, 30);
},

9.string2buffer函数

 string2buffer(str) {
   let buffer = new ArrayBuffer(str.length * 2); // 每个字符占2个字节
   let bufferView = new Uint16Array(buffer);
   for (let i = 0; i < str.length; i++) {
     bufferView[i] = str.charCodeAt(i);
   }
   return buffer;
 },

四、扩展

蓝牙 (Bluetooth) | 微信开放文档

只能连接蓝牙4.0以上低功耗,就是手机啥的蓝牙检测不到,耳机什么的可以检测到

相关推荐

  1. 程序连接

    2024-05-03 23:38:05       33 阅读
  2. 程序实现连接通讯

    2024-05-03 23:38:05       25 阅读
  3. 程序连接设备

    2024-05-03 23:38:05       32 阅读
  4. uniapp程序连接与设备数据对接

    2024-05-03 23:38:05       29 阅读
  5. uniapp中程序——连接并通信

    2024-05-03 23:38:05       34 阅读
  6. 程序连接

    2024-05-03 23:38:05       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-03 23:38:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-03 23:38:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-03 23:38:05       82 阅读
  4. Python语言-面向对象

    2024-05-03 23:38:05       91 阅读

热门阅读

  1. 「C/C++ 01」变量,变量名和指针

    2024-05-03 23:38:05       39 阅读
  2. Rust async,看这一篇就够了~

    2024-05-03 23:38:05       37 阅读
  3. face_recognition+python-opencv实现摄像头实时人脸识别

    2024-05-03 23:38:05       35 阅读
  4. web server apache tomcat11-29-Windows Authentication

    2024-05-03 23:38:05       32 阅读
  5. npm详解

    2024-05-03 23:38:05       39 阅读
  6. 基于FPGA的数字信号处理(4)--浮点数的定点化

    2024-05-03 23:38:05       34 阅读
  7. 【C++】右值引用

    2024-05-03 23:38:05       39 阅读
  8. Golang 设计模式(行为型)

    2024-05-03 23:38:05       35 阅读
  9. 互斥关系和同步关系

    2024-05-03 23:38:05       34 阅读
  10. SDWebImage源码分析

    2024-05-03 23:38:05       27 阅读
  11. TypeScript 的 interface

    2024-05-03 23:38:05       31 阅读