i***@outlook.com
i***@outlook.com
  • 发布:2020-07-17 16:53
  • 更新:2020-07-17 16:53
  • 阅读:1188

为何华为对于低功耗蓝牙无法监听特征值的变化呢,其他型号的手机都可以

分类:5+ SDK
var serviceId = "14839AC4-7D7E-415C-9A42-167340CF2339" //设备主服务ID  
var notifyID = "0734594A-A8E7-4B1A-A6B1-CD5243059A57" //监听数据变化ID  
var writeID = "8B00ACE7-EB0B-49B0-BBE9-9AEE0A26E1A3" //写入蓝牙数据特征值ID  
var url = getPort(); //数据接口地址  
var devicesIds = []; //连接的设备号  
var available = null; //蓝牙开关  
var app_session = localStorage.getItem("app_session"); //app_session  

let bluetooths = []  
let deviceIdList = []  
var availables = []; //可用设备  
localStorage.removeItem("bluetooths");  

// 页面初始化操作   
document.addEventListener('plusready', function(e) {  
    openBluetoothAdapter();  
    listenerConnection()  
    // 监听蓝牙适配器状态变化   
    plus.bluetooth.onBluetoothAdapterStateChange(function(e) {  
        available = e.available  
        setTimeout(function() {  
            if (!e.available) {  
                stopBluetoothDiscovery()  
                // mui.alert("您的手机蓝牙未开启,请打开蓝牙后在进行操作", "温馨提示", function() {})  
            }  
        }, 600)  
        if (available && !e.discovering) {  
            location.reload()  
        }  
    });  
    //  监听搜索到新设备   
    plus.bluetooth.onBluetoothDeviceFound(function(e) {  
        var devices = e.devices[0];  
        var list = []  
        if (devices.advertisServiceUUIDs[0] === "00001802-0000-1000-8000-00805F9B34FB" && devices.advertisServiceUUIDs[0]) {  
            if (devices) {  
                if(bluetooths.length==0){  
                    bluetooths.push({  
                        bluetooth_name: devices.name,  
                        deviceId: devices.deviceId  
                    })  
                }else{  
                    var list = bluetooths.every(i=>{return i.bluetooth_name!=devices.name})  
                    if(list){  
                        bluetooths.push({  
                            bluetooth_name: devices.name,  
                            deviceId: devices.deviceId  
                        })  
                    }  
                }  
            }  
        }  
        console.log(JSON.stringify(bluetooths))  
        if(bluetooths.length!=0){  
            localStorage.setItem("bluetooths", JSON.stringify(bluetooths))  
        }  

        if (availables.indexOf(devices.name) != -1) {  
            devicesIds.push(devices.deviceId)  
        }  
    });  
    //监听数据蓝牙数据变化  
    onBLECharacteristicValueChange()  
}, false);  

//初始化蓝牙模块  
function openBluetoothAdapter() {  
    plus.bluetooth.openBluetoothAdapter({  
        success: function(e) {  
            startBluetoothDiscovery()  
            console.log("初始化蓝牙设备成功")  
        },  
        fail: function(e) {  
            mui.alert("您的手机蓝牙未开启,请打开蓝牙后在进行操作", "温馨提示", function() {})  
        }  
    });  
}  

// 开始搜索蓝牙  
function startBluetoothDiscovery() {  
    plus.bluetooth.startBluetoothDevicesDiscovery({  
        services: ["00001802-0000-1000-8000-00805F9B34FB"],  
        allowDuplicatesKey: false,  
        success: function(e) {  
            console.log("开始搜索蓝牙设备")  
        },  
        fail: function(e) {}  
    });  
}  
//连接蓝牙  
async function createConnection(deviceId) {  
    return new Promise(function(resolve, reject) {  
        plus.bluetooth.createBLEConnection({  
            deviceId: deviceId,  
            timeout: 2000,  
            success: function(e) {  
                resolve(e)  
                deviceIdList.push(deviceId)  
                // writeBLECharacteristicValue(deviceId)  
                str2ArrayBuffer("%SYNC=1,0", function(buffer) {  
                    setTimeout(function() {  
                        writeBLECharacteristicValue(deviceId, buffer).then(res => {  
                            notifyBLECharacteristicValueChange(deviceId)  
                        }).catch(err => {  

                        })  
                    }, 1000)  
                });  
            },  
            fail: function(e) {  
                reject(e)  
            }  
        });  
    })  
}  

//断开连接的蓝牙  
async function closeConnection(deviceId) {  
    return new Promise(function(resolve, reject) {  
        plus.bluetooth.closeBLEConnection({  
            deviceId: deviceId,  
            success: function(e) {  
                resolve(e)  
            },  
            fail: function(e) {  
                reject(e)  
            }  
        });  
    })  
}  

