更新记录
1.0.3(2026-05-28)
修改显示名称
1.0.2(2026-05-28)
修改文档安装
1.0.1(2026-05-28)
增加详细使用说明
查看更多
平台兼容性
uni-app(5.0)
| Vue2 |
Vue3 |
Chrome |
Safari |
app-vue |
app-nvue |
Android |
iOS |
鸿蒙 |
| - |
- |
- |
- |
- |
- |
- |
- |
5.0.0 |
| 微信小程序 |
支付宝小程序 |
抖音小程序 |
百度小程序 |
快手小程序 |
京东小程序 |
鸿蒙元服务 |
QQ小程序 |
飞书小程序 |
小红书小程序 |
快应用-华为 |
快应用-联盟 |
| - |
- |
- |
- |
- |
- |
- |
- |
- |
- |
- |
- |
uni-app x(5.08)
| Chrome |
Safari |
Android |
iOS |
鸿蒙 |
微信小程序 |
| - |
- |
- |
- |
5.0.0 |
- |
ysm-bluetooth
📘 ysm-bluetooth 插件接口文档
平台 BLE 蓝牙低功耗插件,仅支持鸿蒙。为已经使用uni-app 低功耗蓝牙,升级需要鸿蒙蓝牙的搭桥牵线
🚀 快速开始
import {ble} from '@/uni_modules/ysm-bluetooth'
// 1. 初始化蓝牙
await ble.openBluetooth()
// 2. 监听蓝牙状态
ble.onBluetoothStateChange((state) => {
console.log('蓝牙状态:', state)
})
// 3. 开始扫描
await ble.startScan()
ble.onScanDevice((devices) => {
console.log('发现设备:', devices)
})
// 4. 连接设备
await ble.connect({
deviceId: 'xx:xx:xx:xx:xx:xx'
})
// 5. 订阅通知
await ble.notifyBLECharacteristicValueChange({
deviceId: 'xx:xx:xx:xx:xx:xx',
serviceUuid: '0000ffe0-0000-1000-8000-00805f9b34fb',
charUuid: '0000ffe1-0000-1000-8000-00805f9b34fb',
state: true
})
ble.onNotify((char) => {
console.log('收到通知:', char)
})
📋 目录
📡 蓝牙状态
类型定义
type BluetoothStatus =
| 'unknown' // 未知
| 'off' // 关闭
| 'on' // 开启(经典蓝牙)
| 'bleOn' // 开启(BLE)
| 'turningOn' // 正在开启
| 'turningOff' // 正在关闭
| 'bleTurningOn' // BLE 正在开启
| 'bleTurningOff'// BLE 正在关闭
API
| 方法 |
说明 |
openBluetooth() |
开启蓝牙 |
closeBluetooth() |
关闭蓝牙 |
getBluetoothState() |
获取当前蓝牙状态 |
onBluetoothStateChange(cb) |
监听蓝牙状态变化 |
offBluetoothStateChange() |
取消监听 |
示例
// 开启蓝牙
await ble.openBluetooth()
// 获取状态
const state = await ble.getBluetoothState()
console.log(state) // 'bleOn'
// 监听变化
ble.onBluetoothStateChange((state) => {
if (state === 'bleOn') {
console.log('蓝牙已就绪,可以扫描了')
}
})
🔍 扫描设备
扫描过滤器
type ScanFilter = {
serviceUuids?: string[] // 过滤服务 UUID
name?: string // 精确匹配设备名
namePrefix?: string // 前缀匹配
interval?: number // 扫描间隔(ms)
}
扫描结果
type ScanDeviceInfo = {
deviceId: string // 设备 ID
name: string // 设备名称
rssi: number // 信号强度
advertisServiceUUIDs?: string[] // 广播的服务 UUID
localName?: string // 本地名称
advertisData: ArrayBuffer // 广播数据
serviceData?: UTSJSONObject // 服务数据
}
API
| 方法 |
说明 |
startScan(filters?) |
开始扫描 |
stopScan() |
停止扫描 |
getScanDevices() |
获取已扫描到的设备列表 |
onScanDevice(cb) |
实时监听扫描结果 |
offScanDevice() |
取消监听 |
示例
// 基础扫描
await ble.startScan()
// 带过滤条件扫描
await ble.startScan({
namePrefix: 'Mi',
serviceUuids: ['0000ffe0-0000-1000-8000-00805f9b34fb']
})
// 获取已扫描设备
const devices = ble.getScanDevices()
console.log(devices)
// 实时监听
ble.onScanDevice((devices) => {
devices.forEach(device => {
console.log(`发现: ${device.name} (${device.rssi}dBm)`)
})
})
🔗 连接管理
连接状态
type ConnectionState =
| 'disconnected' // 断开
| 'connecting' // 连接中
| 'connected' // 已连接
| 'disconnecting' // 断开中
API
| 方法 |
说明 |
connect({ deviceId, success?, fail? }) |
连接设备 |
disconnect(deviceId) |
断开连接 |
getConnectionState(deviceId) |
获取连接状态 |
setMtu(deviceId, mtu) |
设置 MTU(默认 23) |
onConnectionStateChange(cb) |
监听连接状态变化 |
offConnectionStateChange() |
取消监听 |
示例
// 连接设备
await ble.connect({
deviceId: 'AA:BB:CC:DD:EE:FF',
success: () => console.log('连接成功'),
fail: (err) => console.error('连接失败', err)
})
// 检查状态
const state = ble.getConnectionState('AA:BB:CC:DD:EE:FF')
// 'connected'
// 设置 MTU
await ble.setMtu('AA:BB:CC:DD:EE:FF', 512)
// 监听状态
ble.onConnectionStateChange((deviceId, state) => {
if (state === 'connected') {
console.log(`${deviceId} 已连接`)
} else if (state === 'disconnected') {
console.log(`${deviceId} 已断开`)
}
})
📋 GATT 服务与特征值
设备服务
type DeviceService = {
uuid: string
isPrimary: boolean
characteristics: DeviceCharacteristic[]
}
特征值属性
type Properties = {
read?: boolean
write?: boolean
writeNoResponse?: boolean
notify?: boolean
indicate?: boolean
}
特征值
interface DeviceCharacteristic extends Characteristic {
properties?: Properties
value: ArrayBuffer
}
interface Characteristic {
deviceId: string
serviceUuid?: string
charUuid?: string
}
API
| 方法 |
说明 |
getServices(deviceId) |
获取设备所有服务 |
getCharacteristics(deviceId, serviceUuid) |
获取服务下的特征值 |
示例
// 获取服务列表
const services = await ble.getServices('AA:BB:CC:DD:EE:FF')
console.log(services)
// 获取特征值
const chars = await ble.getCharacteristics(
'AA:BB:CC:DD:EE:FF',
'0000ffe0-0000-1000-8000-00805f9b34fb'
)
chars.forEach(char => {
console.log(`特征值: ${char.charUuid}`)
console.log(`属性: ${JSON.stringify(char.properties)}`)
console.log(`值: ${char.value}`)
})
📤 数据读写
写特征值
interface WriteCharacteristic extends Characteristic {
value: ArrayBuffer
writeType?: 'write' | 'writeNoResponse' // 默认 write
}
读特征值
interface ReadCharacteristic extends Characteristic {
// 空接口,继承 deviceId, serviceUuid, charUuid
}
API
| 方法 |
说明 |
writeCharacteristic(write) |
写入数据 |
readCharacteristic(read) |
读取数据(返回 DeviceCharacteristic) |
示例
// 写入数据(不响应)
await ble.writeCharacteristic({
deviceId: 'AA:BB:CC:DD:EE:FF',
serviceUuid: '0000ffe0-0000-1000-8000-00805f9b34fb',
charUuid: '0000ffe1-0000-1000-8000-00805f9b34fb',
value: new ArrayBuffer(8),
writeType: 'writeNoResponse'
})
// 读取数据
const char = await ble.readCharacteristic({
deviceId: 'AA:BB:CC:DD:EE:FF',
serviceUuid: '0000ffe0-0000-1000-8000-00805f9b34fb',
charUuid: '0000ffe1-0000-1000-8000-00805f9b34fb'
})
console.log('读取到的值:', char.value)
📥 通知订阅
订阅参数
interface Notify extends Characteristic {
state: boolean // true=订阅, false=取消
}
API
| 方法 |
说明 |
notifyBLECharacteristicValueChange(notify) |
开启/关闭通知 |
onNotify(cb) |
监听通知数据 |
offNotify() |
取消监听 |
示例
// 开启通知
await ble.notifyBLECharacteristicValueChange({
deviceId: 'AA:BB:CC:DD:EE:FF',
serviceUuid: '0000ffe0-0000-1000-8000-00805f9b34fb',
charUuid: '0000ffe1-0000-1000-8000-00805f9b34fb',
state: true
})
// 接收通知
ble.onNotify((char) => {
console.log('收到通知:', char)
console.log('数据:', new Uint8Array(char.value))
})
// 关闭通知
await ble.notifyBLECharacteristicValueChange({
deviceId: 'AA:BB:CC:DD:EE:FF',
serviceUuid: '0000ffe0-0000-1000-8000-00805f9b34fb',
charUuid: '0000ffe1-0000-1000-8000-00805f9b34fb',
state: false
})
🔧 MTU 设置
MTU(Maximum Transmission Unit)最大传输单元,默认 23 字节,最大可设 512 字节。
API
| 方法 |
说明 |
setMtu(deviceId, mtu) |
设置 MTU(返回实际值) |
onMtuChanged(cb) |
监听 MTU 变化 |
offMtuChanged() |
取消监听 |
示例
// 设置 MTU
const mtu = await ble.setMtu('AA:BB:CC:DD:EE:FF', 512)
console.log('MTU:', mtu)
// 监听变化
ble.onMtuChanged((deviceId, mtu) => {
console.log(`${deviceId} MTU 变更为: ${mtu}`)
})
🎧 回调系统
| 回调类型 |
参数 |
说明 |
BleStateCallback |
state: BluetoothStatus |
蓝牙状态变化 |
BleScanCallback |
devices: ScanDeviceInfo[] |
扫描到新设备 |
BleDeviceCallback |
deviceId, state: ConnectionState |
连接状态变化 |
BleNotifyCallback |
char: DeviceCharacteristic |
收到通知数据 |
BleMtuCallback |
deviceId, mtu: number |
MTU 变化 |
🧹 资源清理
ble.destroy() // 销毁插件实例,释放资源
💡 完整示例:心率监测
import BlePlugin from 'ysm-bluetooth'
const ble = uni.requireNativePlugin('ysm-bluetooth') as BlePlugin
async function startHeartRateMonitor() {
try {
// 1. 开启蓝牙
await ble.openBluetooth()
// 2. 监听状态
ble.onBluetoothStateChange((state) => {
if (state === 'bleOn') {
startScan()
}
})
// 3. 扫描设备
await ble.startScan()
ble.onScanDevice((devices) => {
devices.forEach(device => {
if (device.name?.includes('Mi Band')) {
connectDevice(device.deviceId)
}
})
})
// 4. 连接
await ble.connect({ deviceId: 'AA:BB:CC:DD:EE:FF' })
// 5. 监听连接
ble.onConnectionStateChange((deviceId, state) => {
if (state === 'connected') {
getServices()
}
})
// 6. 获取服务
const services = await ble.getServices('AA:BB:CC:DD:EE:FF')
const hrService = services.find(s =>
s.uuid === '0000180d-0000-1000-8000-00805f9b34fb'
)
if (hrService) {
// 7. 订阅心率通知
await ble.notifyBLECharacteristicValueChange({
deviceId: 'AA:BB:CC:DD:EE:FF',
serviceUuid: hrService.uuid,
charUuid: '00002a37-0000-1000-8000-00805f9b34fb',
state: true
})
// 8. 接收数据
ble.onNotify((char) => {
const data = new Uint8Array(char.value)
const heartRate = data[1] // 简化解析
console.log(`心率: ${heartRate} bpm`)
})
}
} catch (err) {
console.error('初始化失败:', err)
}
}
// 清理
onUnmount(() => {
ble.offBluetoothStateChange()
ble.offScanDevice()
ble.offConnectionStateChange()
ble.offNotify()
ble.offMtuChanged()
ble.destroy()
})
⚠️ 注意事项
| 项目 |
说明 |
| 🔐 权限 |
需要蓝牙权限(Android: BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_FINE_LOCATION) |
| 📡 扫描间隔 |
建议设置 interval: 3000 避免耗电过快 |
| 🔌 连接数量 |
同时最多连接 7 个设备 |
| 📦 数据格式 |
所有二进制数据使用 ArrayBuffer,需要手动转换 |
| 🧹 及时清理 |
使用完记得调用 destroy() 和 offXxx() |
📦 安装
https://ext.dcloud.net.cn/plugin?name=ysm-bluetooth
📝 更新日志
| 版本 |
日期 |
更新内容 |
| v1.0.0 |
2024-01 |
初始版本,支持全平台 |
📧 如有问题请提交评论
⭐ 如果觉得有用,请给个 Star ⭐
开发文档
UTS 语法
UTS API插件
UTS uni-app兼容模式组件
UTS 标准模式组件
Hello UTS