使用Web Bluetooth API开发手机蓝牙通信网页应用
以下是一个简单的Web页面示例,用于通过低功耗蓝牙(Bluetooth Low Energy)发送和接收信息。请注意,此示例仅适用于支持Web Bluetooth API的浏览器。
<!DOCTYPE html>
<html>
<head>
<title>Web Bluetooth Demo</title>
</head>
<body>
<button onclick='connect()'>连接蓝牙设备</button>
<button onclick='disconnect()'>断开蓝牙连接</button>
<input type='text' id='messageInput' placeholder='输入要发送的信息'>
<button onclick='sendMessage()'>发送信息</button>
<div id='receivedMessages'></div>
<script>
let bluetoothDevice;
let receivedMessages = [];
async function connect() {
try {
// 请求蓝牙设备
bluetoothDevice = await navigator.bluetooth.requestDevice({
filters: [{ services: ['generic_access'] }]
});
// 连接蓝牙设备
await bluetoothDevice.gatt.connect();
// 监听接收到的特征值变化
const service = await bluetoothDevice.gatt.getPrimaryService('generic_access');
const characteristic = await service.getCharacteristic('generic_access');
await characteristic.startNotifications();
characteristic.addEventListener('characteristicvaluechanged', handleCharacteristicValueChanged);
console.log('已连接蓝牙设备');
} catch (error) {
console.error('连接蓝牙设备时出错:', error);
}
}
function disconnect() {
if (!bluetoothDevice) return;
bluetoothDevice.gatt.disconnect();
bluetoothDevice = null;
console.log('已断开蓝牙连接');
}
async function sendMessage() {
if (!bluetoothDevice) {
console.error('尚未连接蓝牙设备');
return;
}
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
if (!message) {
console.error('请输入要发送的信息');
return;
}
const service = await bluetoothDevice.gatt.getPrimaryService('generic_access');
const characteristic = await service.getCharacteristic('generic_access');
const encoder = new TextEncoder();
await characteristic.writeValue(encoder.encode(message));
messageInput.value = '';
console.log('已发送信息:', message);
}
function handleCharacteristicValueChanged(event) {
const value = event.target.value;
const decoder = new TextDecoder();
const message = decoder.decode(value);
receivedMessages.push(message);
updateReceivedMessages();
console.log('已接收到信息:', message);
}
function updateReceivedMessages() {
const receivedMessagesDiv = document.getElementById('receivedMessages');
receivedMessagesDiv.innerHTML = '';
for (let message of receivedMessages) {
const messageElement = document.createElement('p');
messageElement.textContent = message;
receivedMessagesDiv.appendChild(messageElement);
}
}
</script>
</body>
</html>
在这个示例中,我们使用了Web Bluetooth API来请求用户选择一个低功耗蓝牙设备,连接到该设备,并通过通知接收和发送信息。页面上有几个按钮和输入框,用于执行连接、断开连接、发送信息的操作。接收到的信息会显示在页面上。
请注意,此示例仅包含了基本的功能,你可能需要在实际应用中根据自己的需求进行修改和扩展。
原文地址: http://www.cveoy.top/t/topic/pg5t 著作权归作者所有。请勿转载和采集!