Uniapp低功耗蓝牙操作实例

  • Post author:
  • Post category:uniapp


uniapp低功耗蓝牙在移动端使用较为平常,本文相较于官方文档介绍一下低功耗蓝牙的操作案例,即取即用。低功耗蓝牙虽工作原理与经典蓝牙类似,但是有着独特的架构体系,所以LE独立出来成为一种蓝牙形态。不过LE和经典蓝牙使用相同的2.4G无线电频率,可以共享同一个天线,组成双模蓝牙。

在这里插入图片描述




扫描蓝牙设备

Search() {
  var that = this;
  console.log("search:", that.searching);
  if (!that.searching) {
    //关闭现有的蓝牙连接
    uni.closeBluetoothAdapter({
      complete: function (res) {
        console.log("关闭蓝牙模块-----------------------------------------");
        console.log(res);
        //打开蓝牙适配
        uni.openBluetoothAdapter({
          success: function (res) {
            console.log(
              "初始化蓝牙模块----------------------------------------"
            );
            console.log(res);
            uni.getBluetoothAdapterState({
              success: function (res) {
                console.log(
                  "获取本机蓝牙适配器状态----------------------------------------"
                );
                console.log(res);
              },
            });

            //开始搜索蓝牙设备
            uni.startBluetoothDevicesDiscovery({
              allowDuplicatesKey: false,
              success: function (res) {
                console.log(
                  "搜索设备-----------------------------------------"
                );
                that.onBluetoothDeviceFound();
                that.searching = true;
                that.devicesList = [];
              },
            });
          },
          fail: function (res) {
            console.log("############");
            console.log(res);
            setTimeout(() => {
              uni.showModal({
                title: "温馨提示",
                content: "蓝牙未打开,请打开后再连接",
                showCancel: false,
                confirmColor: "#008fd6",
              });
              that.isSearch = false;
            }, 1000);
          },
        });
      },
    });
  } else {
    uni.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("停止搜索设备-----------------------------------------");
        console.log(res);
        that.searching = false;
      },
    });
  }
}




连接设备

ConnectByID(item, index) {
				var that = this;
				// console.log(item);
				that.connectedDeviceId = item.deviceId;
				uni.setStorageSync('pageName', item.name);
				uni.setStorageSync('connectedDeviceId', that.connectedDeviceId)
				 uni.showLoading({
				 	title: '正在连接设备...',
				 })

				uni.createBLEConnection({
					deviceId: item.deviceId,
					success(res) {
						uni.hideLoading()
						uni.showToast({
							title: '连接成功',
							duration: 2000,
							icon: "none"
						});
						// that.open()
						console.log("已连接设备----------------------------------------");
						that.getBLEDeviceServices(); //获取特征值

					},
					fail(res) {
						console.log(res)
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '连接失败',
							showCancel: false
						})
					}
				})
				// }
			},




获取设备UUID

			//获取蓝牙设备的服务uuid    //服务uuid可能有多个
			getBLEDeviceServices() {
				var that = this;
				setTimeout(() => {
					//获取数据可能会有延迟
					uni.getBLEDeviceServices({
						deviceId: that.connectedDeviceId,
						success: function(res) {
							console.log(
								"获取蓝牙设备的服务uuid:" + JSON.stringify(res.services)
							);
							that.services = res.services;
							that.serviceId = res.services[2].uuid;
							that.deviceId = that.connectedDeviceId;
							uni.setStorageSync("serviceId", that.serviceId);
							that.getBLEDeviceCharacteristics();
						},
						fail(res) {
							console.log(res);
						},
					});
				}, 3000);
			},




获取蓝牙特征值开始监听

// 根据服务uuid获取蓝牙特征值开始监听写入和接收
			getBLEDeviceCharacteristics() {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.connectedDeviceId,
					serviceId: that.serviceId,
					success: function(res) {
						console.log(
							"获取蓝牙设备的特征" + JSON.stringify(res.characteristics)
						);
						for (var i = 0; i < res.characteristics.length; i++) {
							if (res.characteristics[i].properties.notify === true) {
								that.characteristics = res.characteristics[i];
								that.characteristicId = res.characteristics[i].uuid;
							}

							if (res.characteristics[i].properties.write === true) {
								that.characteristics = res.characteristics[i];
								that.writeId = res.characteristics[i].uuid;
							}
						}
						uni.setStorageSync("characteristicId", that.characteristicId);
						uni.setStorageSync("writeId", that.writeId);
						that.notifyBLECharacteristicValueChange(); //7.0,开始侦听数据
					},
				});
			},




开启蓝牙数据监听

notifyBLECharacteristicValueChange() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,

					success: function(res) {
						console.log("启用notify成功");
						that.onBLECharacteristicValueChange();
					},
					fail: function(res) {
						console.log("启用notify失败");
					},
				});
			},




接收处理数据

			//设备返回数据的接收
			onBLECharacteristicValueChange() {
				var that = this;
				uni.onBLECharacteristicValueChange((res) => {
					// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过这个方法转换成字符串
					var resHex = that.ab2hex(res.value);
					// that.dealWithData(resHex);
					console.log("接收数据:" + resHex);
					var hexArray = stickyBag(resHex);
					for (let s of hexArray) {
						//处理数据
					}
				});
			},




监听寻找新设备

			//监听寻找到新设备的事件
			onBluetoothDeviceFound() {
				var that = this;
				console.log("打开设备监听");
				uni.onBluetoothDeviceFound(function(devices) {
					var reg = new RegExp(/[^\s]+/g);
					if (devices.devices) {
						if (devices.devices[0].name.match(reg)) {
							console.log(devices.devices[0]);
							that.devicesList.push(devices.devices[0]);
						}
					}
				});
			},




监听蓝牙状态

onBLEConnectionStateChange() {
				var that = this;
				uni.onBLEConnectionStateChange(function(res) {
					that.connected = res.connected;
					if (!that.connected) {
						console.log("蓝牙已断开");
						uni.createBLEConnection({
							// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
							deviceId: that.connectedDeviceId,
							success(res) {
								that.getBLEDeviceServices();
								//获取该设备地址
								console.log("蓝牙重新连接" + JSON.stringify(res));
							},
							fail(res) {
								console.log("蓝牙重新连接失败" + JSON.stringify(res));
							},
						});
					} else {
						console.log("蓝牙连接成功");
					}
				});
			},

低功耗蓝牙相较于传统蓝牙,连接速度更快,接收成功后会自动断开,下一次连接的时候再激活就可以了



版权声明:本文为qq_43774332原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。