let deviceIndex = 0  
// 监听低功耗蓝牙设备的特征值变化  
function onBLECharacteristicValueChange() {  

    plus.bluetooth.onBLECharacteristicValueChange(function(e) {  
        var value = buf2hex(e.value);  
        let device = bluetooths.find(item => {  
            return item.deviceId === e.deviceId  
        })  
        let bluetooth_name = device.bluetooth_name;  
        if (value.length == 20) {  
            var week = []; //一周的数据  
            for (let i = 1; i < 5; i++) {  
                week.push({  
                    day: parseInt(value[2], 16),  
                    time: parseInt(value[(i * 4)], 16),  
                    steps: parseInt(value[(i * 4 + 3)], 16) + parseInt(value[(i * 4 + 2)], 16) * 250  
                })  
            }  
            mui.ajax({  
                url: url + "/api/index/getMovementList",  
                type: "POST",  
                data: {  
                    bluetooth_name: bluetooth_name,  
                    movement: week,  
                },  
                success: function(json) {  
                    week = [];  
                    console.log(bluetooth_name + ":" + value)  
                },  
            })  
        } else if (value.length == 6) {  
            mui.ajax({  
                url: url + "/api/index/getMovement",  
                type: "POST",  
                data: {  
                    bluetooth_name: device.bluetooth_name,  
                    number: parseInt(value[5], 16) + parseInt(value[4], 16) * 250,  
                    hours: parseInt(value[2], 16)  
                },  
                success: function(data) {  
                    console.log(JSON.stringify(data))  
                }  
            })  
        }  
    });  
}  
// 启用notify功能  
async function notifyBLECharacteristicValueChange(deviceId) {  
    return new Promise(function(resolve, reject) {  
        plus.bluetooth.notifyBLECharacteristicValueChange({  
            deviceId: deviceId,  
            serviceId: serviceId,  
            characteristicId: notifyID,  
            state: true,  
            success: function(e) {  

                resolve(e)  
            },  
            fail: function(e) {  
                reject(e)  
            }  
        });  
    })  
}  

//写入数据  
async function writeBLECharacteristicValue(deviceId, buffer) {  
    return new Promise(function(resolve, reject) {  
        plus.bluetooth.writeBLECharacteristicValue({  
            deviceId: deviceId,  
            serviceId: serviceId,  
            characteristicId: writeID,  
            value: buffer,  
            success: function(e) {  
                resolve(e)  
                // notifyBLECharacteristicValueChange(deviceId)  
            },  
            fail: function(e) {  
                reject(e)  
                // writeBLECharacteristicValue(deviceId)  
            }  
        });  
    })  
}  

// 结束搜索蓝牙  
function stopBluetoothDiscovery() {  
    plus.bluetooth.stopBluetoothDevicesDiscovery({  
        success: function(e) {  
            plus.bluetooth.closeBluetoothAdapter({  
                success: function(e) {},  
                fail: function(e) {}  
            });  
        },  
        fail: function(e) {}  
    });  

}  

// 转换为ArrayBuffer写入蓝牙  
function str2ArrayBuffer(s, f) {  
    var b = new Blob([s], {  
        type: 'text/plain'  
    });  
    var r = new FileReader();  
    r.readAsArrayBuffer(b);  
    r.onload = function() {  
        if (f) f.call(null, r.result)  
    }  
}  

//转化为十六进制  
function buf2hex(buffer) {  
    return Array.prototype.map.call(  
        new Uint8Array(buffer),  
        x => {  
            return ('00' + x.toString(16)).slice(-2)  
        });  
}  
var statusWrite = true;  
// 监听蓝牙设备连接状态  
function listenerConnection() {  

    plus.bluetooth.onBLEConnectionStateChange(function(e) {  
        let device = bluetooths.find(item => {  
            return item.deviceId === e.deviceId  
        })  
        if (!e.connected && !state) {  
            devicesIds.push(device.deviceId)  
            $("#" + device.bluetooth_name).removeClass("mui-active")  
        }  
    });  
}  
setInterval(function() {  
    devicesIds = [...new Set(devicesIds)]  
    if (devicesIds.length > 0) {  
        againCreateConnection()  
    }  
}, 3000)  
//自动连接  
function againCreateConnection() {  
    let device = bluetooths.find(item => {  
        return item.deviceId === devicesIds[0]  
    })  
    createConnection(device.deviceId).then(res => {  
        $("#" + device.bluetooth_name).addClass("mui-active")  
        let index = devicesIds.indexOf(device.deviceId)  
        devicesIds.splice(index, 1)  
    }).catch(err => {  
        return false  
    })  
}  
2020-07-17 16:53 负责人:无 分享
已邀请:

该问题目前已经被锁定, 无法添加新回复