vue实现蓝牙开关功能
Vue 实现蓝牙开关功能
准备工作
确保项目环境支持 Web Bluetooth API,该 API 需要在 HTTPS 环境或本地开发环境(如 localhost)中运行。检查浏览器兼容性,Chrome、Edge 和 Opera 支持较好。
检测蓝牙支持
在 Vue 组件中,通过 navigator.bluetooth 检测浏览器是否支持蓝牙功能。若不支持,需提示用户更换浏览器或环境。
mounted() {
if (!navigator.bluetooth) {
console.error('Web Bluetooth API is not supported in this browser.');
}
}
请求蓝牙设备
使用 navigator.bluetooth.requestDevice 方法扫描并连接蓝牙设备。需指定设备过滤条件(如服务 UUID)。
methods: {
async connectToDevice() {
try {
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true, // 或指定 filters
optionalServices: ['generic_access'] // 需要的服务
});
this.device = device;
console.log('Connected to:', device.name);
} catch (error) {
console.error('Connection failed:', error);
}
}
}
开关功能实现
通过获取设备的 GATT 服务并操作特征值(Characteristic)实现开关控制。假设蓝牙设备有一个可写的特征值用于控制开关。
methods: {
async toggleBluetoothDevice(powerOn) {
if (!this.device) {
console.error('No device connected.');
return;
}
try {
const server = await this.device.gatt.connect();
const service = await server.getPrimaryService('generic_access');
const characteristic = await service.getCharacteristic('power_control');
const value = powerOn ? new Uint8Array([1]) : new Uint8Array([0]);
await characteristic.writeValue(value);
console.log('Device state set to:', powerOn ? 'ON' : 'OFF');
} catch (error) {
console.error('Toggle failed:', error);
}
}
}
断开连接
主动断开蓝牙连接以释放资源。
methods: {
disconnectDevice() {
if (this.device && this.device.gatt.connected) {
this.device.gatt.disconnect();
console.log('Device disconnected.');
}
}
}
完整示例组件
整合上述代码的 Vue 组件示例:
<template>
<div>
<button @click="connectToDevice">Connect</button>
<button @click="toggleBluetoothDevice(true)">Turn On</button>
<button @click="toggleBluetoothDevice(false)">Turn Off</button>
<button @click="disconnectDevice">Disconnect</button>
</div>
</template>
<script>
export default {
data() {
return {
device: null
};
},
methods: {
async connectToDevice() {
try {
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: ['generic_access']
});
this.device = device;
} catch (error) {
console.error(error);
}
},
async toggleBluetoothDevice(powerOn) {
if (!this.device) return;
try {
const server = await this.device.gatt.connect();
const service = await server.getPrimaryService('generic_access');
const characteristic = await service.getCharacteristic('power_control');
await characteristic.writeValue(new Uint8Array([powerOn ? 1 : 0]));
} catch (error) {
console.error(error);
}
},
disconnectDevice() {
if (this.device?.gatt.connected) {
this.device.gatt.disconnect();
}
}
}
};
</script>
注意事项
- 权限:首次调用
requestDevice会触发用户授权弹窗,需用户手动允许。 - 错误处理:蓝牙操作可能因信号、权限或设备问题失败,需捕获并处理异常。
- 设备兼容性:不同蓝牙设备的服务 UUID 和特征值可能不同,需根据实际设备文档调整代码。
通过以上步骤,可以在 Vue 项目中实现基础的蓝牙开关控制功能。







