A comprehensive BLE (Bluetooth Low Energy) SDK for uniapp with connection management, device discovery, and data handling
npm install @leir0ng/uniapp-ble-sdkbash
npm install uniapp-ble-sdk
`
快速开始
$3
`typescript
import { BLEManager, BLEEventType, ConnectionState } from 'uniapp-ble-sdk';
// 创建BLE管理器实例
const bleManager = new BLEManager({
autoReconnect: true,
reconnectInterval: 3000,
maxReconnectAttempts: 5
});
// 初始化
await bleManager.initialize();
// 监听事件
bleManager.on(BLEEventType.DEVICE_FOUND, (device) => {
console.log('发现设备:', device);
});
bleManager.on(BLEEventType.CONNECTION_STATE_CHANGE, (event) => {
console.log('连接状态变化:', event);
});
// 开始搜索设备
await bleManager.startDeviceDiscovery({
nameKeyword: 'MyDevice',
minRSSI: -80
});
// 连接设备
await bleManager.connect('device-id');
// 获取服务和特征值
const services = await bleManager.getDeviceServices();
const characteristics = await bleManager.getDeviceCharacteristics(serviceId);
// 启用通知
await bleManager.notifyCharacteristicValueChange(serviceId, characteristicId);
// 监听数据
bleManager.on(BLEEventType.CHARACTERISTIC_VALUE_CHANGE, (data) => {
console.log('收到数据:', data);
});
// 写入数据
const buffer = new ArrayBuffer(4);
await bleManager.writeCharacteristicValue(serviceId, characteristicId, buffer);
// 断开连接
await bleManager.disconnect();
// 销毁管理器
await bleManager.destroy();
`
API 文档
$3
主要的 BLE 管理类。
#### 构造函数
`typescript
constructor(options?: BLEOptions)
`
参数:
- options - 可选配置项
`typescript
interface BLEOptions {
allowDuplicatesKey?: boolean; // 是否允许重复上报同一设备,默认 false
interval?: number; // 上报设备间隔(ms),默认 0
autoReconnect?: boolean; // 是否启用自动重连,默认 true
reconnectInterval?: number; // 重连间隔(ms),默认 3000
maxReconnectAttempts?: number; // 最大重连次数,默认 5
connectionTimeout?: number; // 连接超时时间(ms),默认 10000
}
`
#### 方法
##### initialize(): Promise
初始化蓝牙适配器。
`typescript
await bleManager.initialize();
`
##### destroy(): Promise
销毁管理器,关闭所有连接和监听。
`typescript
await bleManager.destroy();
`
##### getAdapterState(): Promise
获取蓝牙适配器状态。
`typescript
const state = await bleManager.getAdapterState();
console.log('蓝牙可用:', state.available);
console.log('正在搜索:', state.discovering);
`
##### startDeviceDiscovery(filter?: DeviceFilter): Promise
开始搜索蓝牙设备。
`typescript
// 搜索所有设备
await bleManager.startDeviceDiscovery();
// 使用过滤器搜索
await bleManager.startDeviceDiscovery({
nameKeyword: 'sensor',
minRSSI: -70,
services: ['180F'] // 电池服务
});
`
##### stopDeviceDiscovery(): Promise
停止搜索蓝牙设备。
`typescript
await bleManager.stopDeviceDiscovery();
`
##### getDiscoveredDevices(): BLEDevice[]
获取已发现的设备列表。
`typescript
const devices = bleManager.getDiscoveredDevices();
`
##### connect(deviceId: string): Promise
连接到指定设备。
`typescript
await bleManager.connect('device-id-123');
`
##### disconnect(): Promise
断开当前连接。
`typescript
await bleManager.disconnect();
`
##### getDeviceServices(deviceId?: string): Promise
获取设备服务列表。
`typescript
const services = await bleManager.getDeviceServices();
`
##### getDeviceCharacteristics(serviceId: string, deviceId?: string): Promise
获取设备特征值列表。
`typescript
const characteristics = await bleManager.getDeviceCharacteristics('180F');
`
##### getDeviceRSSI(deviceId?: string): Promise
获取设备信号强度。
`typescript
const rssi = await bleManager.getDeviceRSSI();
`
##### notifyCharacteristicValueChange(serviceId: string, characteristicId: string, state?: boolean, deviceId?: string): Promise
启用或禁用特征值变化通知。
`typescript
// 启用通知
await bleManager.notifyCharacteristicValueChange(serviceId, characteristicId, true);
// 禁用通知
await bleManager.notifyCharacteristicValueChange(serviceId, characteristicId, false);
`
##### readCharacteristicValue(serviceId: string, characteristicId: string, deviceId?: string): Promise
读取特征值。
`typescript
const data = await bleManager.readCharacteristicValue(serviceId, characteristicId);
`
##### writeCharacteristicValue(serviceId: string, characteristicId: string, value: ArrayBuffer, writeType?: WriteType, deviceId?: string): Promise
写入特征值。
`typescript
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setUint32(0, 1234, true);
await bleManager.writeCharacteristicValue(
serviceId,
characteristicId,
buffer,
WriteType.WRITE
);
`
##### setMTU(mtu: number, deviceId?: string): Promise
设置最大传输单元 (22-512)。
`typescript
await bleManager.setMTU(247);
`
##### getConnectionState(): ConnectionState
获取当前连接状态。
`typescript
const state = bleManager.getConnectionState();
`
##### getConnectedDevice(): BLEDevice | null
获取当前连接的设备信息。
`typescript
const device = bleManager.getConnectedDevice();
`
#### 事件监听
##### on(event: string, callback: EventCallback): void
添加事件监听器。
`typescript
bleManager.on(BLEEventType.DEVICE_FOUND, (device) => {
console.log('发现设备:', device);
});
`
##### off(event: string, callback?: EventCallback): void
移除事件监听器。
`typescript
bleManager.off(BLEEventType.DEVICE_FOUND, callback);
// 或移除所有监听器
bleManager.off(BLEEventType.DEVICE_FOUND);
`
$3
`typescript
enum BLEEventType {
ADAPTER_STATE_CHANGE = 'adapterStateChange', // 适配器状态变化
DEVICE_FOUND = 'deviceFound', // 发现新设备
CONNECTION_STATE_CHANGE = 'connectionStateChange', // 连接状态变化
CHARACTERISTIC_VALUE_CHANGE = 'characteristicValueChange', // 特征值变化
ERROR = 'error' // 错误事件
}
`
$3
`typescript
enum ConnectionState {
DISCONNECTED = 'disconnected', // 未连接
CONNECTING = 'connecting', // 连接中
CONNECTED = 'connected', // 已连接
DISCONNECTING = 'disconnecting' // 断开连接中
}
`
$3
`typescript
enum WriteType {
WRITE = 'write', // 需要回复
WRITE_NO_RESPONSE = 'writeNoResponse' // 不需要回复
}
`
完整示例
$3
`vue
v-for="device in devices"
:key="device.deviceId"
class="device-item"
@click="connectDevice(device.deviceId)"
>
{{ device.name || device.localName || '未知设备' }}
{{ device.RSSI }}dBm
已连接: {{ connectedDevice.name }}
{{ log.message }}
`
注意事项
1. 权限配置: 确保在 manifest.json 中配置了蓝牙权限:
`json
{
"mp-weixin": {
"permission": {
"scope.bluetooth": {
"desc": "用于连接蓝牙设备"
}
}
},
"app-plus": {
"modules": {
"Bluetooth": {}
}
}
}
``