源代码开源地址
首先通過import 引入封裝好的文件
import zBlue from '../../new_open_blue.js'
首先要了解状态(STATUS)对象
const STATUS = {
CLOSED: 1, //已关闭蓝牙适配器
OPENED: 2, //已打开蓝牙适配器
DISCOVERING: 3, //搜索中
NOT_CONNECTED: 4, //未连接
CONNECTED: 5 //已连接
};
初始化
- 在使用蓝牙模块前最好使其进入未初始化状态。调用该方法将断开所有已建立的链接并释放系统资源
断开已建立链接,并释放资源
由于是 promise对象,使用可以写在链式中。
zBlue.DEVICE.close()
.then((res){console.log("关闭成功")})
确定断开后再打开蓝牙模块蓝牙适配器
zBlue.DEVICE.open()
.then((res)=>{console.log("蓝牙适配器已打开")})
.catch((res){
// 项目使用uiapp框架
uni.showToast({
title:
"未搜索到设备,请确认手机蓝牙已经开启,或者重新刷新搜索设备!",
icon: "none",
duration: 2000,
});
})
1. 连接设备
- 在蓝牙适配器已打开成功后
若是已知设备dviceid**(MAC或者UUID)**可以直接对设备进行初始化连接
zBlue.DEVICE.initWithMac(mac)
.then((res)=>{
console.log("成功与设备创建连接")
})
此时在zBlue对象中全局变量foundDevice.deviceId=mac
1.1 指令写入
- 若成功则可以对设备进行写入指令
zBlue.DEVICE.write("指令")
.then((res)=>{
console.log("已发送指令",res)
})
.catch((res)=>{
console.log(res)
})
可以根据返回的res打印的状态就可以判断是否失败
1.2 再次连接
- 若失败了则可以在catch中调用执行
zBlue.DEVICE.write("指令")
.then((res)=>{
console.log("已发送指令",res)
})
.catch((res)=>{
console.log(res)
return zBlue.DEVICE.reconnect() //默认为10次两秒执行重连
})
.then((res)=>{
/*
* 重新执行initWithMAC(foundDevice.deviceId)
* 打印 重新连接成功
*/
})
.catch((res)=>{
// 打印 所有重新连接均失败
})
若依旧是失败回调说明设备异常或deviceid有误
1.3 释放已保存的设备信息
- 最后通过调用,释放后对象中全局变量foundDevice.deviceId为空,为下次连接做准备
zBlue.DEVICE.write("指令")
.then((res)=>{
...
.catch((res)=>{
zBlue.DEVICE.disconnect().then(()=>{})
})
2. 获取蓝牙设备信息
若未知设备MAC地址或UUID则可以获取蓝牙广播包然后根据唯一识别符再获取deviceId
- 搜索时间越长能获得设备信息越多,低于1s可能会搜索不到目标设备信息
zBlue.DEVICE.open()
.then((res)=>{
zBlue.DEVICE.getBluetoothDevices(timeout)
})
...
timeout设置搜索时间单位为毫秒
2.1 蓝牙广播包的处理
获取设备信息还需要对获取到的蓝牙广播包信息进行处理
- 针对不同设备需要不同处理,在源文件中
this.getBluetoothDevices = (timeout) => {
return new Promise((resolve, reject) => {
...
wx.onBluetoothDeviceFound((res) => {
// 对res广播包信息处理
...
device = “处理好符合信息的设备”
foundDevices.push(device);
...
});
},
fail: () => {
...
}
});
});
};
对蓝牙广播包的处理需根据各设备在wx.onBluetoothDeviceFound中编写
2.2 获得目标设备
- 返回获取到的将会是一个列表,均为符合的设备,还需要再对设备筛选,获取对应设备devicedId
zBlue.DEVICE.open()
.then((res)=>{
return zBlue.DEVICE.getBluetoothDevices(timeout)
})
.then((res)=>{
// 判断res中的唯一识别符和已知的唯一识别符是否相同,若相同则保存deviceid
// 为zBlue.DEVICE.iinitWithMac(mac)做准备
})
2.3 同上1的操作
zBlue.DEVICE.iinitWithMac(填写获取到deviceid)
下面为使用案例
zBlue.DEVICE.close().then((res) => {
zBlue.DEVICE.open()
.then((res) => {
console.log("蓝牙适配器已打开",res)
return zBlue.DEVICE.getBluetoothDevices(2 * 1000)
})
.catch((res)=>{
console.log("请确定已开启蓝牙适配器")
})
.then((res)=>{
console.log("蓝牙列表", res);
that.blue_lock_name_list = []
res.forEach((item) => {
item.name = item.prefix_id + item.name
that.blue_lock_name_list.push(item);
});
that.activeBlue = that.blueList[0]["deviceId"];
zBlue.DEVICE.initWithMac(that.activeBlue)
})
.then((res) => {
console.log("设备连接成功")
zBlue.DEVICE.write("xxxxxx")
.then((res)=>{
console.log("指令发送成功")
})
})
.catch((res)=>{
console.log("找不到目标设备")
})