使用js连接蓝牙设备,只贴代码不做过多详细解释(因为我也不太懂)
推荐的网站1 通过 JavaScript 与蓝牙设备通信,如果地址不可用,百度直接搜索 通过JavaScript与蓝牙设备通信
推荐的网站2 chrome://bluetooth-internals/#devices/c8:b2:1e:97:9e:a3 在谷歌游览器打开,在这里面扫描出要连接的蓝牙设备,通过连接可以得到该蓝牙设备的 服务的uuid 与特征的 uuid,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="btns">连接蓝牙</button>
<script>
var bluetoothDevice;
let btn = document.querySelector('.btns')
btn.addEventListener('click', getBlueObject)
// 获取蓝牙对象
function getBlueObject() {
bluetoothDevice = null;
// 这一块的筛选条件在 推荐的网站1里面可以粗略的学习到
navigator.bluetooth.requestDevice({
filters: [{
// 如果你使用的 acceptAllDevices: true, 这个筛选条件,当你要连接 服务 和 特征 的时候,就必须添加一个 optionalServices 把你的服务的uuid 和 特征的uuid 写进入
services: ['00001810-0000-1000-8000-00805f9b34fb']
}]
}).then(device => {
bluetoothDevice = device
// 监听蓝牙蓝牙断开
bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected)
connect()
}).catch(err => {
console.log('获取蓝牙失败');
})
}
// 开始连接
function connect() {
exponentialBackoff(3 /* 最大重试次数 */, 2 /* 秒延迟 */,
function toTry() {
return bluetoothDevice.gatt.connect();
},
function success(server) {
getServer(server)
},
function fail() {
console.log('连接失败');
});
}
// 获取服务\特征,监听蓝牙数据返回
function getServer(server) {
console.log('连接成功', server);
server.getPrimaryService('00001810-0000-1000-8000-00805f9b34fb').then(service => {
console.log('获取全部服务信息成功,开始获取特征信息', service)
return service.getCharacteristic('00002a35-0000-1000-8000-00805f9b34fb')
}).then(characteristic => {
return characteristic.startNotifications().then(_ => {
characteristic.addEventListener('characteristicvaluechanged',
handleNotifications);
});
}).catch(err => {
console.log('获取服务失败', err);
})
}
function onDisconnected(max, delay, status) {
console.log('重连中');
connect()
}
function exponentialBackoff(max, delay, toTry, success, fail) {
toTry().then(result => success(result))
.catch(_ => {
if (max === 0) {
return fail();
}
setTimeout(function () {
exponentialBackoff(--max, delay * 2, toTry, success, fail);
}, delay * 1000);
});
}
function handleNotifications(event) {
let value = event.target.value;
let a = [];
for (let i = 0; i < value.byteLength; i++) {
a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
}
console.log('> ' + a.join(' '));
}
</script>
</body>
</html>
两个简单的案例 gitee地址