// 初始化蓝牙(判断用户有没有开蓝牙) --> 搜索蓝牙 --> 连接蓝牙 --> 根据连接的deviceId获取服务serviceUUID -->
// 根据服务serviceUUID获取特征值 --> 根据特征值获取 读写权限 --> 根据读写 数据交互
var test = 'FE08010000000000000108';
var ble={
//适配器开启状态
openBluetoothAdapter:false,
//蓝牙是否可用
available:false,
//服务发现是否开启
discovering:false,
//发现的设备列表
deviceList:[],
//当前连接设备id
connectingDeviceId:'',
//服务uuid
services_UUID:'',
//特征值uuid
characteristic_UUID:'',
}
//蓝牙方法
// 初始化蓝牙
ble.openEvent = () => {
wx.getLocation({
type: 'gcj02', //返回可以用于wx.openLocation的经纬度
success: function (res) {
// let latitude = res.latitude //维度
// let longitude = res.longitude //经度
console.log(res);
}
});
openBluetooth();
}
// 搜索蓝牙
ble.searchEvent = () => {
if (ble.discovering){
toast('正在搜索');
return;
}
ble.deviceList= []
// 停止搜寻附近的蓝牙外围设备
stopDiscovery();
// 获取本机蓝牙适配器状态
if(getBluetoothState()){
return;
}
// 监听蓝牙适配器状态变化事件
onBluetoothStateChange();
// 开始搜寻附近的蓝牙外\围设备
startDiscovery();
// 监听寻找到新设备
onFoundBluetooth();
}
// 连接设备
ble.connectEvent = function(deviceId, successCallback,errorCallback){
if(this.data.connected){
return;
}
// 停止搜寻附近的蓝牙外围设备
stopDiscovery();
// 断开与低功耗蓝牙设备的连接 然后再连接新的设备
closeConnection(deviceId);
// 连接低功耗蓝牙设备
BLEConnection(deviceId);
}
//蓝牙发送数据
ble.sendMsg = function(msg, successCallback,errorCallback){
this.writeToBluetoothValue(ble.connectingDeviceId,ble.services_UUID,ble.characteristic_UUID,msg,successCallback,errorCallback);
}
//=========================================
//依赖方法
// 初始化蓝牙模块
function openBluetooth(){
wx.openBluetoothAdapter({
success(e){
if (e.errMsg == 'openBluetoothAdapter:ok'){
ble.openBluetoothAdapter = true;
getBluetoothState();
}
},
fail(){
wx.showModal({
title: '温馨提示',
content: '请检查手机蓝牙是否开启',
showCancel:false
});
ble.openBluetoothAdapter = false;
},
})
}
// 获取本机蓝牙适配器状态
function getBluetoothState(){
wx.getBluetoothAdapterState({
success(e){
ble.available=e.available
ble.discovering=e.discovering
return true;
},
fail(){
ble.available=false
ble.discovering=false
return false;
}
});
}
// 停止搜寻附近的蓝牙外围设备
function stopDiscovery(){
wx.stopBluetoothDevicesDiscovery({
success(res){
console.log('停止搜寻附近的蓝牙外围设备');
console.log(res);
ble.discovering = false
},
fail(){
toast('停止搜索失败');
},
});
}
// 监听蓝牙适配器状态变化事件
function onBluetoothStateChange(){
wx.onBluetoothAdapterStateChange(function(res){
ble.available = res.available
ble.discovering = res.discovering
});
}
// 开始搜寻附近的蓝牙外围设备
function startDiscovery(){
console.log('开始搜索设备');
wx.startBluetoothDevicesDiscovery({
success (res) {
ble.discovering = res.isDiscovering
// that.getDevices();
},
fail(){
ble.discovering = false
toast('搜索失败');
}
})
}
// 监听寻找到新设备的事件
function onFoundBluetooth(){
wx.onBluetoothDeviceFound(function (res) {
// that.getDevices();
// 兼容安卓及iOS设备
if(res.deviceId){
that.devicesData(res);
} else if(res.devices){
that.devicesData(res.devices[0]);
} else if(res[0]){
that.devicesData(res[0]);
}
});
}
// 获取在蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备
function getDevices(){
wx.getBluetoothDevices({
success: function (res) {
console.log('获取在蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备');
console.log(res);
ble.deviceList = res.devices;
}
})
}
// 断开与低功耗蓝牙设备的连接
function closeConnection(){
let connectingDeviceId = ble.connectingDeviceId;
if(!connectingDeviceId){
return;
}
wx.closeBLEConnection({
deviceId: connectingDeviceId,
success(res){
console.log('断开与低功耗蓝牙设备的连接');
console.log(res);
},
fail(){
toast('断开连接失败');
}
});
}
// 连接低功耗蓝牙设备
function BLEConnection(deviceId){
loading('连接中');
console.log('连接中...');
console.log(deviceId);
wx.createBLEConnection({
deviceId: deviceId,
timeout: 60000,
success(res){
console.log('连接成功');
console.log(res);
// connectingDeviceId = deviceId;
ble.connected = true;
ble.connectingDeviceId = deviceId
getServices(deviceId);
hide_Loading();
toast('连接成功');
},
fail(res){
console.log('连接失败');
console.log(res);
ble.connected = false;
hide_Loading();
},
});
}
// 获取蓝牙设备所有服务(service) 为了获取service的UUID
function getServices(deviceId){
// console.log(deviceId);
wx.getBLEDeviceServices({
deviceId:deviceId,
success(res){
// console.log('获取蓝牙设备service');
console.log(res);
ble.services = res.services
let uuid = res.services;
let len = uuid.length;
for(let i = 0; i < len; i++){
// if (res.services[i].isPrimary) {
getCharacteristics(deviceId,res.services[i].uuid);
}
},
fail(res){
toast('获取服务失败');
console.log(res);
},
});
}
// 获取蓝牙设备某个服务中所有特征值(characteristic) 为了该特征值UUID支持的操作类型
function getCharacteristics(deviceId,servicesId){
wx.getBLEDeviceCharacteristics({
deviceId:deviceId,
serviceId:servicesId,
success(res){
console.log('获取蓝牙设备characteristic');
console.log(res);
if(res.errCode === 0){
let characteristics = res.characteristics;
let len = characteristics.length;
for(let k = 0; k < len; k++){
let indicate = characteristics[k].properties.indicate;
let notify = characteristics[k].properties.notify;
let read = characteristics[k].properties.read;
let write = characteristics[k].properties.write;
console.log(indicate,notify,read,write);
if(indicate && notify && read && write){
// let connectingDeviceId = res.deviceId;
let connectingDeviceId = deviceId;
console.log('connectingDeviceId');
console.log(connectingDeviceId);
// let services_UUID = res.serviceId;
let services_UUID = servicesId;
console.log('services_UUID');
console.log(services_UUID);
let characteristic_UUID = characteristics[k].uuid;
console.log('characteristic_UUID');
console.log(characteristic_UUID);
ble.connectingDeviceId = connectingDeviceId;
ble.services_UUID = services_UUID
ble.characteristic_UUID = characteristic_UUID
notifyValueChange(connectingDeviceId,services_UUID,characteristic_UUID);
}
}
}
},
fail(){
toast('获取特征值失败');
}
});
}
// 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值
function notifyValueChange(deviceId,services_UUID,characteristic_UUID){
wx.notifyBLECharacteristicValueChange({
deviceId:deviceId,
serviceId:services_UUID,
characteristicId:characteristic_UUID,
state:true,
success(res){
console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值: 成功---');
console.log(res);
onValueChange();
// setTimeout(function () {
// let connectingDeviceId = that.data.connectingDeviceId;
// let services_UUID = that.data.services_UUID;
// let characteristic_UUID = that.data.characteristic_UUID;
// writeToBluetoothValue(connectingDeviceId,services_UUID,characteristic_UUID,test);
// },1000);
},
fail(res){
console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值: 失败---');
console.log(res);
},
});
}
// 监听低功耗蓝牙设备的特征值变化
// 必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
function onValueChange(){
wx.onBLECharacteristicValueChange(function(res){
console.log('监听低功耗蓝牙设备的特征值变化');
console.log(res);
console.log(ab2hex(res.value));
// 获取设备返回的数据
let hex = ab2hex(res.value);
// 获取总次数
let num = hexSlice(hex);
console.log(num)
ble.shakeNum = num
});
}
// 蓝牙写数据
function writeToBluetoothValue(deviceId,services_UUID,characteristic_UUID,buffer,successCallback,errorCallback){
let value = hex2ab(buffer);
wx.writeBLECharacteristicValue({
deviceId:deviceId,
serviceId:services_UUID,
characteristicId:characteristic_UUID,
value:value,
success(res){
console.log('向低功耗蓝牙设备特征值中写入二进制数据: 成功---');
console.log(res);
successCallback(res)
},
fail(res){
console.log('向低功耗蓝牙设备特征值中写入二进制数据: 失败---');
console.log(res);
errorCallback(res)
}
})
}
// 读取低功耗蓝牙设备的特征值的二进制数据值
// 接口读取到的信息需要在 onBLECharacteristicValueChange 方法注册的回调中获取
function readValue(){
let connectingDeviceId = this.data.connectingDeviceId;
let services_UUID = this.data.services_UUID;
let characteristic_UUID = this.data.characteristic_UUID;
wx.readBLECharacteristicValue({
deviceId:connectingDeviceId,
serviceId:services_UUID,
characteristicId:characteristic_UUID,
success(res){
console.log('读取低功耗蓝牙设备的特征值的二进制数据值: 成功---');
console.log(res);
},
fail(res){
console.log('读取低功耗蓝牙设备的特征值的二进制数据值: 失败---');
console.log(res);
}
});
}
//=========================================
//工具函数
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
let hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2);
}
);
return hexArr.join('');
}
/**
* 16进制字符串转ArrayBuffer
*/
function hex2ab(str) {
if (!str) {
return new ArrayBuffer(0);
}
let typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
}));
let buffer1 = typedArray.buffer;
console.log(buffer1);
return buffer1;
}
// 16进制字符串取需要的字节(fe 08 01 00 01 01 01 7a0b 008f)
function hexSlice(hex) {
// 取k8位
let k8 = hex.slice(14,16);
//取k9位
let k9 = hex.slice(16,18);
return parseInt(k9+k8,16);
}
function toast(title) {
wx.showToast({
title: title,
icon:'none',
duration:1500,
success(){
setTimeout(()=>{
wx.hideToast();
},2000);
}
});
}
function loading(title) {
wx.showLoading({
title:title,
mask:true,
});
}
function hide_Loading() {
wx.hideLoading();
}
//拼接新的device
function devicesData(new_devices){
let deviceList = ble.deviceList;
let len = deviceList.length;
let isExist = false;
console.log(new_devices);
if(!new_devices.name){
new_devices.name = '空';
return;
}
let advertisData = ab2hex(new_devices.advertisData);
if(!advertisData){
advertisData = '空';
}
new_devices.advertisData = advertisData;
for(let i = 0; i < len; i++){
if(new_devices.deviceId == deviceList[i].deviceId){
isExist = true;
deviceList.splice(i,1,new_devices);
}
}
if(!isExist){
deviceList.push(new_devices);
}
ble.deviceList = deviceList
}
微信小程序连接蓝牙工具类支持IOS和安卓
最新推荐文章于 2024-08-09 03:27:08 发布