当前位置:首页 > VUE

vue实现蓝牙开关功能

2026-02-23 16:30:05VUE

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 项目中实现基础的蓝牙开关控制功能。

vue实现蓝牙开关功能

标签: 蓝牙功能
分享给朋友:

相关文章

前端实现拖拽功能vue

前端实现拖拽功能vue

实现拖拽功能的基本方法 在Vue中实现拖拽功能可以通过HTML5的拖放API或第三方库如vuedraggable来完成。HTML5的拖放API提供了原生支持,而vuedraggable则简化了列表拖拽…

vue实现功能

vue实现功能

Vue 实现功能的方法 Vue.js 是一个流行的前端框架,用于构建用户界面。以下是几种常见的功能实现方法: 数据绑定 Vue 提供了双向数据绑定,可以通过 v-model 指令实现表单输入和应用…

vue 实现 功能

vue 实现 功能

Vue.js 是一个流行的前端框架,用于构建用户界面和单页应用程序。以下是一些常见的 Vue 功能实现方法: 数据绑定 Vue 的核心特性之一是数据绑定,可以通过 v-model 指令实现双向数据…

php怎么实现登录功能

php怎么实现登录功能

数据库准备 创建用户表存储登录信息,通常包括用户名、密码(需加密)等字段。示例SQL: CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY…

vue实现换页功能

vue实现换页功能

Vue 实现分页功能 使用第三方库(如 Element UI) 安装 Element UI: npm install element-ui 在 main.js 中引入: import Vue fr…

php购物车功能实现

php购物车功能实现

数据库设计 购物车功能通常需要设计数据库表来存储商品和用户信息。常见的表包括: products 表:存储商品信息,如商品ID、名称、价格、库存等。 users 表:存储用户信息,如用户ID、用户名…