蓝牙连接步骤和创建读取本地数据库

737 阅读2分钟

bluetooth

Bluetooth模块用于管理蓝牙设备,搜索附近蓝牙设备、实现简单数据传输等。支持搜索发现所有蓝牙设备,但仅支持低功耗蓝牙ble传输协议,不支持蓝牙设备的配对连接传输大量数据。 如果要连接非ble蓝牙设备,可以使用Native.js调用(请到ask.dcloud.net.cn搜索bluetooth相关问答)。

document.addEventListener('plusready', function() {
})

初始化蓝牙模块(开启蓝牙适配器)

var bluetoothState = false; // 蓝牙就绪状态
phoenix.loading(); // 加载中
plus.bluetooth.openBluetoothAdapter({
    success: function(e) {

    },
    fail: function(e) {
        new phoenix.dialog({
            title: '打开蓝牙失败!',
            button: [{
                name: '重试',
            }],
            onTap: function(index) {
                plus.runtime.restart(); // 重启应用
            }
        });
        return;
    },		
});

获取本机蓝牙适配器状态

plus.bluetooth.getBluetoothAdapterState({
    success:function(e){						
        phoenix.pluginRemove(); // 移除加载中					
        bluetoothState = true; // 蓝牙就绪						
    },
    fail:function(e){
        new phoenix.dialog({
            title: '蓝牙未开启,请开启蓝牙后重启应用!',
            button: [{
                name: '重启应用',
            }],
            onTap: function(index) {
                plus.runtime.restart(); // 重启应用
            }
        });
        return;
    }
});

判断蓝牙是否准备就绪

if(!bluetoothState){
    new phoenix.dialog({
        title: '蓝牙未准备就绪',
        button: [{
            name: '重试',
        }],
        onTap: function(index) {
        }
    });
    return;
};

开始搜索附近的蓝牙设备

plus.bluetooth.startBluetoothDevicesDiscovery({
    success:function(e){

    },
    fail:function(e){
        new phoenix.dialog({
            title: '搜索蓝牙设备失败',
            button: [{
                name: '重试',
            }],
            onTap: function(index) {
            }
        });
        return;
    }
});

根据uuid获取处于已连接的设备

plus.bluetooth.getConnectedBluetoothDevices({
    services:['0003CDD0-0000-1000-8000-00805F9B0131'],
    success:function(e){
        var devices = e.devices;
        for(var i in devices){
            var device = devices[i];
            var deviceHtml =
            `
                <div class="box ptb12 plr10 flex relative">
                    <div class="link color"  data-id=${device.deviceId} data-name=${device.name}></div>
                    <div class="flex0">名称:${device.name}</div>
                    <div class="flex1 ar">${device.deviceId}</div>		
                    <div class="flex0 ew60 ar color relative">
                        已连接
                    </div>	
                </div>
            `;
            page.querySelector(".my_device_connect_list").insertAdjacentHTML('beforeEnd', deviceHtml);
        }
    },
    fail:function(e){
    }
});

当有新设备上报,插入设备列表

注意:连接中的设备不上报

plus.bluetooth.onBluetoothDeviceFound(function(e) {
    var flag = false; // 判断该设备是否缓存在本地
    var connectedHtml = '<i class="phoenix_icon phoenix_icon_setting"></i>'; // 连接状态
    var devices = e.devices;    
    for (var i in devices) {
        //if (devices[i].name && devices[i].name == 'xxx') {
            var device = devices[i];	
            // 判断是否连接过该设备(即本地是否存有该设备的数据)
            if(localStorage.getItem('device') && JSON.parse(localStorage.getItem('device')).length>0){							
                JSON.parse(localStorage.getItem('device')).forEach(function(item){
                    if(item.id && item.id == device.deviceId){
                        flag = true;
                    } 
                })
            }

            // 展示搜索出的设备列表
            var deviceHtml =
                `
                    <div class="box ptb12 plr10 flex relative">
                        <div class="link"  data-id=${device.deviceId} data-name=${device.name}></div>
                        <div class="flex0">名称:${device.name}</div>
                        <div class="flex1 ar">${device.deviceId}</div>		
                        <div class="flex0 ew60 ar">
                            ${connectedHtml}
                        </div>	
                    </div>
                `;
            if(flag == true){ // 连接过的设备
                // 展示在我的设备中
                page.querySelector(".my_device_list").insertAdjacentHTML('beforeEnd', deviceHtml);
            } else { //未连过的设备
                // 展示在设备列表中 
                page.querySelector(".available_device_list").insertAdjacentHTML('beforeEnd', deviceHtml);
            };
        //}
    }
});

连接低功耗蓝牙设备

停止搜索

