H5plus的Bluetooth模块如何搜索设备、连接设备、获取数据(简易版)

990 阅读1分钟

文档:H5plus的Bluetooth模块

流程:

  1. 初始化蓝牙模块

    plus.bluetooth.startBluetoothDiscovery

  2. 开始搜索附近的蓝牙设备

    plus.bluetooth.startBluetoothDevicesDiscovery

  3. 监听搜索到新设备的事件

    plus.bluetooth.onBluetoothDeviceFound

  4. 连接低功耗蓝牙设备

    plus.bluetooth.createBLEConnection

  5. [若已知服务id,该步骤可跳过]获取蓝牙设备的所有服务(service)

    plus.bluetooth.getBLEDeviceServices

  6. [若已知特征值id,该步骤可跳过]获取蓝牙设备指定服务中所有特征值(characteristic)

    plus.bluetooth.getBLEDeviceCharacteristics

  7. 启用低功耗蓝牙设备特征值变化时的notify功能,订阅特征值

    plus.bluetooth.notifyBLECharacteristicValueChange

  8. 监听低功耗蓝牙设备的特征值变化事件

    plus.bluetooth.onBLECharacteristicValueChange

  9. 根据业务需求处理数据

代码:

<div class="device_list"></div><!-- 设备列表 -->
<div class="device_value"></div><!-- 数据列表 -->
document.addEventListener('plusready', function() {
    // 开始搜索设备
    startBluetoothDiscovery();

    // 开始搜索蓝牙
    function startBluetoothDiscovery() {
        // 1. 初始化蓝牙模块
        plus.bluetooth.openBluetoothAdapter({
            success: function(e) {
                console.log('open success: ' + JSON.stringify(e));
                
                // 2. 开始搜索附近的蓝牙设备
                plus.bluetooth.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey:false, // 是否允许上报同一设备
                    success: function(e) {
                        console.log('start discovery success: ' + JSON.stringify(e));
                    },
                    fail: function(e) {
                        console.log('start discovery failed: ' + JSON.stringify(e));
                    }
                });
            },
            fail: function(e) {
                console.log('open failed: ' + JSON.stringify(e));
            }
        });
        
        // 3. 监听搜索到新设备的事件
        plus.bluetooth.onBluetoothDeviceFound(function(e){
            var deviceListHtml = '';
            var devices = e.devices;						
            for(var i in devices){						
                if(devices[i].name == 'xxxxxx'){ // 假设要连接指定设备名的设备
                    createConnection(devices[i].deviceId)
                    document.querySelector(".device_list").insertAdjacentHTML('beforeEnd', `<div>${devices[i].name}<div>`);
                }

            }
        });						
    }

    // 4. 连接低功耗蓝牙设备
    function createConnection(deviceId) {
        plus.bluetooth.createBLEConnection({
            deviceId: deviceId,
            success: function(e) {
                console.log('create connection success: ' + JSON.stringify(e));
                getValue(deviceId);
            },
            fail: function(e) {
                console.log('create connection failed: ' + JSON.stringify(e));
            }
        });
    }
    
    // 5. 获取蓝牙设备的所有服务(service)
    function getServices(deviceId){
        plus.bluetooth.getBLEDeviceServices({
            deviceId:deviceId,
            success:function(e){
                var services = e.services;
                console.log('get services success: '+services.length);
                for(var i in services){
                    console.log(i+': '+JSON.stringify(services[i]));

                    if(services[i].uuid == 'xxxxxxxxxxxxxxx'){ 
                        getCharacteristics(deviceId,services[i].uuid)
                    }
                }
            },
            fail:function(e){
                console.log('get services failed: '+JSON.stringify(e));
            }
        });
    }
    
    // 6. 获取蓝牙设备指定服务中所有特征值(characteristic)
    function getCharacteristics(deviceId,serviceId){
        plus.bluetooth.getBLEDeviceCharacteristics({
            deviceId:deviceId,
            serviceId:serviceId,
            success:function(e){
                var characteristics = e.characteristics;
                console.log('get characteristics success: '+characteristics.length);
                for(var i in characteristics){
                    console.log(i+': '+JSON.stringify(characteristics[i]));
                }
            },
            fail:function(e){
                 console.log('get characteristics failed: '+JSON.stringify(e));
            }
        });
    }

    // 监听特征值
    function getValue(deviceId) {
        // 8. 监听低功耗蓝牙设备的特征值变化
        plus.bluetooth.onBLECharacteristicValueChange(function(e) {
            // 9. 根据业务需求处理数据
            var v = new Uint8Array(e.value);
            var _value = Uint8ArrayToString(v)
            console.log(_value)
            document.querySelector(".device_value").insertAdjacentHTML('beforeEnd', `<div>${_value}<div>`);
        });

        setTimeout(function() {
            // 7. 启用低功耗蓝牙设备特征值变化时的notify功能,订阅特征值
            plus.bluetooth.notifyBLECharacteristicValueChange({
                deviceId: deviceId,
                serviceId: "xxxxx-xxxxx-xxxxx-xxxxx-xxxxx",
                characteristicId: "xxxxx-xxxxx-xxxxx-xxxxx-xxxxx",
                state: true,
                success: function(e) {
                    console.log("notifyBLECharacteristicValueChange success " +JSON.stringify(e))
                },
                fail: function(e) {
                    console.log("notifyBLECharacteristicValueChange error " +JSON.stringify(e))
                },
                complete: function(e) {
                    console.log("notifyBLECharacteristicValueChange complete " +JSON.stringify(e))
                }
            });
        }, 5000)

    }    
});

// 处理数据的方法
function buffer2hex(buffer) {
    const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function(bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function Uint8ArrayToString(fileData) {
    var dataString = "";
    for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }
    return dataString
}