要在JavaScript中对接蓝牙并传输数据,通常需要使用Web Bluetooth API,该API允许网页与附近的蓝牙设备进行通信。然而,这个API仅在一些现代浏览器(如Chrome、Opera和Samsung Internet)中受到支持,并且需要用户的明确许可。
以下是一个使用Web Bluetooth API连接蓝牙设备并发送数据的基本步骤:
-
检查浏览器支持:
首先,你需要检查浏览器是否支持Web Bluetooth API。
javascript复制代码
if (!('bluetooth' in navigator)) { | |
console.log('Web Bluetooth API is not available.'); | |
// 通知用户或采取其他措施 | |
} |
-
请求访问蓝牙设备:
使用navigator.bluetooth.requestDevice()
方法来请求用户选择一个蓝牙设备。
javascript复制代码
navigator.bluetooth.requestDevice({ | |
filters: [{services: ['your-service-uuid']}], // 替换为你的服务UUID | |
optionalServices: ['battery-service'] // 可选服务,如电池服务 | |
}) | |
.then(device => { | |
console.log('Device connected: ', device.name); | |
// 你可以在这里保存device对象以便后续使用 | |
}) | |
.catch(error => { | |
console.error('Error occurred. Error code: ' + error.code); | |
// 处理错误 | |
}); |
-
建立GATT连接:
一旦设备被选中,你需要建立一个GATT(Generic Attribute Profile)连接来与设备进行通信。这通常是通过调用设备的gatt.connect()
方法完成的。
javascript复制代码
device.gatt.connect() | |
.then(server => { | |
console.log('Connected to GATT server'); | |
// 你可以在这里继续与设备的服务(services)和特性(characteristics)进行交互 | |
}) | |
.catch(error => { | |
console.error('Failed to connect to GATT server', error); | |
}); |
-
与服务(Service)和特性(Characteristic)交互:
在GATT连接建立后,你可以查找特定的服务(service)和特性(characteristic),并通过它们发送和接收数据。
javascript复制代码
server.getPrimaryService('your-service-uuid') | |
.then(service => { | |
return service.getCharacteristic('your-characteristic-uuid'); | |
}) | |
.then(characteristic => { | |
// 写入数据到特性 | |
const encoder = new TextEncoder(); | |
const data = encoder.encode('Hello, Bluetooth!'); | |
return characteristic.writeValue(data); | |
}) | |
.then(() => { | |
console.log('Data written to characteristic'); | |
}) | |
.catch(error => { | |
console.error('Error occurred while interacting with the characteristic', error); | |
}); |
-
读取特性值:
如果你需要读取特性的值,可以使用readValue()
方法。
javascript复制代码
characteristic.readValue() | |
.then(value => { | |
const decoder = new TextDecoder(); | |
const textValue = decoder.decode(value); | |
console.log('Characteristic value: ', textValue); | |
}) | |
.catch(error => { | |
console.error('Error occurred while reading the characteristic value', error); | |
}); |
-
监听特性值的变化:
你还可以监听特性值的变化。
javascript复制代码
characteristic.addEventListener('characteristicvaluechanged', event => { | |
const decoder = new TextDecoder(); | |
const newValue = decoder.decode(event.target.value); | |
console.log('Characteristic value changed: ', newValue); | |
}); | |
// 开始通知(可能需要先启用通知) | |
characteristic.startNotifications() | |
.then(() => { | |
console.log('Notifications started'); | |
}) | |
.catch(error => { | |
console.error('Failed to start notifications', error); | |
}); |
请注意,以上代码仅作为示例,并且可能需要根据你的具体设备和用例进行调整。另外,请确保你的设备已经配对,并且你的应用已经获得了用户的许可来访问蓝牙设备。此外,处理错误和异常情况也是非常重要的。