闲来没事钻研小程序开发,写了一篇关于微信小程序ble设备控制的底层api,话不多说直接上源码:
目录结构:
baseBleApi.js文件:
var currentDevice = {};
//ble设备
var notifyService = {};
//唤醒特征值
var writeService = {};
//写入服务
var writeCharacteristic = {};
//写入特征值
var notifyCharacteristic = {};
//唤醒特征值
var onSendSuccessCallBack =
undefined;
//成功回调
var onConnectCallback =
undefined;
// 链接回调
var bleUtils =
require(
'utils/strUtils.js');
var crc =
require(
'crc.js');
var isConnected =
false;
//是否已链接
module.exports = {
writeCommend: writeCommend,
closeBLEConnection: closeBLEConnection
// disConnect, disConnect,
// openBluetoothAdapter: openBluetoothAdapter
}
/**
* @param sendCommend 写入命令
* @param deviceName 锁具名称
* @param onSuccessCallBack 成功回调
* @param onFailCallBack 返回失败回调
* @param onCompleteCallBack 成功失败都会回调
*
* @param services 主服务serviceUUID
* @param writeServiceUUID 写入服务UUID
* @param notifyServiceUUID 唤醒服务UUID
*
* @param notifyCharacteristicUUID 唤醒特征值UUID
* @param writeCharacteristicUUID 写入特征值UUID
*/
function writeCommend(options) {
var params = {};
var defalt = {
adviceId:
"",
sendCommend:
"",
onSuccessCallBack:
function success(res) { },
onFailCallBack:
function success(res) { },
onCompleteCallBack:
function success(res) { },
services: [],
writeServiceUUID:
"",
notifyServiceUUID:
"",
notifyCharacteristicUUID:
"",
writeCharacteristicUUID:
""
};
params = Object.assign(defalt, options)
// setConnectionStateChange(params.onFailCallBack)
if (!setConnectionStateChange()) {
openBluetoothAdapter(params);
}
else {
// typeof str == 'string'
sendCmd(params.sendCommend, params.onSuccessCallBack, params.onFailCallBack);
}
}
/**
* 初始化蓝牙适配器
*/
function openBluetoothAdapter(params) {
wx.openBluetoothAdapter({
success:
function (res) {
console.log(
"初始化蓝牙适配器成功")
console.log(res)
startBluetoothDevicesDiscovery(params)
}, fail:
function (res) {
console.log(
"初始化蓝牙适配器失败")
params.onFailCallBack(res.errMsg)
console.log(res);
return
},
complete:
function (res) {
console.log(res);
}
})
}
/**
* 开始搜寻附近的蓝牙外围设备。注意,该操作比较耗费系统资源,请在搜索并连接到设备后调用 stop 方法停止搜索。
* @ params services:['4asdga'],根据主ServiceUUID进行搜索特定蓝牙,提高搜索效率
* 本ble设备主ServiceUUid: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
*/
var delayTimer;
//停止循环获取tag
var isFound =
false
function startBluetoothDevicesDiscovery(params, connectCallback) {
if (
typeof connectCallback ==
'undefined') {
connectCallback =
function (errMsg) { }
}
onConnectCallback = connectCallback;
setTimeout(
function () {
if (isFound) {
return;
}
else {
console.log(
"搜索设备超时");
params.onFailCallBack(
"搜索设备超时")
stopBluetoothDevicesDiscovery();
clearInterval(delayTimer)
return
}
},
10000);
wx.startBluetoothDevicesDiscovery({
services: params.services,
success:
function (res) {
console.log(res)
console.log(
"开启搜索成功")
getBluetoothDevices(params)
}, fail:
function (res) {
console.log(
"开启搜索失败")
console.log(res)
params.onFailCallBack(res)
return
},
complete:
function (res) {
// complete
console.log(res);
}
})
//每隔一秒获取一次
delayTimer = setInterval(
function () {
getBluetoothDevices(params)
},
1000)
}
/**
* 获取所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备
*/
function getBluetoothDevices(params) {
wx.getBluetoothDevices({
success:
function (res) {
console.log(
"getBluetoothDevices");
console.log(res.devices);
for (
var i =
0; i < res.devices.length; i++) {
//忽略传入的deviceName大小写
// isContains bleUtils
var lockNameFinal = bleUtils.removeBytes(params.adviceId,
":")
if (bleUtils.isContains(res.devices[i].name, lockNameFinal)) {
console.log(
"搜索到要链接的设备....")
stopBluetoothDevicesDiscovery();
isFound =
true
clearInterval(delayTimer)
currentDevice = res.devices[i]
createBLEConnection(params)
}
}
},
fail:
function (res) {
clearInterval(delayTimer)
console.log(
"没有搜索到要链接的设备....")
console.log(res)
params.onFailCallBack(res)
stopBluetoothDevicesDiscovery();
return
}
})
}
/**
* 停止搜寻附近的蓝牙外围设备。请在确保找到需要连接的设备后调用该方法停止搜索。
*/
function stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery({
success:
function (res) {
console.log(res)
}
})
}
/**
* 连接低功耗蓝牙设备
*/
function createBLEConnection(params) {
// setConnectionStateChange(params.onFailCallBack);
setTimeout(
function () {
if (isConnected)
return;
console.log(
"连接设备超时");
params.onFailCallBack(
"连接设备超时")
return
},
5000)
wx.createBLEConnection({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: currentDevice.deviceId +
"",
success:
function (res) {
console.log(res)
console.log(
`连接成功 : ${
currentDevice.deviceId
}`)
isConnected =
true
getBLEDeviceServices(params);
}, fail:
function (res) {
console.log(res)
params.onFailCallBack(res)
console.log(
`连接失败 : ${
currentDevice.deviceId
}`)
}
})
}
/**
* closeBLEConnection
* 断开与低功耗蓝牙设备的连接