小程序连接蓝牙

1.授予蓝牙权限

//1.蓝牙授权
const authBlue = (callback, initApp) => {
    app = initApp;
    //鉴定是否授权蓝牙
    wx.getSetting().then(res => {
        if (!res.authSetting['scope.bluetooth']) {
            //未授予蓝牙权限
            return wx.authorize({
                scope: 'scope.bluetooth',
            })
        } else {
            //已授予
            if (callback != null) {
                callback({
                    blueAuth: true
                }) 
                // init() //2.蓝牙初始化
            }

            return new Promise(() => {})
        }
    }).then(() => {
        if (callback != null) {
            callback({
                blueAuth: true
            }) //回调-app.js-蓝牙权限
            // init() //2.蓝牙初始化
        }
        return new Promise(() => {})
    }).catch(err => {
        if (callback != null)
            callback({
                blueAuth: false
            })
        console.err(err);
    })
}

2.蓝牙初始化

//2.蓝牙初始化
const init = (onFound) => {
    console.log("2.蓝牙初始化");
    //打开蓝牙适配器
    wx.openBluetoothAdapter({
        mode: 'central'
    }).then(res => {
        app.globalData.isOpenBleAdapter = true //蓝牙适配器已打开
        wx.onBluetoothAdapterStateChange((res) => { //回调---蓝牙适配器状态改变
            if (!res.available) { //蓝牙适配器是否可用
                wx.showModal({
                    title: '温馨提示',
                    content: '蓝牙蓝牙适配器不可用,请重新启动',
                    showCancel: false
                })
            }
        })
        onFound(); //监听+寻找 新设备 -- 回调函数
    }).catch(() => {
        //失败
        wx.showToast({
            title: '请检查手机蓝牙是否打开',
            icon: 'none',
        })
    })
}

3.监听寻找新设备

//3.监听寻找新设备
const onDeviceFound = (addDevicesList) => {
    console.log("3.监听寻找新设备");
    wx.onBluetoothDeviceFound((res) => {
        const devicesList = []
        for (const item of res.devices) {
            if (!item.connectable) continue; //无法连接 --> 跳过
        	//过滤设备,找出自己想连接的设备  filterDevices
            let device = Device.filterDevices(item)
        	//addDevicesList 是一个回调函数,将数据更新到 View
            if (device && addDevicesList != null) {
                // 判断是否已经存在相同id的对象
                var existingObjIndex = devicesList.findIndex(function (obj) {
                    return obj.deviceId === device.deviceId;
                });
                if (existingObjIndex !== -1) { // 存在相同id的对象
                    // 更新对应位置上的对象属性值
                    Object.assign(devicesList[existingObjIndex], device);
                } else { // 不存在相同id的对象
                    // 将新对象添加到数组末尾
                    devicesList.push(device);
                }
            }
        }
        //更新到设备列表
        addDevicesList(devicesList)
    })
}

4.搜索新设备

//4.搜索新设备
const startDevicesDiscovery = (obj) => {
    wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true, //允许上报同一台设备
        interval: 1000, //上报间隔时间
        success: (res) => {
            console.log("4.搜索新设备");
            // getBluetoothDevices()		// 获取蓝牙设备列表
        },
        fail: function (res) {
            wx.showToast({
                title: '搜索蓝牙外围设备失败,请重新初始化蓝牙!',
                icon: 'none',
            })
        }
    })
}

5.建立连接⭐⭐⭐⭐⭐

/** 5.建立连接 
 * @param {*} deviceId 要连接的设备MAC
 * @param {*} func 连接后要执行的命令
 * 1.建立连接
 * 2.设置MTU    setBLEMTU
 * 3.获取蓝牙服务 UUID  getBLEDeviceServices
 * 4.获取蓝牙服务列表 UUIDS   getBLEDeviceCharacteristics
 * 5.判断UUIDS中哪个服务可用于indicate | notify,使用该UUID订阅特征变化 notifyBLECharacteristicValueChange
 * 6.监听特征值变化:onBLECharacteristicValueChange
 * 7.func({isConnect: true}) //连接成功
 */
