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 = []
console.log('blue')
// 页面初始化操作
document.addEventListener('plusready', function(e) {
console.log('初始化')
openBluetoothAdapter();
listenerConnection()
console.log(localStorage.getItem("bluetooths"))
// 监听蓝牙适配器状态变化
plus.bluetooth.onBluetoothAdapterStateChange(function(e) {
available = e.available
setTimeout(function() {
if (!available) {
console.log("关闭蓝牙")
localStorage.removeItem("bluetooths");
stopBluetoothDiscovery()
mui.alert("您的手机蓝牙未开启,请打开蓝牙后在进行操作", "温馨提示", function() {})
}
}, 600)
});
// 监听搜索到新设备
plus.bluetooth.onBluetoothDeviceFound(function(e) {
var devices = e.devices[0];
if (devices && devices.advertisServiceUUIDs) {
bluetooths.push({
bluetooth_name: devices.name,
deviceId: devices.deviceId
})
}
console.log(456)
console.log(JSON.stringify(bluetooths))
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) {
console.log("连接蓝牙")
resolve(e)
deviceIdList.push(deviceId)
writeBLECharacteristicValue(deviceId)
},
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);
deviceIdList = [...new Set(deviceIdList)]
let device = bluetooths.find(item => {
return item.deviceId === deviceIdList[deviceIndex]
})
deviceIndex++;
if (deviceIndex == deviceIdList.length) {
deviceIndex = 0;
}
let bluetooth_name = device.bluetooth_name;
if (notifyID == e.characteristicId) {
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,
movement: week,
},
success: function(json) {
week = [];
},
})
} else if (value.length == 6) {
console.log(bluetooth_name + ":" + value)
mui.ajax({
url: url + "/api/index/getMovement",
type: "POST",
data: {
bluetooth_name,
number: parseInt(value[5], 16) + parseInt(value[4], 16) * 250,
hours: parseInt(value[2], 16)
},
success: function(data) {}
})
}
}
});
}
// 启用notify功能
function notifyBLECharacteristicValueChange(deviceId) {
plus.bluetooth.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: notifyID,
state: true,
success: function(e) {
console.log(JSON.stringify(e))
},
fail: function(e) {
console.log(JSON.stringify(e))
}
});
}
//写入数据
function writeBLECharacteristicValue(deviceId) {
var value = "%SYNC=1,0";
str2ArrayBuffer(value, function(buffer) {
plus.bluetooth.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: writeID,
value: buffer,
success: function(e) {
console.log(JSON.stringify(e))
notifyBLECharacteristicValueChange(deviceId)
},
fail: function(e) {
setTimeout(function() {
writeBLECharacteristicValue(deviceId)
}, 3000);
}
});
});
}
// 结束搜索蓝牙
function stopBluetoothDiscovery() {
plus.bluetooth.stopBluetoothDevicesDiscovery({
success: function(e) {
console.log('成功1')
plus.bluetooth.closeBluetoothAdapter({
success: function(e) {console.log('成功2')},
fail: function(e) {console.log('失败1')}
});
},
fail: function(e) {console.log('失败2')}
});
console.log('shuaxin')
if (available && !e.discovering) {
location.reload()
}
}
// 转换为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
})
}

i***@outlook.com
- 发布:2020-06-24 16:59
- 更新:2020-06-24 16:59
- 阅读:1728
mui项目,使用bluetooth模块,ios中当第一次连接是正常的,当蓝牙从关闭重新打开后就无法获取到蓝牙设备了,低功耗蓝牙
分类:MUI
0 个回复