uniapp微信小程序蓝牙连接与设备数据对接
蓝牙连接并通信方法封装大致步骤。
- 初始化蓝牙并搜索;
- 获取并启用service服务;
- 数据读取和监听设备返回数据
需要使用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、开启蓝牙适配器初始化蓝牙模块,获取手机蓝牙是否打开
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();
}
});
});
}
2、开启蓝牙设备搜索:
const discoveryBluetooth = () => {
return new Promise((resolve) => {
uni.startBluetoothDevicesDiscovery({
success(res) {
uni.showLoading({
title: "正在搜索设备",
icon:"none",
duration: 2000
});
console.log('搜索蓝牙外围设备完成', res)
setTimeout(() => {
// 监听寻找到的蓝牙设备
resolve();
}, 2000);
}
})

本文详细介绍了在uniapp微信小程序中实现蓝牙连接,包括初始化蓝牙、搜索设备、获取服务、监听数据变化以及数据传输的方法,供开发者参考。

1万+

被折叠的 条评论
为什么被折叠?