const createConnect = (deviceId, func) => {
    let mtu = 209 //协商设置蓝牙低功耗的最大传输单元
    let serviceId = '0000FFE0-0000-1000-8000-00805F9B34FB';	//特定的UUID
    let characteristics;
    wx.createBLEConnection({
        deviceId
    }).then((res) => { //2.设置MTU
        if (res.errCode === 0 || res.errCode === -1) {
            console.log('1.连接成功');
            const systemInfo = wx.getSystemInfoSync();
            const platform = systemInfo.platform; //Android | IOS
            if (platform === 'android') {
                return wx.setBLEMTU({
                    deviceId,
                    mtu
                });
            } else if (platform === 'ios') {
                return {
                    mtu
                }
            } else {
                return {
                    mtu
                }
            }
        } else {
            console.log('连接失败');
            func({
                isConnect: false
            }) //连接失败
            return new Promise(() => {})
        }
    }, error => {
        console.log(error)
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => { //3.获取蓝牙服务
        console.log("2.MTU设置成功,协商MTU:", res.mtu, deviceId, serviceId);
        return wx.getBLEDeviceServices({deviceId});
    }, (res) => {
        console.log("2.MTU设置失败:", res);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => {//4.获取蓝牙服务列表
        console.log("3.获取蓝牙服务成功", res);
        for (let i = 0; i < res.services.length; i++) {
            console.log("+++++++++发现服务:", res.services[i].uuid);
            if (res.services[i].uuid === '0000FFE0-0000-1000-8000-00805F9B34FB') {
                return wx.getBLEDeviceCharacteristics({
                    deviceId,
                    serviceId
                });
            }
        }
    },(err) => {
        console.error("3.获取蓝牙服务失败", err);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => { //5.判断哪个服务可用于indicate | notify
        console.log("4.获取UUIDS成功", res);
        characteristics = res.characteristics

        for (let i = 0; i < characteristics.length; i++) {
            const item = characteristics[i];
            if (item.properties.notify || item.properties.indicate) {
                return wx.notifyBLECharacteristicValueChange({
                    deviceId: deviceId,
                    serviceId: serviceId,
                    characteristicId: item.uuid,
                    state: true
                });
            }
        }
    }, (res) => {
        console.log("4.获取UUIDS失败", res);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => { //6.监听特征值变化
        console.log('5.订阅特征变化成功', res);
        for (let i = 0; i < characteristics.length; i++) {
            let item = characteristics[i];
            if (item.uuid.substr(0, 8) == '0000FFE1') {
                app.globalData.characteristicId = item.uuid
                break;
            }
        }
        func({ isConnect: true}) //连接成功
    }, (err) => {
        console.log("5.订阅特征变化失败", res);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).catch((err) => {
        func({ isConnect: false}) //连接失败
        console.error(err);
    });
}

6.监听蓝牙低功耗连接状态改变事件

//6.监听蓝牙低功耗连接状态改变事件--主动连接或断开连接,设备丢失,连接异常断开
const onConnectionStateChange = (listenBleStatus) => {
    wx.onBLEConnectionStateChange(res => listenBleStatus(res))
}

8.监听特征值变化

//8.监听特征值变化   --  onBleValueChange  回调函数
const onCharacteristicValueChange = (onBleValueChange) => {
    wx.onBLECharacteristicValueChange(res => onBleValueChange(res))
}

/**
 * 监听蓝牙设备传输的数据
 * @param {*} res deviceId、serviceId、characteristicId、【value	ArrayBuffer	特征最新的值】
 */
function onBleValueChange(res) {
    console.log("监听到数据", res);
    //处理数据
    .
    .
    .
}

9.发送数据

/** 9.发送数据
 * @param {*} deviceId 设备ID
 * @param {*} command  命令
 */
const writeCharacteristicValue = (deviceId, command) => {
    return wx.writeBLECharacteristicValue({
        characteristicId: app.globalData.characteristicId,
        deviceId: deviceId,
        serviceId: app.globalData.serviceId,
        value: command,
    })
}

完整ble模块⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

let app = getApp()
const {
    default: Device
} = require('./device')
const commandUtil = require('./commandUtil')

//1.蓝牙授权
const authBlue = (callback, initApp) => {
    app = initApp;
    //鉴定是否授权蓝牙
    wx.getSetting().then(res => {
        if (!res.authSetting['scope.bluetooth']) {
            //未授予蓝牙权限
            return wx.authorize({
                scope: 'scope.bluetooth',
            })
        } else {
            //已授予
            if (callback != null) {
                callback({
                    blueAuth: true
                }) 
                // init() //2.蓝牙初始化
            }

            return new Promise(() => {})
        }
    }).then(() => {
        if (callback != null) {
            callback({
                blueAuth: true
            }) //回调-app.js-蓝牙权限
            // init() //2.蓝牙初始化
        }
        return new Promise(() => {})
    }).catch(err => {
        if (callback != null)
            callback({
                blueAuth: false
            })
        console.err(err);
    })
}

//2.蓝牙初始化
const init = (onFound) => {
    console.log("2.蓝牙初始化");
    //打开蓝牙适配器
    wx.openBluetoothAdapter({
        mode: 'central'
    }).then(res => {
        app.globalData.isOpenBleAdapter = true //蓝牙适配器已打开
        wx.onBluetoothAdapterStateChange((res) => { //回调---蓝牙适配器状态改变
            if (!res.available) { //蓝牙适配器是否可用
                wx.showModal({
                    title: '温馨提示',
                    content: '蓝牙适配器不可用,请重新启动',
                    showCancel: false
                })
            }
        })
        onFound(); //监听+寻找 新设备
    }).catch(() => {
        //失败
        wx.showToast({
            title: '请检查手机蓝牙是否打开',
            icon: 'none',
        })
    })
}


//3.监听寻找新设备
const onDeviceFound = (addDevicesList) => {
    console.log("3.监听寻找新设备");
    wx.onBluetoothDeviceFound((res) => {
        const devicesList = []
        for (const item of res.devices) {
            if (!item.connectable) continue; //无法连接 --> 跳过
            let device = Device.filterDevices(item)
            if (device && addDevicesList != null) {
                // 判断是否已经存在相同id的对象
                var existingObjIndex = devicesList.findIndex(function (obj) {
                    return obj.deviceId === device.deviceId;
                });
                if (existingObjIndex !== -1) { // 存在相同id的对象
                    // 更新对应位置上的对象属性值
                    Object.assign(devicesList[existingObjIndex], device);
                } else { // 不存在相同id的对象
                    // 将新对象添加到数组末尾
                    devicesList.push(device);
                }
            }
        }
        //更新到设备列表
        addDevicesList(devicesList)
    })
}

//4.搜索新设备
const startDevicesDiscovery = (obj) => {
    wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true, //允许上报同一台设备
        interval: 500, //上报间隔时间
        success: (res) => {
            console.log("4.搜索新设备");
            // getBluetoothDevices()
        },
        fail: function (res) {
            wx.showToast({
                title: '搜索蓝牙外围设备失败,请重新初始化蓝牙!',
                icon: 'none',
            })
        }
    })
}

//5.获取蓝牙列表
const getBluetoothDevices = (obj) => {

}

/** 6.建立连接 
 * @param {*} deviceId 要连接的设备MAC
 * @param {*} func 连接后要执行的命令
 * 1.建立连接
 * 2.设置MTU    setBLEMTU
 * 3.获取蓝牙服务 UUID  getBLEDeviceServices
 * 4.获取蓝牙服务列表 UUIDS   getBLEDeviceCharacteristics
 * 5.判断UUIDS中哪个服务可用于indicate | notify,使用该UUID订阅特征变化 notifyBLECharacteristicValueChange
 * 6.监听特征值变化:onBLECharacteristicValueChange
 * 7.func({isConnect: true}) //连接成功
 */
const createConnect = (deviceId, func) => {
    let mtu = 209 //协商设置蓝牙低功耗的最大传输单元
    let serviceId = '0000FFE0-0000-1000-8000-00805F9B34FB';
    let characteristics;
    wx.createBLEConnection({
        deviceId
    }).then((res) => { //2.设置MTU
        if (res.errCode === 0 || res.errCode === -1) {
            console.log('1.连接成功');
            const platform = app.globalData.platform; //Android | IOS
            if (platform === 'android') {
                return wx.setBLEMTU({
                    deviceId,
                    mtu
                });
            } else if (platform === 'ios') {
                return {
                    mtu
                }
            } else {
                return {
                    mtu
                }
            }
        } else {
            console.log('连接失败');
            func({
                isConnect: false
            }) //连接失败
            return new Promise(() => {})
        }
    }, error => {
        console.log(error)
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => { //3.获取蓝牙服务
        console.log("2.MTU设置成功,协商MTU:", res.mtu, deviceId, serviceId);
        return wx.getBLEDeviceServices({deviceId});
    }, (res) => {
        console.log("2.MTU设置失败:", res);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => {//4.获取蓝牙服务列表
        console.log("3.获取蓝牙服务成功", res);
        for (let i = 0; i < res.services.length; i++) {
            console.log("+++++++++发现服务:", res.services[i].uuid);
            if (res.services[i].uuid === '0000FFE0-0000-1000-8000-00805F9B34FB') {
                return wx.getBLEDeviceCharacteristics({
                    deviceId,
                    serviceId
                });
            }
        }
    },(err) => {
        console.error("3.获取蓝牙服务失败", err);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => { //5.判断哪个服务可用于indicate | notify
        console.log("4.获取UUIDS成功", res);
        characteristics = res.characteristics

        for (let i = 0; i < characteristics.length; i++) {
            const item = characteristics[i];
            if (item.properties.notify || item.properties.indicate) {
                return wx.notifyBLECharacteristicValueChange({
                    deviceId: deviceId,
                    serviceId: serviceId,
                    characteristicId: item.uuid,
                    state: true
                });
            }
        }
    }, (res) => {
        console.log("4.获取UUIDS失败", res);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).then((res) => { //6.监听特征值变化
        console.log('5.订阅特征变化成功', res);
        for (let i = 0; i < characteristics.length; i++) {
            let item = characteristics[i];
            if (item.uuid.substr(0, 8) == '0000FFE1') {
                app.globalData.characteristicId = item.uuid
                break;
            }
        }
        func({ isConnect: true}) //连接成功
    }, (err) => {
        console.log("5.订阅特征变化失败", res);
        func({ isConnect: false}) //连接失败
        return new Promise(() => {})
    }).catch((err) => {
        func({ isConnect: false}) //连接失败
        console.error(err);
    });
}

//7.监听蓝牙低功耗连接状态改变事件--主动连接或断开连接,设备丢失,连接异常断开
const onConnectionStateChange = (listenBleStatus) => {
    wx.onBLEConnectionStateChange(res => listenBleStatus(res))
}

//8.断开连接
const closeConnection = (deviceId) => {
    wx.closeBLEConnection({
        deviceId
    }).then(() => {
        console.log("关闭成功");
    }).catch(err => console.error(err))
}

//9.监听特征值变化
const onCharacteristicValueChange = (onBleValueChange) => {
    wx.onBLECharacteristicValueChange(res => onBleValueChange(res))
}

/** 10.发送数据
 * @param {*} deviceId 设备ID
 * @param {*} command  命令
 */
const writeCharacteristicValue = async (deviceId, command) => {
    return wx.writeBLECharacteristicValue({
        characteristicId: app.globalData.characteristicId,
        deviceId: deviceId,
        serviceId: app.globalData.serviceId,
        value: command,
    })
}

/**
 * 11.获取已连接设备的信号强度
 * @param {*} deviceId 
 */
const getDeviceRSSI = (deviceId) => {
    return wx.getBLEDeviceRSSI({
        deviceId
    })
}

const stopDevicesDiscovery = () => {
    return wx.stopBluetoothDevicesDiscovery();
}

module.exports = {
    authBlue, //蓝牙授权
    init, //初始化
    onDeviceFound, //监听寻找新设备
    startDevicesDiscovery, //搜索新设备
    createConnect, //连接设备
    onConnectionStateChange, //监听设备的连接状态
    closeConnection, //取消连接
    onCharacteristicValueChange, //监听数据变化
    writeCharacteristicValue, //向蓝牙设备发送数据
    getDeviceRSSI, //获取已连接设备的信号强度
    stopDevicesDiscovery, //停止搜索附近设备
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值