Skip to content

Instantly share code, notes, and snippets.

@wwj718
Last active November 15, 2023 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwj718/2d2cefbd496561af4b8f78918c1cde29 to your computer and use it in GitHub Desktop.
Save wwj718/2d2cefbd496561af4b8f78918c1cde29 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BLE Echo Service</title>
</head>
<body>
<button id="connect">连接 BLE 设备</button>
<input type="text" id="inputData" placeholder="输入数据">
<button id="sendData">发送数据</button>
<button id="readData">读取数据</button>
<div id="output"></div>
<script>
const SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
const CHARACTERISTIC_UUID_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
const CHARACTERISTIC_UUID_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
let bleDevice = null;
let txCharacteristic = null;
document.getElementById('connect').addEventListener('click', () => {
navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: [SERVICE_UUID]
})
.then(device => {
bleDevice = device;
return device.gatt.connect();
})
.then(server => server.getPrimaryService(SERVICE_UUID))
.then(service => {
// 获取 RX 和 TX 特征
return Promise.all([
service.getCharacteristic(CHARACTERISTIC_UUID_RX),
service.getCharacteristic(CHARACTERISTIC_UUID_TX)
]);
})
.then(characteristics => {
const [rxCharacteristic, txCharacteristic] = characteristics;
this.txCharacteristic = txCharacteristic;
// 订阅 TX 特征的通知
txCharacteristic.startNotifications().then(_ => {
txCharacteristic.addEventListener('characteristicvaluechanged', handleNotifications);
});
})
.catch(error => {
console.log('连接错误:' + error);
});
});
document.getElementById('sendData').addEventListener('click', () => {
const data = new TextEncoder().encode(document.getElementById('inputData').value);
bleDevice.gatt.getPrimaryService(SERVICE_UUID)
.then(service => service.getCharacteristic(CHARACTERISTIC_UUID_RX))
.then(characteristic => characteristic.writeValue(data))
.catch(error => {
console.log('发送数据错误:' + error);
});
});
document.getElementById('readData').addEventListener('click', () => {
if (!bleDevice || !bleDevice.gatt.connected) {
console.log('设备未连接');
return;
}
bleDevice.gatt.getPrimaryService(SERVICE_UUID)
.then(service => service.getCharacteristic(CHARACTERISTIC_UUID_TX))
.then(characteristic => characteristic.readValue())
.then(value => {
let data = new TextDecoder().decode(value);
document.getElementById('output').textContent = '读取到的数据: ' + data;
})
.catch(error => {
console.log('读取数据错误:' + error);
});
});
function handleNotifications(event) {
let value = new TextDecoder().decode(event.target.value);
document.getElementById('output').textContent = '收到数据: ' + value;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment