当前位置:首页 > uni-app

uniapp蓝牙源代码

2026-02-06 08:49:48uni-app

uniapp蓝牙源代码

uniapp蓝牙源代码

使用uniapp开发蓝牙功能的源代码示例

以下是一个基于uniapp的蓝牙功能实现示例,包含扫描、连接、读写等核心操作。

初始化蓝牙模块

// 在页面或组件中引入uni蓝牙API
export default {
  data() {
    return {
      devices: [],
      connectedDeviceId: '',
      services: [],
      characteristics: []
    }
  }
}

检查蓝牙适配器状态

checkBluetooth() {
  uni.openBluetoothAdapter({
    success: (res) => {
      console.log('蓝牙适配器初始化成功');
      this.startBluetoothDevicesDiscovery();
    },
    fail: (err) => {
      console.error('蓝牙适配器初始化失败:', err);
      uni.showToast({
        title: '请开启手机蓝牙',
        icon: 'none'
      });
    }
  });
}

开始扫描蓝牙设备

startBluetoothDevicesDiscovery() {
  uni.startBluetoothDevicesDiscovery({
    services: [], // 指定要搜索的蓝牙设备主服务UUID
    allowDuplicatesKey: false,
    success: (res) => {
      console.log('开始扫描设备');
      this.onBluetoothDeviceFound();
    },
    fail: (err) => {
      console.error('扫描失败:', err);
    }
  });
}

监听发现新设备事件

onBluetoothDeviceFound() {
  uni.onBluetoothDeviceFound((res) => {
    const devices = res.devices;
    devices.forEach(device => {
      if (!this.devices.some(d => d.deviceId === device.deviceId)) {
        this.devices.push(device);
      }
    });
  });
}

连接蓝牙设备

connectDevice(deviceId) {
  uni.createBLEConnection({
    deviceId,
    success: (res) => {
      this.connectedDeviceId = deviceId;
      console.log('连接成功', res);
      this.getBLEDeviceServices(deviceId);
    },
    fail: (err) => {
      console.error('连接失败:', err);
    }
  });
}

获取设备服务列表

getBLEDeviceServices(deviceId) {
  uni.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      this.services = res.services;
      console.log('获取服务列表成功', res.services);
      // 获取第一个服务的特征值
      if (res.services.length > 0) {
        this.getBLEDeviceCharacteristics(deviceId, res.services[0].uuid);
      }
    },
    fail: (err) => {
      console.error('获取服务失败:', err);
    }
  });
}

获取特征值

getBLEDeviceCharacteristics(deviceId, serviceId) {
  uni.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
      this.characteristics = res.characteristics;
      console.log('获取特征值成功', res.characteristics);
    },
    fail: (err) => {
      console.error('获取特征值失败:', err);
    }
  });
}

写入数据

writeBLECharacteristicValue(deviceId, serviceId, characteristicId, value) {
  const buffer = new ArrayBuffer(value.length);
  const dataView = new DataView(buffer);
  for (let i = 0; i < value.length; i++) {
    dataView.setUint8(i, value.charCodeAt(i));
  }

  uni.writeBLECharacteristicValue({
    deviceId,
    serviceId,
    characteristicId,
    value: buffer,
    success: (res) => {
      console.log('写入成功', res);
    },
    fail: (err) => {
      console.error('写入失败:', err);
    }
  });
}

读取数据

readBLECharacteristicValue(deviceId, serviceId, characteristicId) {
  uni.readBLECharacteristicValue({
    deviceId,
    serviceId,
    characteristicId,
    success: (res) => {
      console.log('读取成功', res);
    },
    fail: (err) => {
      console.error('读取失败:', err);
    }
  });
}

监听数据接收

onBLECharacteristicValueChange() {
  uni.onBLECharacteristicValueChange((res) => {
    const value = res.value;
    const dataView = new DataView(value);
    let receivedString = '';
    for (let i = 0; i < dataView.byteLength; i++) {
      receivedString += String.fromCharCode(dataView.getUint8(i));
    }
    console.log('收到数据:', receivedString);
  });
}

断开连接

disconnectDevice() {
  if (this.connectedDeviceId) {
    uni.closeBLEConnection({
      deviceId: this.connectedDeviceId,
      success: (res) => {
        console.log('断开连接成功');
        this.connectedDeviceId = '';
      },
      fail: (err) => {
        console.error('断开连接失败:', err);
      }
    });
  }
}

停止扫描

stopScan() {
  uni.stopBluetoothDevicesDiscovery({
    success: (res) => {
      console.log('停止扫描成功');
    },
    fail: (err) => {
      console.error('停止扫描失败:', err);
    }
  });
}

注意事项

  1. 需要在manifest.json中配置蓝牙权限
  2. 真机调试时需要开启手机蓝牙功能
  3. iOS和Android平台的蓝牙API行为可能有差异
  4. 部分设备可能需要配对后才能正常通信

以上代码提供了uniapp蓝牙开发的基本框架,实际应用中需要根据具体设备协议调整服务UUID和特征值处理逻辑。

标签: 蓝牙源代码
分享给朋友:

相关文章

uniapp蓝牙密码

uniapp蓝牙密码

关于UniApp蓝牙密码的使用 在UniApp中开发蓝牙功能时,涉及密码或配对码的场景通常出现在蓝牙设备连接阶段。以下是关键信息整理: 蓝牙配对流程 UniApp通过uni.connectBluet…

uniapp蓝牙有问题

uniapp蓝牙有问题

uniapp蓝牙常见问题及解决方法 蓝牙初始化失败 检查是否在manifest.json中正确配置了蓝牙权限,Android需要添加<uses-permission android:name="…

uniapp源代码没了

uniapp源代码没了

恢复或处理丢失的 Uniapp 源代码的方法 检查本地备份或版本控制 查看本地电脑的回收站、临时文件夹或备份目录,可能源代码未被彻底删除。若项目使用过 Git、SVN 等版本控制工具,可通过 git…

vue实现蓝牙开关功能

vue实现蓝牙开关功能

Vue 实现蓝牙开关功能 准备工作 确保项目环境支持 Web Bluetooth API,该 API 需要在 HTTPS 环境或本地开发环境(如 localhost)中运行。检查浏览器兼容性,Chro…

如何看java源代码

如何看java源代码

查看Java源代码的方法 使用IDE内置功能 现代Java开发工具(如IntelliJ IDEA、Eclipse)通常内置了JDK源码关联功能。按住Ctrl键(或Command键)点击类/方法名,ID…