微信小程序连接蓝牙模块实现数据发送

前言

         蓝牙设备是使用蓝牙通讯技术来实现特定功能的设备。蓝牙设备内部包含蓝牙服务,其中包括服务、特性和属性。每个服务和特性都有唯一的UUID标识,而每个特性又具备read、write、notify等属性。在使用蓝牙服务时,实际上是针对不同属性的特性进行操作。操作步骤为:通过蓝牙通讯建立设备连接,找到相应的服务,确定该服务下的特定特性,并根据特性的属性执行具体操作。  

蓝牙设备通常包括两个主要角色:蓝牙主设备和蓝牙从设备。

  • 蓝牙主设备(Bluetooth Master):负责发起蓝牙连接,并控制连接过程。例如,智能手机、电脑等可以作为蓝牙主设备。

  • 蓝牙从设备(Bluetooth Slave):被动地等待蓝牙连接请求,并与蓝牙主设备进行通信。例如,蓝牙耳机、智能手表、传感器等可以作为蓝牙从设备。

1.Bluetooth Address

        蓝牙地址(Bluetooth Address)是蓝牙设备的唯一标识符,用于在蓝牙通信中唯一标识一个蓝牙设备。蓝牙地址通常由48位的二进制数表示,也可以以十六进制形式进行显示。

        蓝牙地址的格式通常是XX:XX:XX:XX:XX:XX(每组XX表示两位十六进制数)。这个地址对于每个蓝牙设备来说都是唯一的,类似于设备的身份证号码。蓝牙地址由设备的制造商在生产过程中分配,并且不能被更改。

2.UUID(Universal User Identifier)

        UUID(通用唯一标识符,全称 Universal Unique Identifier)是一种128位的二进制编码格式,用于在计算机系统中唯一标识信息。UUID的设计目的是为了在分布式系统中,标识信息实体,而不受到名称重复、分配冲突等问题的影响。

        在蓝牙通信中,UUID用于唯一标识蓝牙设备提供的服务、特征和属性。

2.1. 服务(Service)

        服务是蓝牙设备提供的一组相关功能或操作。每个服务都有一个唯一的UUID来进行标识。一个蓝牙设备可以提供多个服务。

2.2. 特性(Characteristic)

        特征是服务中的一个具体功能单元,它描述了某种数据类型和操作方式。每个特征也有一个唯一的UUID来进行标识。一个服务可以包含多个特征。

2.3.属性(Property)

        属性是特征的属性或数据值,可以读取、写入或订阅。属性包括值、权限和描述等信息。通过读取或写入属性,可以与蓝牙设备进行数据交换。

Read: 读属性,具有该属性的UUID 是可读的,也就是说这个属性允许MASTER读取信息。

Write: 写属性, 具体该属性的 UUID 是可以接收写入数据的。通常手机发送数据给蓝模块就是通过这个属性完成的。

Notify: 通知属性, 具有该属性的 UUID是可以发送通知的,也就是说具有这个属性的特性可以发送信息给MASER。

API函数介绍

  1. 获取权限:在小程序的app.json文件中,需要在"permission"字段中添加"bluetooth"权限,并在用户授权后获取蓝牙权限。

  2. 初始化蓝牙适配器:使用wx.openBluetoothAdapter()函数初始化蓝牙适配器,并监听适配器状态的变化。

  3. 开启蓝牙搜索:使用wx.startBluetoothDevicesDiscovery()函数开始搜索附近的蓝牙设备,并监听设备列表的变化。

  4. 获取蓝牙设备列表:使用wx.getBluetoothDevices()函数获取搜索到的蓝牙设备列表,并显示给用户选择。

  5. 连接蓝牙设备:使用wx.createBLEConnection()函数连接用户选择的蓝牙设备,并监听连接状态的变化。

  6. 获取蓝牙设备的服务列表:使用wx.getBLEDeviceServices()函数获取蓝牙设备的服务列表,并显示给用户选择。

  7. 获取蓝牙设备的特征值列表:使用wx.getBLEDeviceCharacteristics()函数获取蓝牙设备的特征值列表,并显示给用户选择。

  8. 监听特征值变化:使用wx.onBLECharacteristicValueChange()函数监听蓝牙设备特征值的变化,并处理接收到的数据。

  9. 读取特征值数据:使用wx.readBLECharacteristicValue()函数读取蓝牙设备特征值的数据。

  10. 向特征值写入数据:使用wx.writeBLECharacteristicValue()函数向蓝牙设备特征值写入数据。

小程序连接蓝牙

首先你要知道自己的蓝牙地址(询问商家或者通过手机连接之后查看),然后通过下面这一段程序去获取蓝牙设备的服务列表,和特征值列表

