这不是我想要的,我要一个完整能运行H5 蓝牙BLE的
时间: 2024-03-07 11:47:51 浏览: 21
好的,这里提供一个完整的H5蓝牙BLE的示例代码,您可以根据实际情况进行修改:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bluetooth BLE Example</title>
</head>
<body>
<h1>Bluetooth BLE Example</h1>
<button id="btn-scan" disabled>Scan</button>
<button id="btn-disconnect" disabled>Disconnect</button>
<table id="table-devices">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>RSSI</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
// 获取HTML元素
var btnScan = document.querySelector('#btn-scan');
var btnDisconnect = document.querySelector('#btn-disconnect');
var tableDevices = document.querySelector('#table-devices tbody');
// 蓝牙设备列表
var devices = {};
// 扫描蓝牙设备
function scanDevices() {
// 清空设备列表
devices = {};
tableDevices.innerHTML = '';
// 开始扫描
navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }]
})
.then(device => {
devices[device.id] = device;
addDevice(device);
})
.catch(error => {
console.error('Bluetooth Error:', error);
});
}
// 添加蓝牙设备到列表中
function addDevice(device) {
var tr = document.createElement('tr');
var tdName = document.createElement('td');
var tdAddress = document.createElement('td');
var tdRssi = document.createElement('td');
tdName.innerText = device.name;
tdAddress.innerText = device.id;
tdRssi.innerText = 'N/A';
tr.appendChild(tdName);
tr.appendChild(tdAddress);
tr.appendChild(tdRssi);
tableDevices.appendChild(tr);
device.addEventListener('advertisementreceived', event => {
tdRssi.innerText = event.rssi;
});
}
// 连接蓝牙设备
function connectDevice(device) {
device.gatt.connect()
.then(server => {
return server.getPrimaryService('battery_service');
})
.then(service => {
return service.getCharacteristic('battery_level');
})
.then(characteristic => {
characteristic.readValue()
.then(value => {
console.log('Battery Level: ' + value.getUint8(0));
});
})
.catch(error => {
console.error('Bluetooth Error:', error);
});
}
// 断开蓝牙设备连接
function disconnectDevice(device) {
device.gatt.disconnect();
}
// 监听扫描和断开按钮的点击事件
btnScan.addEventListener('click', function() {
btnScan.disabled = true;
btnDisconnect.disabled = false;
scanDevices();
});
btnDisconnect.addEventListener('click', function() {
btnScan.disabled = false;
btnDisconnect.disabled = true;
for (var id in devices) {
if (devices.hasOwnProperty(id)) {
disconnectDevice(devices[id]);
}
}
});
</script>
</body>
</html>
```
该示例代码实现了扫描蓝牙设备、连接蓝牙设备、读取特征值和断开蓝牙设备连接等功能。您可以在浏览器中运行该代码并进行调试。请注意,不同的浏览器支持的Web Bluetooth API可能存在差异,您需要根据您的浏览器进行相应的修改。