• uniapp微信小程序蓝牙连接与设备数据对接


    蓝牙连接并通信方法封装大致步骤。

    1. 初始化蓝牙并搜索;
    2. 获取并启用service服务;
    3. 数据读取和监听设备返回数据
    需要使用uniapp官方提供api:
    // 关闭蓝牙
    uni.closeBluetoothAdapter({})
    // 打开蓝牙
    uni.openBluetoothAdapter({})
    // 搜索附近的蓝牙
    uni.startBluetoothDevicesDiscovery({})
    // 停止搜索
    uni.stopBluetoothDevicesDiscovery({})
    // 连接低功耗BLE蓝牙
    uni.createBLEConnection({})
    // 获取蓝牙设备所有服务(service)
    uni.getBLEDeviceServices({})
    // 获取蓝牙特征值
    uni.getBLEDeviceCharacteristics({})
    // 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值
    uni.notifyBLECharacteristicValueChange({})
    // 监听低功耗蓝牙设备的特征值变化事件
    uni.onBLECharacteristicValueChange({})
    // 读取低功耗蓝牙设备的特征值的二进制数据值
    uni.readBLECharacteristicValue({})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    1、开启蓝牙适配器初始化蓝牙模块,获取手机蓝牙是否打开

    const getBluetoothState = () => {
    	return new Promise((resolve, reject) => {
    		uni.openBluetoothAdapter({
    			mode: 'central', // 主机模式
    			success: (r) => {
    				console.log("蓝牙初始化成功");
    				// 获取蓝牙的匹配状态
    				uni.getBluetoothAdapterState({
    					success: function(row) {
    						console.log('蓝牙状态:', row.available);
    						if (row.available) {
    							// 蓝牙连接成功,开启蓝牙设备搜索
    							resolve();
    						} else {
    							// 请开启蓝牙
    							uni.showToast({
    								title: "请开启蓝牙",
    								icon: 'none',
    								duration: 2000
    							});
    							reject();
    						}
    					},
    					fail: function(err) {
    						// 请开启蓝牙
    						uni.showToast({
    							title: "请开启蓝牙",
    							icon: 'none',
    							duration: 2000
    						});
    						reject();
    					}
    				})
    			},
    			fail: () => {
    				// 请开启蓝牙
    				uni.showToast({
    					title: "请开启蓝牙",
    					icon: 'none',
    					duration: 2000
    				});
    				reject();
    			}
    		});
    	});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    2、开启蓝牙设备搜索

    const discoveryBluetooth = () => {
    	return new Promise((resolve) => {
    		uni.startBluetoothDevicesDiscovery({
    			success(res) {
    				uni.showLoading({
    	                title: "正在搜索设备",
    	                icon:"none",
    	                duration: 2000
    	            });
    				console.log('搜索蓝牙外围设备完成', res)
    				setTimeout(() => {
    					// 监听寻找到的蓝牙设备
    					resolve();
    				}, 2000);
    			}
    		});
    	});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3、获取搜索到的设备信息

    const getBluetoothDevices = () => {
    	return new Promise((resolve, reject) => {
    		uni.getBluetoothDevices({
    			success(res) {
    				// 过滤掉name为空或者未知设备的设备
    				let devices = res.devices.filter(function(obj) {
    					return obj.name !== "" && obj.name !== "未知设备"
    				});
    				devices && devices.forEach(item => {
    					// 获取指定连接deviceId
    					if(item.name && item.name.substring(0, 5) === 'aaaa-'){
    						// aaaa-*********蓝牙设备型号,根据需求选择设备型号
    						// item.deviceId;
    					}
    				});
    			},
    			fail: function() {
    				console.log('搜索蓝牙设备失败');
    				reject();
    			},
    			complete: function() {
    				console.log("蓝牙搜索完成");
    				resolve();
    			}
    		});
    	});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    4、关闭蓝牙搜索

    const stopDiscoveryBluetooth = () => {
    	uni.stopBluetoothDevicesDiscovery({
    		success(r) {
    			console.log("停止搜索蓝牙设备", r);
    		}
    	});
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5、连接蓝牙

    const connectBluetooth = () => {
    	return new Promise((resolve, reject) => {
    		uni.createBLEConnection({
    			deviceId: deviceId, // 设备id
    			success() {
    				// 蓝牙连接成功后关闭蓝牙搜索并获取服务id
    				stopDiscoveryBluetooth();
    				resolve();
    				// 获取服务id
    				getServiceId();
    			},
    			fail() {
    				console.log("蓝牙连接失败");
    				reject();
    			}
    		});
    	});
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    6、获取服务id

    const getServiceId = () => {
    	uni.getBLEDeviceServices({
    		deviceId: deviceId,
    		success(res) {
    			console.log("获取服务Id", res)
    			// serviceId固定,获取蓝牙设备某个服务中的所有特征值【读写属性】
    			let model = res.services[0];
    			serviceId = model.uuid;
    			// 调用蓝牙监听和写入功能
    			getCharacteId();
    		},
    		fail(err){
    			console.log('获取服务失败', err);
    		}
    	})
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    7、获取蓝牙低功耗设备某个服务中所有特征

    const getCharacteId = () => {
    	uni.getBLEDeviceCharacteristics({
    		deviceId: deviceId, // 蓝牙设备id
    		serviceId: serviceId, // 蓝牙服务UUID
    		success(res) {
    			console.log('数据监听', res);
    			res.characteristics.forEach(item => {
    				// 003
    				if (item.properties.notify === true) {
    					// 监听
    					notify = item.uuid;
    				}
    				// 002
    				if (item.properties.write === true) {
    					// 写入
    					let writeId = item.uuid;
    				}
    			});
    		},
    		fail(err) {
    			console.log("数据监听失败", err)
    		}
    	})
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    8、监听设备返回数据,启用低功耗蓝牙设备特征值变化时的notify功能

    const startNotice = () => {
    	uni.notifyBLECharacteristicValueChange({
    		characteristicId: notify,
    		deviceId: deviceId,
    		serviceId: serviceId,
    		state: true,
    		success(res) {
    			// 监听低功耗蓝牙设备的特征值变化
    			uni.onBLECharacteristicValueChange(result => {
    				console.log("监听低功耗蓝牙设备的特征值变化", result);
    				if (result.value) {
    					console.log('设备返回数据', result.value)
    				}
    			})
    		}
    	});
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    9、向蓝牙设备发送数据

    const writeData = (buffer) => {
    	return new Promise((resolve, reject) => {
    		uni.writeBLECharacteristicValue({
    			characteristicId: uni.getStorageSync("writeId"),
    			deviceId: deviceId,
    			serviceId: serviceId,
    			value: buffer,
    			success(res) {
    				console.log("writeBLECharacteristicValue success", res);
    				resolve();
    			},
    			fail(err) {
    				console.log("报错了", err);
    				reject();
    			}
    		});
    	});
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    封装完整方法:
    import { TextDecoder } from 'text-encoding-utf-8';
    let bluetoothOpen = false; // 手机蓝牙是否打开
    let bluetoothConnect = false; // 设备和蓝牙是否连接
    let isHaveDevice = false; // 是否查找到设备
    let deviceId = null; // 设备id
    let serviceId = null; // 服务id
    let notify = null; // 监听uuid
    let writeId = null; // 写入uuid
    /**
     * 获取手机蓝牙是否打开
     */
    const getBluetoothState = () => {
    	// 主机模式
    	return new Promise((resolve, reject) => {
    		uni.openBluetoothAdapter({
    			mode: 'central',
    			success: (r) => {
    				console.log("蓝牙初始化成功");
    				// 获取蓝牙的匹配状态
    				uni.getBluetoothAdapterState({
    					success: function(row) {
    						console.log('蓝牙状态:', row.available);
    						if (row.available) {
    							bluetoothOpen = true;
    							resolve();
    						} else {
    							// 请开启蓝牙
    							bluetoothOpen = false;
    							bluetoothConnect = false;
    							reject();
    						}
    					},
    					fail: function(err) {
    						// 请开启蓝牙
    						bluetoothOpen = false;
    						bluetoothConnect = false;
    						reject();
    					}
    				})
    			},
    			fail: () => {
    				// 请开启蓝牙
    				bluetoothOpen = false;
    				bluetoothConnect = false;
    				reject();
    			}
    		});
    	});
    };
    /**
     * 开始搜索蓝牙设备
     */
    const discoveryBluetooth = () => {
    	return new Promise((resolve) => {
    		uni.startBluetoothDevicesDiscovery({
    			success(res) {
    				console.log('搜索蓝牙外围设备完成', res)
    				setTimeout(() => {
    					resolve();
    				}, 2000);
    			}
    		});
    	})
    };
    // 关闭蓝牙搜索
    const stopDiscoveryBluetooth = () => {
    	uni.stopBluetoothDevicesDiscovery({
    		success(r) {
    			console.log("停止搜索蓝牙设备", r);
    		}
    	});
    };
    /**
     * 获取搜索到的设备信息
     */
    const getBluetoothDevices = () => {
    	return new Promise((resolve, reject) => {
    		uni.getBluetoothDevices({
    			success(res) {
    				bluetoothConnect = false;
    				// 过滤掉name为空或者未知设备的设备
    				let devices = res.devices.filter(function(obj) {
    					return obj.name !== "" && obj.name !== "未知设备"
    				});
    				devices && devices.forEach(item => {
    					if(item.name && item.name.substring(0, 5) === 'aaaa-'){
    						deviceId = item.deviceId;
    					}
    				});
    			},
    			fail: function() {
    				console.log('搜索蓝牙设备失败');
    				bluetoothConnect = false;
    				reject();
    			},
    			complete: function() {
    				console.log("蓝牙搜索完成");
    				// 是否具有当前设备
    				if (deviceId) {
    					isHaveDevice = true;
    				} else {
    					isHaveDevice = false;
    				}
    				resolve(isHaveDevice);
    			}
    		});
    	});
    }
    /**
     * 连接蓝牙
     * deviceId 蓝牙设备id
     */
    const connectBluetooth = () => {
    	return new Promise((resolve, reject) => {
    		uni.createBLEConnection({
    			deviceId: deviceId, // 设备id
    			success() {
    				bluetoothConnect = true;
    				// 蓝牙连接成功后关闭蓝牙搜索
    				stopDiscoveryBluetooth();
    				resolve();
    				// 获取服务id
    				getServiceId();
    			},
    			fail() {
    				bluetoothConnect = false;
    				console.log("蓝牙连接失败");
    				reject();
    			}
    		});
    	});
    };
    // 获取服务id
    const getServiceId = () => {
    	uni.getBLEDeviceServices({
    		deviceId: deviceId,
    		success(res) {
    			console.log("获取服务Id", res)
    			let model = res.services[0];
    			serviceId = model.uuid;
    			// 调用蓝牙监听和写入功能
    			getCharacteId();
    		}
    	})
    };
    // 获取蓝牙低功耗设备某个服务中所有特征
    const getCharacteId = () => {
    	uni.getBLEDeviceCharacteristics({
    		deviceId: deviceId, // 蓝牙设备id
    		serviceId: serviceId, // 蓝牙服务UUID
    		success(res) {
    			console.log('数据监听', res);
    			res.characteristics.forEach(item => {
    				// 003
    				if (item.properties.notify === true) {
    					// 监听
    					notify = item.uuid;
    					startNotice();
    				}
    				// 002
    				if (item.properties.write === true) {
    					// 写入
    					let writeId = item.uuid;
    					uni.setStorageSync("writeId", item.uuid);
    				}
    			});
    		},
    		fail(err) {
    			console.log("数据监听失败", err)
    		}
    	})
    };
    // 启用低功耗蓝牙设备特征值变化时的notify功能
    const startNotice = () => {
    	uni.notifyBLECharacteristicValueChange({
    		characteristicId: notify,
    		deviceId: deviceId,
    		serviceId: serviceId,
    		state: true,
    		success(res) {
    			// 监听低功耗蓝牙设备的特征值变化
    			uni.onBLECharacteristicValueChange(result => {
    				console.log("监听低功耗蓝牙设备的特征值变化", result);
    				if (result.value) {
    					let decoder = new TextDecoder('utf-8');
    					let data = decoder.decode(result.value);
    					console.log('帽子返回数据', data)
    				}
    			})
    		}
    	});
    };
    // 蓝牙发送数据
    const writeData = (buffer) => {
    	return new Promise((resolve, reject) => {
    		uni.writeBLECharacteristicValue({
    			characteristicId: uni.getStorageSync("writeId"),
    			deviceId: deviceId,
    			serviceId: serviceId,
    			value: buffer,
    			success(res) {
    				console.log("writeBLECharacteristicValue success", res);
    				resolve();
    			},
    			fail(err) {
    				console.log("报错了", err);
    				reject();
    			}
    		});
    	});
    };
    export default {
    	getBluetoothState,
    	discoveryBluetooth,
    	stopDiscoveryBluetooth,
    	getBluetoothDevices,
    	connectBluetooth,
    	getServiceId,
    	getCharacteId,
    	startNotice,
    	writeData
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    使用案例:
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
  • 相关阅读:
    强化学习和推荐系统的结合应用
    【Docker】Docker:解析容器化技术的利器与在Linux中的关键作用
    1认识一下防火墙
    面试打底稿② 专业技能的第二部分
    探索visionOS:TabView
    解决线上OutOfMemoryError: GC overhead limit exceeded问题
    如何从零开始拆解uni-app开发的vue项目(一)
    基于JAVA球迷信息交流论坛计算机毕业设计源码+数据库+lw文档+系统+部署
    SQLines数据迁移工具
    Linux platform总线驱动基础知识
  • 原文地址:https://blog.csdn.net/weixin_44242600/article/details/133642834