如何在uniapp中使用蓝牙(api版)

130 阅读3分钟
  1. 初始化蓝牙适配器: 使用uni.openBluetoothAdapter()方法初始化蓝牙适配器,该方法返回一个Promise对象,可以通过then方法来获取初始化结果。
uni.openBluetoothAdapter().then(res => {
  console.log('蓝牙适配器初始化成功');
}).catch(err => {
  console.log('蓝牙适配器初始化失败:', err);
});
  1. 监听蓝牙适配器状态变化: 使用uni.onBluetoothAdapterStateChange()方法监听蓝牙适配器状态变化,可以在回调函数中获取到蓝牙适配器的当前状态。
uni.onBluetoothAdapterStateChange(function(res) {
  console.log('蓝牙适配器状态变化:', res);
});
  1. 开始搜索蓝牙设备: 使用uni.startBluetoothDevicesDiscovery()方法开始搜索蓝牙设备,该方法返回一个Promise对象,可以通过then方法来获取搜索结果。
uni.startBluetoothDevicesDiscovery().then(res => {
  console.log('开始搜索蓝牙设备成功');
}).catch(err => {
  console.log('开始搜索蓝牙设备失败:', err);
});
  1. 监听蓝牙设备发现事件: 使用uni.onBluetoothDeviceFound()方法监听蓝牙设备发现事件,可以在回调函数中获取到搜索到的蓝牙设备信息。
uni.onBluetoothDeviceFound(function(res) {
  console.log('蓝牙设备发现:', res);
});
  1. 停止搜索蓝牙设备: 使用uni.stopBluetoothDevicesDiscovery()方法停止搜索蓝牙设备。
uni.stopBluetoothDevicesDiscovery();
  1. 连接蓝牙设备: 使用uni.createBLEConnection()方法连接蓝牙设备,该方法返回一个Promise对象,可以通过then方法来获取连接结果。
uni.createBLEConnection({ deviceId: '蓝牙设备ID' }).then(res => {
  console.log('蓝牙设备连接成功');
}).catch(err => {
  console.log('蓝牙设备连接失败:', err);
});
  1. 监听蓝牙连接状态变化: 使用uni.onBLEConnectionStateChange()方法监听蓝牙连接状态变化,可以在回调函数中获取到蓝牙设备的当前连接状态。
uni.onBLEConnectionStateChange(function(res) {
  console.log('蓝牙连接状态变化:', res);
});
  1. 断开蓝牙连接: 使用uni.closeBLEConnection()方法断开蓝牙设备的连接。
uni.closeBLEConnection({ deviceId: '蓝牙设备ID' });
  1. 获取蓝牙设备服务列表: 使用uni.getBLEDeviceServices()方法获取蓝牙设备的服务列表,该方法返回一个Promise对象,可以通过then方法来获取服务列表。
uni.getBLEDeviceServices({ deviceId: '蓝牙设备ID' }).then(res => {
  console.log('蓝牙设备服务列表:', res.services);
}).catch(err => {
  console.log('获取蓝牙设备服务列表失败:', err);
});
  1. 获取蓝牙设备特征值列表: 使用uni.getBLEDeviceCharacteristics()方法获取蓝牙设备的特征值列表,该方法返回一个Promise对象,可以通过then方法来获取特征值列表。
uni.getBLEDeviceCharacteristics({ deviceId: '蓝牙设备ID', serviceId: '服务ID' }).then(res => {
  console.log('蓝牙设备特征值列表:', res.characteristics);
}).catch(err => {
  console.log('获取蓝牙设备特征值列表失败:', err);
});
  1. 读取蓝牙设备特征值的值: 使用uni.readBLECharacteristicValue()方法读取蓝牙设备特征值的值,该方法返回一个Promise对象,可以通过then方法来获取特征值的值。
uni.readBLECharacteristicValue({ deviceId: '蓝牙设备ID', serviceId: '服务ID', characteristicId: '特征值ID' }).then(res => {
  console.log('读取蓝牙设备特征值的值:', res.characteristic.value);
}).catch(err => {
  console.log('读取蓝牙设备特征值的值失败:', err);
});
  1. 向蓝牙设备特征值写入数据: 使用uni.writeBLECharacteristicValue()方法向蓝牙设备特征值写入数据,该方法返回一个Promise对象,可以通过then方法来获取写入结果。
uni.writeBLECharacteristicValue({ deviceId: '蓝牙设备ID', serviceId: '服务ID', characteristicId: '特征值ID', value: '要写入的数据' }).then(res => {
  console.log('向蓝牙设备特征值写入数据成功');
}).catch(err => {
  console.log('向蓝牙设备特征值写入数据失败:', err);
});