uniapp 小程序 蓝牙 兼容Android和IOS 微信小程序和支付宝小程序

本文介绍了在微信小程序中使用JavaScript操作手机蓝牙的功能,包括检测蓝牙状态、搜索设备、连接设备、获取服务ID和特征ID、监听和写入数据以及断开连接的详细步骤。
摘要由CSDN通过智能技术生成

ly.js

// 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
let timer = null
let time = 0 //时间
/**
 * 获取手机蓝牙是否打开
 */
const getBluetoothState = () => {
	// 主机模式
	return new Promise((resolve, reject) => {
		// mode: 'central',
		uni.openBluetoothAdapter({
			success: (r) => {
				console.log("蓝牙初始化成功");
				// 获取蓝牙的匹配状态
				uni.getBluetoothAdapterState({
					success: function(row) {
						console.log('蓝牙状态:', row.available);
						if (row.available) {
							bluetoothOpen = true;
							getLocation().then(res => {
								console.log('4444');
								resolve();
							}).catch(err => {

								bluetoothOpen = false;
								bluetoothConnect = false;
								reject();
							})

						} else {
							// 请开启蓝牙
							uni.showToast({
								title: '请打开蓝牙',
								icon: 'none'
							})
							bluetoothOpen = false;
							bluetoothConnect = false;

							reject();
						}
					},
					fail: function(err) {
						// 请开启蓝牙
						uni.showToast({
							title: '请打开蓝牙',
							icon: 'none'
						})
						bluetoothOpen = false;
						bluetoothConnect = false;
						reject();
					}
				})
			},
			fail: (err) => {
				// 请开启蓝牙
				console.log('蓝牙初始化失败', err);
				if (err.errno == 103) {
					uni.showModal({
						title: '温馨提示',
						content: '您已拒绝授权,是否去设置打开?',
						confirmText: "确认",
						cancelText: "取消",
						success: function(res) {
							// console.log(res);
							if (res.confirm) {
								uni.openSetting({
									success: (res) => {
										console.log(res, '设置');
										// res.authSetting[scope] = true
										// resolve()
									}
								});
							}
						},

					});
				} else if (err.errCode == 10001) {

					uni.showToast({
						title: '请前往手机设置,打开此APP蓝牙权限',
						icon: 'none'
					})

				} else {
					uni.showToast({
						title: '请打开手机蓝牙',
						icon: 'none'
					})
				}
				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 = (deviceName) => {
	return new Promise((resolve, reject) => {
		uni.getBluetoothDevices({
			success(res) {
				console.log('获取搜索到的设备信息', res.devices);
				bluetoothConnect = false;
				// 过滤掉name为空或者未知设备的设备
				let devices = res.devices.filter(function(obj) {
					return obj.name !== "" && obj.name !== "未知设备"
				});
				console.log('有名称蓝牙列表', devices, deviceName);
				devices && devices.forEach(item => {
					if (item.name == deviceName || item.localName == deviceName) {
						deviceId = item.deviceId;
						isHaveDevice = true;
						resolve(isHaveDevice);
						console.log('设备ID', deviceId, item);
					}
				});
				timer = setInterval(() => {
					time++
					if (!deviceId) {
						discoveryBluetooth().then(
							getBluetoothDevices2(deviceName).then(res => {
								isHaveDevice = true;
								resolve(res);
							})
						)
					} else {
						clearInterval(timer)
						timer = null
					}
					if (time == 30) {
						clearInterval(timer)
						timer = null
						reject()
					}

				}, 1000)

			},
			fail: function() {
				console.log('搜索蓝牙设备失败');
				bluetoothConnect = false;
				isHaveDevice = false;
				reject(isHaveDevice);
			}

		});
	});
}
const getBluetoothDevices2 = (deviceName) => {
	return new Promise((resolve, reject) => {
		uni.getBluetoothDevices({
			success(res) {
				console.log('获取搜索到的设备信息', res.devices);

				bluetoothConnect = false;
				// 过滤掉name为空或者未知设备的设备
				let devices = res.devices.filter(function(obj) {
					return obj.name !== "" && obj.name !== "未知设备"
				});
				console.log('有名称蓝牙列表', devices, deviceName);
				devices && devices.forEach(item => {
					if (item.name == deviceName || item.localName == deviceName) {
						deviceId = item.deviceId;
						isHaveDevice = true;
						clearInterval(timer)
						timer = null
						resolve(isHaveDevice);
						console.log('设备ID', deviceId, item);
					}
				});




			},
			fail: function() {
				console.log('搜索蓝牙设备失败');
				bluetoothConnect = false;
				isHaveDevice = false;
				reject(isHaveDevice);
			}

		});
	});
}
/**
 * 连接蓝牙
 * deviceId 蓝牙设备id
 */
const connectBluetooth = () => {
	return new Promise((resolve, reject) => {
		uni.createBLEConnection({
			deviceId: deviceId, // 设备id
			success() {
				bluetoothConnect = true;
				console.log('连接蓝牙成功', deviceId);
				// 蓝牙连接成功后关闭蓝牙搜索
				stopDiscoveryBluetooth();
				// 获取服务id
				getServiceId();
				setTimeout(() => {
					resolve();
				})
			},
			fail(err) {
				bluetoothConnect = false;
				console.log("蓝牙连接失败", err);
				reject();
			}
		});
	});
};
// 获取服务id
const getServiceId = () => {
	uni.getBLEDeviceServices({
		deviceId: deviceId,
		success(res) {
			console.log(res.services, '服务id成功');
			// 方案一
			res.services.forEach(item => {
				let firstFive = ''
				// // #ifdef MP-WEIXIN
				// firstFive = item.uuid.substring(0, 8);
				// // #endif
				// // #ifdef MP-ALIPAY
				// firstFive = item.uuid.substring(0, 4);
				// // #endif
				firstFive = item.uuid.substring(0, 8);
				var FFF0 = /fff0/i;
				console.log(firstFive, 'firstFive');
				if (FFF0.test(firstFive)) {
					serviceId = item.uuid;
					// 调用蓝牙监听和写入功能
					getCharacteId();
				}
			});


			// 方案二
			// let model = res.services[0];
			// serviceId = model.uuid;
			// console.log(res, '服务id成功', serviceId);
			// // 调用蓝牙监听和写入功能
			// getCharacteId();
		},
		fail(err) {
			console.log('获取服务失败', err);
		}
	})
};
// 获取蓝牙低功耗设备某个服务中所有特征
const getCharacteId = () => {
	uni.getBLEDeviceCharacteristics({
		deviceId: deviceId, // 蓝牙设备id
		serviceId: serviceId, // 蓝牙服务UUID
		success(res) {
			console.log('数据监听', res);
			res.characteristics.forEach(item => {
				let firstFive = ''
				// #ifdef MP-WEIXIN
				firstFive = item.uuid.substring(0, 8);
				// #endif
				// #ifdef MP-ALIPAY
				firstFive = item.characteristicId.substring(0, 8);
				// #endif

				console.log(firstFive, 'firstFive');
				var FFF1 = /fff1/i;
				var FFF2 = /fff2/i;

				// 001
				if (item.properties.notify === true && FFF1.test(firstFive)) {
					// 监听
					// 微信
					// #ifdef MP-WEIXIN
					notify = item.uuid;
					// #endif

					//支付宝
					// #ifdef MP-ALIPAY
					notify = item.characteristicId;
					// #endif
					startNotice();
				}
				// 002
				if (item.properties.write === true && FFF2.test(firstFive)) {
					// 写入 
					// 微信
					// #ifdef MP-WEIXIN
					let writeId = item.uuid;
					uni.setStorageSync("writeId", item.uuid);

					// #endif

					//支付宝
					// #ifdef MP-ALIPAY
					let writeId = item.serviceId;
					uni.setStorageSync("writeId", item.characteristicId);
					// #endif


				}
			});
		},
		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);
					// let data = result.value;
					console.log('帽子返回数据', result)
				}
			})
		}
	});
};


// 蓝牙发送数据
const writeData = (buffer) => {
	return new Promise((resolve, reject) => {
		console.log(uni.getStorageSync("writeId"), '下发命令1writeId');
		console.log(deviceId, '下发命令2deviceId');
		console.log(serviceId, '下发命令3serviceId');
		console.log(buffer, '下发命令4buffer');

		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();
			}
		});
	});
};

