uniapp连接BLE设备 进行读、写、notify源码

 * 初始化蓝牙设备          */
         openBluetoothAdapter() {
            uni.openBluetoothAdapter({
               success: e => {
                  console.log('初始化蓝牙成功:' + e.errMsg);
                  console.log(JSON.stringify(e));
                  this.isStop = false;
                  this.$set(this.disabled, 0, true);
                  this.$set(this.disabled, 1, false);
                  this.$set(this.disabled, 10, false);
                  this.getBluetoothAdapterState();
               },
               fail: e => {
                  console.log(e)
                  console.log('初始化蓝牙失败,错误码:' + (e.errCode || e.errMsg));
                  if (e.errCode !== 0) {
                     initTypes(e.errCode, e.errMsg);
                  }
               }
            });
         },
         /**
          * 开始搜索蓝牙设备          */
         startBluetoothDevicesDiscovery() {
            uni.startBluetoothDevicesDiscovery({
               success: e => {
                  console.log('开始搜索蓝牙设备:' + e.errMsg);
                  this.searchLoad = true;
                  this.$set(this.disabled, 1, true);
                  this.$set(this.disabled, 2, false);
                  this.$set(this.disabled, 3, false);
                  this.onBluetoothDeviceFound();
               },
               fail: e => {
                  console.log('搜索蓝牙设备失败,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
               }
            });
         },
         /**
          * 停止搜索蓝牙设备          */
         stopBluetoothDevicesDiscovery(types) {
            uni.stopBluetoothDevicesDiscovery({
               success: e => {
                  console.log('停止搜索蓝牙设备:' + e.errMsg);
                  if (types) {
                     this.$set(this.disabled, 1, true);
                  } else {
                     this.$set(this.disabled, 1, false);
                  }
                  this.$set(this.disabled, 2, true);
                  // this.$set(this.disabled, 3, true);
                  this.searchLoad = false;
               },
               fail: e => {
                  console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
               }
            });
         },
         /**
          * 发现外围设备          */
         onBluetoothDeviceFound() {
            uni.onBluetoothDeviceFound(devices => {
               console.log('开始监听寻找到新设备的事件');
               // this.$set(this.disabled, 3, false);
               this.getBluetoothDevices();
            });
         },
         /**
          * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。          */
         getBluetoothDevices() {
            uni.getBluetoothDevices({
               success: res => {
                  this.newDeviceLoad = false;
                  console.log('获取蓝牙设备成功:' + res.errMsg);
                  // console.log(JSON.stringify(res))
                  this.list = res.devices;
               },
               fail: e => {
                  console.log('获取蓝牙设备错误,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
               }
            });
         },
         /**
          * 获取本机蓝牙适配器状态          */
         getBluetoothAdapterState() {
            console.log('--->');
            uni.getBluetoothAdapterState({
               success: res => {
                  console.log(JSON.stringify(res));
                  this.adapterState = res;
               },
               fail: e => {
                  console.log('获取本机蓝牙适配器状态失败,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
               }
            });
         },
         /**
          * 连接低功耗蓝牙          */
         createBLEConnection() {
            let deviceId = this.equipment[0].deviceId;
            uni.showToast({
               title: '连接蓝牙...',
               icon: 'loading',
               duration: 99999
            });
            uni.createBLEConnection({
               // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
               deviceId,
               success: res => {
                  console.log(res);
                  console.log('连接蓝牙成功:' + res.errMsg);
                  // 连接设备后断开搜索 并且不能搜索设备
                  this.stopBluetoothDevicesDiscovery(true);
                  uni.hideToast();
                  uni.showToast({
                     title: '连接成功',
                     icon: 'success',
                     duration: 2000
                  });
                  this.$set(this.disabled, 3, true);
                  this.$set(this.disabled, 4, true);
                  this.$set(this.disabled, 5, false);
                  this.$set(this.disabled, 9, false);
                  this.connected = true;
               },
               fail: e => {
                  console.log('连接低功耗蓝牙失败,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
               }
            });
         },
         /**
          * 断开与低功耗蓝牙设备的连接          */
         closeBLEConnection() {
            let deviceId = this.equipment[0].deviceId;
            uni.closeBLEConnection({
               deviceId,
               success: res => {
                  console.log(res);
                  console.log('断开低功耗蓝牙成功:' + res.errMsg);
                  this.$set(this.disabled, 1, false);
                  this.$set(this.disabled, 3, true);
                  this.$set(this.disabled, 4, true);
                  this.$set(this.disabled, 5, true);
                  this.$set(this.disabled, 6, true);
                  this.$set(this.disabled, 7, true);
                  this.$set(this.disabled, 8, true);
                  this.$set(this.disabled, 9, true);
                  this.equipment = [];
                  this.servicesData = [];
                  this.characteristicsData = [];
               },
               fail: e => {
                  console.log('断开低功耗蓝牙成功,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
               }
            });
         },
         /**
          * 获取所有服务          */
         getBLEDeviceServices() {
            let deviceId = this.equipment[0].deviceId;
            console.log('获取所有服务的 uuid:' + deviceId);
            setTimeout(() => {
               uni.getBLEDeviceServices({
                  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                  deviceId,
                  success: res => {
                     console.log(JSON.stringify(res.services));
                     console.log('获取设备服务成功:' + res.errMsg);
                     this.$set(this.disabled, 7, true);
                     this.$set(this.disabled, 8, true);
                     this.showMaskType = 'service';
                     this.list = res.services;

                     this.characteristicsData = [];
                     if (this.list.length <= 0) {
                        toast('获取服务失败,请重试!');
                        return;
                     }
                     this.maskShow = true;
                  },
                  fail: e => {
                     console.log('获取设备服务失败,错误码:' + e.errCode);
                     if (e.errCode !== 0) {
                        initTypes(e.errCode);
                     }
                  }
               });
            }, 0)

         },
         /**
          * 获取某个服务下的所有特征值          */
         getBLEDeviceCharacteristics() {
            let deviceId = this.equipment[0].deviceId;
            let serviceId = this.servicesData[0].uuid;
            console.log(deviceId);
            console.log(serviceId);
            setTimeout(() => {
               uni.getBLEDeviceCharacteristics({
                  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                  deviceId,
                  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                  serviceId,
                  success: res => {
                     console.log(JSON.stringify(res));
                     console.log('获取特征值成功:' + res.errMsg);
                     this.$set(this.disabled, 7, true);
                     this.valueChangeData = {};
                     this.showMaskType = 'characteristics';
                     this.list = res.characteristics;
                     if (this.list.length <= 0) {
                        toast('获取特征值失败,请重试!');
                        return;
                     }
                     this.maskShow = true;
                  },
                  fail: e => {
                     console.log('获取特征值失败,错误码:' + e.errCode);
                     if (e.errCode !== 0) {
                        initTypes(e.errCode);
                     }
                  }
               });
            }, 0)

         },
         /**
          * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等          */
         onBLEConnectionStateChange() {
            uni.onBLEConnectionStateChange(res => {
               // 该方法回调中可以用于处理连接意外断开等异常情况
               console.log(`蓝牙连接状态 -------------------------->`);
               console.log(JSON.stringify(res));
               if (!res.connected) {
                  if (this.isStop) return;
                  console.log('断开低功耗蓝牙成功:');
                  this.$set(this.disabled, 1, false);
                  this.$set(this.disabled, 3, true);
                  this.$set(this.disabled, 4, true);
                  this.$set(this.disabled, 5, true);
                  this.$set(this.disabled, 6, true);
                  this.$set(this.disabled, 7, true);
                  this.$set(this.disabled, 8, true);
                  this.$set(this.disabled, 9, true);
                  this.searchLoad = false;
                  this.equipment = [];
                  this.servicesData = [];
                  this.characteristicsData = [];
                  this.valueChangeData = {};
                  toast('已经断开当前蓝牙连接');
               }
            });
         },
         /**
          * 订阅操作成功后需要设备主动更新特征值的 value,才会触发 uni.onBLECharacteristicValueChange 回调。          */
         notifyBLECharacteristicValueChange() {
            let deviceId = this.equipment[0].deviceId;
            let serviceId = this.servicesData[0].uuid;
            let characteristicId = this.characteristicsData[0].uuid;
            let notify = this.characteristicsData[0].properties.notify;
            console.log(deviceId);
            console.log(serviceId);
            console.log(characteristicId);
            console.log(notify);
            uni.notifyBLECharacteristicValueChange({
               state: true, // 启用 notify 功能
               // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
               deviceId,
               // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
               serviceId,
               // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
               characteristicId,
               success: (res) => {
                  console.log('notifyBLECharacteristicValueChange success:' + res.errMsg);
                  console.log(JSON.stringify(res));
                  this.onBLECharacteristicValueChange(this.deviceId);
               },
               fail: (res) => {
                  console.log('notifyBLECharacteristicValueChange success', res.errMsg);
                  this.onBLECharacteristicValueChange(this.deviceId);
               },
            });
         },
         ab2hex(buffer) {
            const hexArr = Array.prototype.map.call(
               new Uint8Array(buffer),
               function(bit) {
                  return ('00' + bit.toString(16)).slice(-2)
               }
            )
            return hexArr.join('')
         },
         /**
          * 监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。          */
         onBLECharacteristicValueChange() {
            // 必须在这里的回调才能获取
            uni.onBLECharacteristicValueChange((res) => {
               console.log('监听低功耗蓝牙设备的特征值变化事件成功');
               console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`);
               console.log(this.ab2hex(res.value));
               this.macAddress = res.deviceId;
               this.macValue = this.ab2hex(res.value);
               console.log('res.serviceId=>', res.serviceId);
               // this.valueChangeData.value = this.ab2hex(res.value);
               this.extraLine.push(this.macValue);
               this.valueChangeData = this.extraLine.join(' \n ');

            });
         },
         /**
          * 读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用          */
         readBLECharacteristicValue() {
            let deviceId = this.equipment[0].deviceId;
            let serviceId = this.servicesData[0].uuid;
            let characteristicId = this.characteristicsData[0].uuid;
            console.log("deviceId=>", deviceId);
            console.log("serviceId=>", serviceId);
            console.log('characteristicId=>', characteristicId);
            uni.readBLECharacteristicValue({
               // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
               deviceId,
               // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
               serviceId,
               // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
               characteristicId,
               success: (res) => {

                  console.log('读取设备数据值成功');
                  console.log(JSON.stringify(res));
                  //this.notifyBLECharacteristicValueChange();
                  this.onBLECharacteristicValueChange(this.deviceId);

               },
               fail: (res) => {
                  console.log('读取设备数据值失败,错误码:' + e.errCode);
                  if (e.errCode !== 0) {
                     initTypes(e.errCode);
                  }
                  this.onBLECharacteristicValueChange(this.deviceId);
               }
            });
            //this.onBLECharacteristicValueChange();
         },
         /**
          *     断开蓝牙模块          */
         closeBluetoothAdapter(OBJECT) {
            uni.closeBluetoothAdapter({
               success: res => {
                  console.log('断开蓝牙模块成功');
                  this.isStop = true;
                  this.$set(this.disabled, 0, false);
                  this.$set(this.disabled, 1, true);
                  this.$set(this.disabled, 2, true);
                  this.$set(this.disabled, 3, true);
                  this.$set(this.disabled, 4, true);
                  this.$set(this.disabled, 5, true);
                  this.$set(this.disabled, 6, true);
                  this.$set(this.disabled, 7, true);
                  this.$set(this.disabled, 8, true);
                  this.$set(this.disabled, 9, true);
                  this.$set(this.disabled, 10, true);
                  this.equipment = [];
                  this.servicesData = [];
                  this.characteristicsData = [];
                  this.valueChangeData = {};
                  this.adapterState = [];
                  this.searchLoad = false;
                  toast('断开蓝牙模块');
               }
            });
         }
      }
   };

   /**
    * 判断初始化蓝牙状态    */
   function initTypes(code, errMsg) {
      switch (code) {
         case 10000:
            toast('未初始化蓝牙适配器');
            break;
         case 10001:
            toast('未检测到蓝牙,请打开蓝牙重试!');
            break;
         case 10002:
            toast('没有找到指定设备');
            break;
         case 10003:
            toast('连接失败');
            break;
         case 10004:
            toast('没有找到指定服务');
            break;
         case 10005:
            toast('没有找到指定特征值');
            break;
         case 10006:
            toast('当前连接已断开');
            break;
         case 10007:
            toast('当前特征值不支持此操作');
            break;
         case 10008:
            toast('其余所有系统上报的异常');
            break;
         case 10009:
            toast('Android 系统特有,系统版本低于 4.3 不支持 BLE');
            break;
         default:
            toast(errMsg);
      }
   }

获取源码,欢迎关注公众号:MT5T21

### 回答1: 微信小程序是一种在微信平台上运行的应用程序,它具有轻量化、便捷性和高兼容性的特点。微信小程序可以通过蓝牙低功耗(BLE)协议连接外部设备,并向外部设备发送数据。以下是一个示例代码,演示如何在微信小程序中实现BLE设备连接与发送。 首先,在小程序的json配置文件中声明需要使用蓝牙能力: ```json { "permissions": { "bluetooth": true, "ble": true } } ``` 然后,在小程序的页面逻辑代码中执行以下步骤: 1. 开启蓝牙适配器并监听状态变化: ```js wx.openBluetoothAdapter({ success: function(res) { console.log("蓝牙适配器已打开"); // 监听蓝牙适配器状态变化 wx.onBluetoothAdapterStateChange(function(res) { console.log("蓝牙适配器状态变化", res); }); }, fail: function(res) { console.log("打开蓝牙适配器失败", res); } }); ``` 2. 开始搜索周围的蓝牙设备: ```js wx.startBluetoothDevicesDiscovery({ success: function(res) { console.log("开始搜索蓝牙设备"); // 监听蓝牙设备发现事件 wx.onBluetoothDeviceFound(function(res) { console.log("发现蓝牙设备", res.devices); // 可以通过设备的serviceUUIDs等信息筛选需要连接设备 // 根据条件筛选出需要连接设备后,调用stopBluetoothDevicesDiscovery停止搜索 }); }, fail: function(res) { console.log("开始搜索蓝牙设备失败", res); } }); ``` 3. 连接目标设备: ```js wx.createBLEConnection({ deviceId: "设备ID", success: function(res) { console.log("蓝牙设备连接成功"); // 连接成功后,可以调用getBLEDeviceServices获取设备的服务列表 }, fail: function(res) { console.log("蓝牙设备连接失败", res); } }); ``` 4. 向设备发送数据: ```js wx.writeBLECharacteristicValue({ deviceId: "设备ID", serviceId: "服务UUID", characteristicId: "特征值UUID", value: "发送的数据", success: function(res) { console.log("数据发送成功"); }, fail: function(res) { console.log("数据发送失败", res); } }); ``` 以上就是一个简单的示例代码,演示了如何在微信小程序中实现BLE设备连接与发送。请注意,实际应用中可能还需要处理设备发现、服务筛选、数据解析等其他逻辑,并适配不同的设备和场景。 ### 回答2: 微信小程序是一种在微信客户端中运行的应用程序,它可以通过微信平台提供的接口与其他设备进行连接和通信。在微信小程序中连接和发送数据BLE(Bluetooth Low Energy)设备源码如下: 1. 首先,我们需要在小程序的app.json文件中配置微信客户端的权限,使其支持蓝牙功能。 ``` "permissions": { "ble": true } ``` 2. 在小程序的页面中创建一个按钮或者其他交互元素,用于触发蓝牙设备连接事件。 ``` <button bindtap="connectDevice">连接设备</button> ``` 3. 在小程序对应的js文件中,编连接蓝牙设备的相关代码。首先,获取蓝牙适配器实例。 ``` wx.openBluetoothAdapter({ success: function (res) { // 成功打开蓝牙适配器 // 在这里可以进行后续操作,如搜索附近的设备 }, fail: function (res) { // 打开蓝牙适配器失败 } }); ``` 4. 接下来,可以使用蓝牙适配器的方法搜索附近的设备。 ``` wx.startBluetoothDevicesDiscovery({ success: function (res) { // 成功开始搜索 // 在这里可以获取搜索到的设备列表,选择需要连接设备 }, fail: function (res) { // 开始搜索失败 } }); ``` 5. 当选择需要连接设备后,可以调用蓝牙适配器的connect方法进行设备连接。 ``` wx.createBLEConnection({ deviceId: deviceId, success: function (res) { // 连接设备成功 // 在这里可以进行后续操作,如发送数据设备 }, fail: function (res) { // 连接设备失败 } }); ``` 6. 连接成功后,可以使用蓝牙适配器的write方法发送数据设备。需要注意的是,发送的数据必须是ArrayBuffer类型。 ``` wx.writeBLECharacteristicValue({ deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId, value: buffer, success: function (res) { // 发送数据成功 }, fail: function (res) { // 发送数据失败 } }); ``` 以上就是微信小程序连接和发送数据BLE设备的简要源码解析。需要根据具体的业务需求和设备特性进行相应的开发和调试。 ### 回答3: 微信小程序是一种能够在微信中运行的轻量级应用程序,它可以通过连接BLE(蓝牙低功耗)设备与之进行通信。在微信小程序中,可以使用wx.createBLEConnection方法来进行BLE设备连接。 要连接BLE设备,首先需要通过wx.openBluetoothAdapter方法打开蓝牙适配器,确保用户已经授权蓝牙权限。然后,使用wx.startBluetoothDevicesDiscovery方法开始搜索附近的蓝牙设备,并监听wx.onBluetoothDeviceFound回调事件来获取扫描到的蓝牙设备信息。 当发现需要连接BLE设备后,可以使用wx.createBLEConnection方法来与设备建立连接。该方法接收一个参数,即BLE设备的deviceId。成功建立连接后,可以通过监听wx.onBLEConnectionStateChanged事件获取连接状态。 连接建立后,可以使用wx.writeBLECharacteristicValue方法来发送数据BLE设备。该方法接收四个参数,即连接deviceId、serviceId、characteristicsId和data。其中,services和characteristics需要通过wx.getBLEDeviceServices和wx.getBLEDeviceCharacteristics方法获取。 要注意的是,在发送数据之前,需要先通过wx.notifyBLECharacteristicValueChange方法启用notify功能,并监听wx.onBLECharacteristicValueChange回调事件来接收设备返回的数据。 以上是关于微信小程序BLE设备连接与发送的简介,涉及的源码实现较为复杂,还需根据具体设备和业务需求进行进一步的开发与调试。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值