3 Star 8 Fork 2

lijigang/bluetooth

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
new2.html 3.27 KB
一键复制 编辑 原始数据 按行查看 历史
lijigang 提交于 2022-03-17 16:25 . tijiao
<!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;
navigator.bluetooth.requestDevice({
// 如果你指定了 services的uuid,即指定了 服务的uuid,就不需要 optionalServices这个参数了
filters: [{
services: ['0000ffe0-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('0000ffe0-0000-1000-8000-00805f9b34fb').then(service => {
console.log('获取全部服务信息成功,开始获取特征信息', service)
return service.getCharacteristic('0000ffe1-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>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/helloljg/bluetooth.git
[email protected]:helloljg/bluetooth.git
helloljg
bluetooth
bluetooth
master

搜索帮助