// 断开蓝牙
const closeBlec = () => {
	return new Promise((resolve, reject) => {
		uni.closeBLEConnection({
			deviceId: deviceId,
			success(res) {
				resolve();
				console.log(res, '断开成功')
			},
			fail(err) {
				reject();
				console.log("断开失败", err);
			}
		})
	})

}

const BLECStateChange = () => {
	return new Promise((resolve, reject) => {
		uni.onBLEConnectionStateChange(function(res) {
			// 该方法回调中可以用于处理连接意外断开等异常情况
			console.log(
				`device ${res.deviceId} state has changed, connected: ${res.connected}`)
			return resolve(res)

		})
	})

}



/*设置蓝牙搜索时间30秒, 如果超时没有搜索到就停止搜索*/
const connectTimeout = () => {
	setTimeout(() => {
		if (!bluetoothConnect) {
			clearInterval(timer)
			timer = null
			uni.stopBluetoothDevicesDiscovery({
				success: (res) => {
					console.log("停止搜索成功")
				}

			})
			uni.showToast({
				title: '蓝牙连接失败',
				icon: 'none'
			})
		}
	}, 30000)

}

const getLocation = () => {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: function(info) {
				console.log('手机', info);
				if (info.platform == 'android') {
					// 安卓手机
					console.log('1111');
					if (info.locationEnabled) {
						if (info.locationAuthorized) {
							time = 0
							connectTimeout()
							resolve()
						} else {
							// #ifdef MP-WEIXIN
							uni.showToast({
								title: '请打开微信定位权限',
								icon: 'none'
							})
							// #endif
							// #ifdef MP-ALIPAY
							uni.showToast({
								title: '请打开支付宝定位权限',
								icon: 'none'
							})
							// #endif
							reject()
						}

					} else {
						console.log('333');
						uni.showToast({
							title: '请打开手机定位权限',
							icon: 'none'
						})
						reject()
					}

				} else {
					// 非安卓手机
					time = 0
					connectTimeout()
					console.log('非安卓手机');
					resolve()
				}
			}
		});
	})

}


// closeBLEConnection  deviceId  断开蓝牙
export default {
	getBluetoothState,
	discoveryBluetooth,
	stopDiscoveryBluetooth,
	getBluetoothDevices,
	connectBluetooth,
	getServiceId,
	getCharacteId,
	startNotice,
	writeData,
	closeBlec,
	BLECStateChange
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值