plus.bluetooth.stopBluetoothDevicesDiscovery({});

连接低功耗蓝牙设备

plus.bluetooth.createBLEConnection({
    deviceId: deviceId, //  蓝牙设备的id
    success: function(e) {
    },
    fail: function(error) {
        console.log(" 连接 fail: " + error.code + "---" + error.message)
        new phoenix.dialog({
            title: '连接失败,请重试',
        });
        return;
    },
 })
监听低功耗蓝牙设备的特征值变化事件
plus.bluetooth.onBLECharacteristicValueChange(function(event) {		
    var value = new Int8Array(event.value);
    //console.log('特征值变化: ' + value);
    var value = new Uint8Array(event.value);
    // console.log('value(hex) = ' + buffer2hex(value));
    // 首页接收数据
    acceptData(ab2str(value));
});
启用低功耗蓝牙设备特征值变化时的notify功能,订阅特征值
setTimeout(function() {
    // 启用低功耗蓝牙设备特征值变化时的notify功能,订阅特征值
    plus.bluetooth.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: deviceId,
        serviceId: serviceUUID,
        characteristicId: characteristicUUID1,
        success: function(e) {
            var characteristics = e.characteristics;
            //console.log('notify get characteristics success: ' + characteristics);
            new phoenix.toast('连接成功,读取数据中');
        },
        fail: function(e) {
            //console.log('notify get characteristics failed: ' + JSON.stringify(e));
            new phoenix.dialog({
                title: '设备不匹配,连接失败!',
                onTap: function(index) {
                    // 点击确定并关闭弹框后后执行

                }
            });

        }
    });
}, 1000)
监听蓝牙设备连接状态
plus.bluetooth.onBLEConnectionStateChange(function(e){
    new phoenix.dialog({
        title: '连接已断开!',
        onTap: function(index) {
            // 点击确定并关闭弹框后后执行

        }
    });			
});

断开连接

plus.bluetooth.closeBLEConnection({
    deviceId:t.getAttribute('data-id'),
    success:function(e){
        //console.log('close success: '+JSON.stringify(e));
        page.querySelector('.device_list_box').classList.add('hide');
        page.querySelector('.my_device_connect_list').innerHTML = '';
    },
    fail:function(e){
        //console.log('close failed: '+JSON.stringify(e));
    }
});

停止搜寻附近的蓝牙外围设备的几种情况

连接低功耗蓝牙设备之前

关闭设备列表页

设备信息存储到本地

var deviceObj = {
    id:t.getAttribute('data-id'),
    name:t.getAttribute('data-name'),
}

var localDevice = localStorage.getItem('device');
var localDeviceArr = JSON.parse(localStorage.getItem('device'));
var flag = false;

// 监听连接蓝牙设备时先判断本地有无指定key的存储数据,如果有数据就判断并插入;如果没有就创建本地存储数据
if(localDevice && localDeviceArr.length > 0){ // 本地有数据
    localDeviceArr.forEach(function(item){ // 判断本地数据是否已存在要连接的设备
        if(item['id'] == t.getAttribute('data-id')){  // 已存在,则忽略
            flag = true;  
        }
    })
    if(flag == false){ // 不存在,则插入到本地数据中
        localDeviceArr.push(deviceObj);
    }
    localStorage.setItem('device', JSON.stringify(localDeviceArr));
} else { // 本地无数据
    var localDeviceArr = []; //本地数据
    localDeviceArr.push(deviceObj);
    localStorage.setItem('device', JSON.stringify(localDeviceArr));
}

sqlite

SQLite模块用于操作本地数据库文件,可实现数据库文件的创建,执行SQL语句等功能。注意:HBuilderX1.7.2及以上版本支持此功能。

打开数据库

plus.sqlite.openDatabase({
        name: 'xxx',
        path: '_doc/xxx.db',
        success: function(e) {

        },
        fail: function(e) {
                //console.log('openDatabase failed: ' + JSON.stringify(e));
        }
});

执行增删改等操作的SQL语句

plus.sqlite.executeSql({
    name: 'xxx',
    sql: `create table if not exists ${database}("year" REAL , "month" REAL , "day" REAL,"hour" REAL ,"time" TEXT,"blood_oxy" REAL,"heart_rate" REAL,"temperature" REAL)`,
    success: function(e) {
        //console.log('table  success: ' + JSON.stringify(e));
    },
    fail: function(e) {
        //console.log('table    failed: ' + JSON.stringify(e));
    }
});

执行查询的SQL语句

plus.sqlite.selectSql({
    name: 'xxx',
    sql: 'select * from database',,
    success: function(e) {
       

    },
    fail: function(e) {
        //console.log('executeSql failed: ' + JSON.stringify(e));
    }
});