function initBluetooth(deviceId) {  wx.openBluetoothAdapter({    success: function(res) {      console.log('蓝牙适配器初始化成功');      wx.startBluetoothDevicesDiscovery({        success: function(res) {          console.log('开始搜索蓝牙设备');          wx.onBluetoothDeviceFound(function(res) {            console.log('发现新设备:', res.devices);            var devices = res.devices;            for (var i = 0; i < devices.length; i++) {              var device = devices[i];              if (device.deviceId == deviceId) {                wx.stopBluetoothDevicesDiscovery(); // 停止搜索附近的蓝牙外围设备                wx.createBLEConnection({                  deviceId: deviceId,                  success: function(res) {                    console.log('连接蓝牙设备成功');                    wx.getBLEDeviceServices({                      deviceId: deviceId,                      success: function(res) {                        console.log('获取蓝牙设备的服务列表成功:', res.services);                        for (var j = 0; j < res.services.length; j++) {                          var service = res.services[j];                          wx.getBLEDeviceCharacteristics({                            deviceId: deviceId,                            serviceId: service.uuid,                            success: function(res) {                              console.log('获取蓝牙设备的特征值列表成功:', res.characteristics);                            }                          });                        }                      }                    });                  },                  fail: function(res) {                    console.log('连接蓝牙设备失败:', res);                  }                });                break;              }            }          });        }      });    },    fail: function(res) {      console.log('蓝牙适配器初始化失败:', res);    }  });}

通过上述代码获得的设备ID和服务UUID填入以下代码即可实现数据发送

Page({  data: {    deviceID: 'xxxxxxxxxxxx' // 替换为实际的设备ID  },  // 初始化蓝牙适配器  initBluetoothAdapter: function () {    var that = this;    wx.openBluetoothAdapter({      success: function (res) {        console.log('蓝牙适配器初始化成功');        that.getBluetoothAdapterState();      },      fail: function (res) {        console.log('蓝牙适配器初始化失败', res);      }    });  },  // 获取蓝牙适配器状态  getBluetoothAdapterState: function () {    var that = this;    wx.getBluetoothAdapterState({      success: function (res) {        if (res.available) {          console.log('蓝牙适配器可用');          that.startBluetoothDevicesDiscovery();        }      }    });  },  // 开始搜索蓝牙设备  startBluetoothDevicesDiscovery: function () {    var that = this;    wx.startBluetoothDevicesDiscovery({      success: function (res) {        console.log('开始搜索蓝牙设备');        that.onBluetoothDeviceFound();        setTimeout(function () {          that.stopBluetoothDevicesDiscovery();        }, 5000); // 扫描时间为5秒      }    });  },  // 监听蓝牙设备发现事件  onBluetoothDeviceFound: function () {    wx.onBluetoothDeviceFound(function (devices) {      console.log('发现新设备', devices);    });  },  // 停止扫描设备  stopBluetoothDevicesDiscovery: function () {    wx.stopBluetoothDevicesDiscovery({      success: function (res) {        console.log('停止扫描设备');        wx.createBLEConnection({          deviceId: that.data.deviceID,          success: function (res) {            console.log('成功连接设备', res);            that.getBLEDeviceServices();          }        });      }    });  },  // 获取连接设备的服务  getBLEDeviceServices: function () {    var that = this;    wx.getBLEDeviceServices({      deviceId: that.data.deviceID,      success: function (res) {        console.log('获取设备服务成功', res.services);        that.getBLEDeviceCharacteristics(res.services[0].uuid);      }    });  },  // 获取连接设备具有读写功能服务的所有特征值  getBLEDeviceCharacteristics: function (serviceId) {    var that = this;    wx.getBLEDeviceCharacteristics({      deviceId: that.data.deviceID,      serviceId: serviceId,      success: function (res) {        console.log('获取特征值成功', res.characteristics);        that.notifyBLECharacteristicValueChange(res.characteristics[0].uuid);      }    });  },  // 启用蓝牙设备特征值变化  notifyBLECharacteristicValueChange: function (characteristicId) {    var that = this;    wx.notifyBLECharacteristicValueChange({      state: true, // 启用通知      deviceId: that.data.deviceID,      serviceId: 'serviceId', // 实际的服务UUID      characteristicId: characteristicId,      success: function (res) {        console.log('启用特征值变化成功', res);        that.onBLECharacteristicValueChange(characteristicId);      }    });  },  // 接收蓝牙发送的数据  onBLECharacteristicValueChange: function (characteristicId) {    wx.onBLECharacteristicValueChange(function (characteristic) {      console.log('接收到数据', characteristic.value);    });  },  // 向蓝牙写入数据  writeBLECharacteristicValue: function (characteristicId) {    var buffer = new ArrayBuffer(1);    var dataView = new DataView(buffer);    dataView.setUint8(0, 0x01);    wx.writeBLECharacteristicValue({      deviceId: that.data.deviceID,      serviceId: 'serviceId', // 实际的服务UUID      characteristicId: characteristicId,      value: buffer,      success: function (res) {        console.log('向蓝牙写入数据成功', res);      }    });  },  // 开始蓝牙功能  startBluetooth: function () {    var that = this;    that.initBluetoothAdapter();  }});



来源:春哥技术博客,欢迎分享,转载请注明出处。(欢迎加春哥团队客服微信号:taike668)

本文地址:https://www.cgtblog.com/cgymlt/10782.html
上一篇:微信小程序 - 蓝牙连接      下一篇:“5.25秒变0.023秒:小程序图片优化全攻