豫ICP备2024044691号-1
powered by emlog
uniapp 蓝牙模块封装
Mins 2023-3-18 00:32 uniapp

以下代码同样适用于各种小程序平台,具体参加各小程序的开发文档,这里只做记录。

export default {

    // 初始化蓝牙
    init (){
        return new Promise(async (resolve, reject) => {
            console.log('初始化蓝牙');
            let status = await this.status();

            // 如果已经在打开状态,直接走回调
            if(status.opened){
                console.log('已初始化');
                resolve();
            }else{
                // 未打开状态,开启蓝牙
                uni.openBluetoothAdapter({
                    success (res){
                        console.log('初始化蓝牙成功');
                        resolve();
                    },
                    fail (err){
                        console.log('初始化蓝牙失败');
                        console.log(err.errMsg);
                        reject(err);
                    }
                })
            }
        })
    },

    // 获取当前蓝牙状态
    status (){
        console.log('获取蓝牙状态')
        return new Promise(callback => {
            uni.getBluetoothAdapterState({
                success (res){
                    console.log('获取成功')
                    callback({
                        opened: res.errMsg == 'getBluetoothAdapterState:ok' ? true : false,
                        ...res.adapterState
                    });
                },
                fail (err){
                    console.log('获取失败,请先打开蓝牙');
                    console.log(err);
                    callback({
                        opened: false
                    });
                }
            })
        })
    },

    // 开始搜索蓝牙
    start (){
        console.log("开始搜索蓝牙");
        uni.startBluetoothDevicesDiscovery();  
    },

    // 监听搜索
    onFind (callback){
        const that = this;
        that.start();
        uni.onBluetoothDeviceFound(item => {
            let device = item.devices[0];
            if(device.name.match('Smart')){
                callback({
                    name: device.name,
                    deviceId: device.deviceId,
                    serviceId: device.advertisServiceUUIDs[0]
                })
            }
        })
    },

    // 搜索指定属性的蓝牙设备,默认按名称搜索
    find (k, v){
        console.log(`查找蓝牙,k=${k}, v=${v}`);
        const that = this;
        return new Promise(callback => {
            that.start();
            console.log('搜索监听中');
            uni.onBluetoothDeviceFound(item => {
                console.log(`搜索到蓝牙: ${item.devices[0].name}`);
                if(item.devices[0][k] == v){
                    console.log('搜素到指定蓝牙,结束');
                    that.stop();
                    callback({
                        deviceId: item.devices[0].deviceId,
                        serviceId: item.devices[0].advertisServiceUUIDs[0]
                    })
                }
            })
        })
    },

    // 停止搜索
    stop (){
        uni.stopBluetoothDevicesDiscovery();
        console.log('蓝牙搜索已停止');
    },

    // 连接蓝牙设备
    contact (deviceId){
        const that = this;
        return new Promise(callback => {
            uni.createBLEConnection({
                deviceId,
                success (res){
                    console.log('设备连接成功');
                    callback(res);
                    that.stop();
                },
                fail (err){
                    console.log('设备连接失败');
                    console.log(err);
                    that.stop();
                }
            })
        })
    },

    // 获取可用蓝牙服务
    service (deviceId){
        return new Promise(callback => {
            uni.getBLEDeviceServices({
                deviceId,
                success (res){
                    console.log('获取可用服务成功')
                    callback(res);
                }
            })
        })
    },

    // 获取特征值
    getKey (deviceId, serviceId){
        return new Promise(callback => {
            uni.getBLEDeviceCharacteristics({
                deviceId,
                serviceId,
                success (res){
                    console.log('获取特征值成功');
                    callback(res.characteristics[1].uuid);
                }
            })
        })
    },

    // 监听消息
    notice (deviceId, serviceId, characteristicId, state = true){
        return new Promise(callback => {
            console.log(deviceId, serviceId, characteristicId)
            uni.notifyBLECharacteristicValueChange({
                deviceId,
                serviceId,
                characteristicId,
                state,
                success (res){
                    console.log('正在监听消息');
                    callback(res);
                },
                fail (err){
                    console.log('监听失败');
                    console.log(err)
                }
            })
        })
    },

    // 接收数据
    onData (callback){
        const that = this;
        uni.onBLECharacteristicValueChange(data => {
            console.log('收到数据')
            data = that.parse(data.value);
            callback(data);
        })
    },

    // 处理数据
    parse (data){
        // ArrayBuffer转16进度字符串示例
        const ab2hex = (buffer) => {
            let hexArr = Array.prototype.map.call(
                new Uint8Array(buffer),
                function (bit) {
                    return ('00' + bit.toString(16)).slice(-2)
                }
            )
            return hexArr.join('')
        }

        // 将16进制的内容转成我们看得懂的字符串内容
        const hexCharCodeToStr = (hexCharCodeStr) => {
            var trimedStr = hexCharCodeStr.trim();
            var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
            var len = rawStr.length;
            if (len % 2 !== 0) {
                alert("存在非法字符!");
                return "";
            }
            var curCharCode;
            var resultStr = [];
            for (var i = 0; i < len; i = i + 2) {
                curCharCode = parseInt(rawStr.substr(i, 2), 16);
                resultStr.push(String.fromCharCode(curCharCode));
            }
            return resultStr.join("");
        }
        return hexCharCodeToStr(ab2hex(data));
    }
}