h5蓝牙连接
嵌入手机app通过原生方法去启动蓝牙功能
封装蓝牙模块
export const connectData = {
/**
* 连接蓝牙
*/
openBluetooth(){
// 判断手机蓝牙状态
jsInjection.openBluetoothAdapter()
jsInjection.getBluetoothAdapterState("getBluetoothAdapterState");
// 注册蓝牙连接的回调方法
jsInjection.onBleConnectionStateChange("changeBleConnectionState");
// 注册发现服务的回调方法
jsInjection.onBleServicesDiscovered("changeServiceDiscoverState");
// 连接蓝牙
jsInjection.createBleConnection(deviceId);
// 开启定时器,定时器1s执行1次
timer = setInterval(judgeTimeout, 1000);
},
/**
* 断开蓝牙
*/
beforeDestroy() {
// 断开蓝牙连接
jsInjection.closeBleConnection(deviceId);
if (timer) {
clearInterval(timer);
}
},
/**
* 监听
*/
monitor(){
// 注册发现服务的回调方法
jsInjection.onBleServicesDiscovered("changeServiceDiscoverState");
// 连接蓝牙
jsInjection.createBleConnection(deviceId);
},
/**
* 写入
*/
writeCharacter(text){
let value = '';
if(text.substr(0,2)=='A5'){
value = text.substr(0,text.length)
}else{
value = parseInt(text,16)
}
for(let i=0;i<value.length;i+=40){
window.writeCharacteristicCallback = writeCharacteristicCallback;
jsInjection.writeBLECharacteristicValue(
deviceId,
globalData.SERVICE_ID,
globalData.WRITE_CHARACTERISTIC_ID,
value.substring(i,i+40),
"writeCharacteristicCallback"
)
command = value.substring(i,i+40)
// console.log('发送'+value.substring(i,i+40))
}
},
/**
* 读取
*/
read(){
window.readBLECharacteristicValueCallback = readBLECharacteristicValueCallback;
jsInjection.readBLECharacteristicValue(
deviceId,
globalData.BATTERY_SERVICE_ID,
globalData.BATTERY_CHARACTERISTIC_ID,
"readBLECharacteristicValueCallback"
)
//console.log("读取")
},
/**
* 发送命令
*/
sendCommand(c,t,d){
typeNo++;
let text = ''
let cmd = c
store.state.cmd = cmd
let cmd1 = parseInt(255-parseInt(cmd,16)).toString(16)
if(cmd1.split('').length<2){
cmd1 = '0' + cmd1
}
let type = t
let len = '0000'
let data = d
if(data!=''){
if(parseInt(data.length/2).toString(16).length<2){
len = '0'+parseInt(data.length/2).toString(16) + '00'
}else{
len = parseInt(data.length/2).toString(16) + '00'
}
}
let no = parseInt(typeNo).toString(16)
if(no.length<2){
no = '0'+no
}else{
no = no
}
if(typeNo >= 254){
typeNo = 0
}
let crc = Crc8.calculationCrc8('A5'+ cmd + cmd1 + type + no + len + data)
text = 'A5' + cmd + cmd1 + type + no + len + data + crc
//console.log('A5'+',' + cmd+',' + cmd1+',' + type+',' + no+',' + len+',' + data+',' + crc)
return text
},
}