更新记录

1.0.1(2026-08-03)

新增

  • 硬件串口模式 mode: 'serial',支持 Android 工业板 / 收银秤 /dev/ttyS* 通讯
  • 简洁 API(推荐):
    • connect — 蓝牙连接 / 串口打开(自动初始化蓝牙适配器)
    • disconnect — 断开连接 / 关闭串口
    • send — 统一发送(text / hex / data 三选一)
    • scan — 扫描蓝牙(自动初始化适配器)
    • listPorts — 列出可用硬件串口路径
  • 串口参数可一次性配置:波特率、数据位、停止位、校验位、流控
  • 错误码 10023:串口无读写权限
  • OnDataReceivedResult 增加 modeisSendEcho(串口发送回显)字段
  • GetConnectionStateResult 增加串口参数字段(baudRate / dataBits / stopBits / parity

优化

  • BLE / SPP / 串口统一由 lq-bluetooth 一个插件提供,共用 onDataReceived / onConnectionStateChange
  • 旧 API(connectDevicesendString 等)内部转发至简洁 API,保持兼容
  • 串口库改为本地 AAR(libs/Android-SerialPort-1.5.1.aar),避免 JitPack 在线依赖编译失败
  • 完善 readme.md API 文档

Demo

  • 合并蓝牙 + 串口 Demo 至 pages/bluetooth/demo.uvue
  • 新增「串口」模式:端口列表、波特率配置、连接/收发
  • 扫描改用 scan(),发送改用 send()

修复

  • 修复串口 String(bytes, charset) UTS 编译类型错误
  • 修复 Demo 中 UTS 不支持函数提升、undefined 等问题


平台兼容性

uni-app(5.22)

Vue2 Vue3 Chrome Safari app-vue app-nvue Android iOS 鸿蒙
- - × × × × 5.0 × 2.0.0
微信小程序 支付宝小程序 抖音小程序 百度小程序 快手小程序 京东小程序 鸿蒙元服务 QQ小程序 飞书小程序 小红书小程序 快应用-华为 快应用-联盟
× × - - - - - - - - - -

uni-app x(5.22)

Chrome Safari Android iOS 鸿蒙 微信小程序
- - 5.0 × 2.0.0 -

lq-bluetooth

Android 设备通讯 UTS 插件,统一 API 支持:

模式 说明 典型场景
ble BLE GATT 低功耗蓝牙 HM-10、nRF、BLE 串口模块
spp 经典蓝牙 RFCOMM HC-05/06 等已配对串口
serial 硬件串口 /dev/ttyS* 收银秤、工业安卓板

适用:数据透传(AT 指令、传感器、称重协议等)
不适用:蓝牙耳机/音箱音频(A2DP/HFP,走系统音频协议)

平台:仅 Android App 完整可用;iOS / Web / 鸿蒙为占位实现。


安装与调试

  1. uni_modules/lq-bluetooth 放入项目
  2. UTS 修改后必须 重新制作自定义调试基座
  3. Demo:pages/bluetooth/demo.uvue
  4. 编译异常时删除 unpackage/cache/uts_custom_android 后重试(Windows 开发机偶发 EBUSY: index.jar

导入方式

// 函数
import {
  connect, disconnect, send, scan, listPorts,
  getConnectionState, onDataReceived, onDeviceFound
} from '@/uni_modules/lq-bluetooth'

// 类型(Web 预览需分开导入)
import type {
  ConnectOptions,
  SendOptions,
  OnDataReceivedResult,
  GetConnectionStateResult
} from '@/uni_modules/lq-bluetooth'

核心概念

连接模式 mode

说明
ble 低功耗 GATT,默认模式
spp 经典蓝牙 SPP
serial Android 硬件串口

未传 mode 时,蓝牙 API 默认 blesend / disconnect 等会沿用最近一次 connect 的模式。

数据通道就绪 ready

模式 connected ready
BLE GATT 已连接 Notify 已启用且读写特征可用
SPP RFCOMM 已连接 同 connected
serial 串口已打开 同 connected

BLE 可能出现「已连接但发不出/收不到」——此时 ready === false,需检查特征值或手动 setBLECharacteristics

回调约定

所有 API 采用 uni 风格:success / fail / complete。事件监听使用 onXxx / offXxx


推荐 API(简洁)

API 总览

API 说明
scan 扫描蓝牙设备(自动初始化适配器)
connect 连接蓝牙 / 打开串口(自动初始化蓝牙)
disconnect 断开连接 / 关闭串口
send 发送数据(text / hex / data 三选一)
listPorts 列出硬件串口路径(仅 serial)
getConnectionState 查询连接与通道状态

scan(options) — 扫描蓝牙

scan({
  mode: 'ble',              // 'ble' | 'spp',不支持 serial
  filterNameless: true,     // 隐藏无名称设备
  minRssi: -85,             // 最小信号强度 dBm
  nameKeywords: ['HM', 'nRF'],
  connectableOnly: true,    // 仅 BLE 可连接设备(Android 8+)
  services: ['FFE0'],        // BLE 服务 UUID 过滤(可选)
  success: () => {},
  fail: (err) => console.error(err.errMsg)
})

配合 onDeviceFound / onDiscoveryFinished 使用;扫描结束需自行 stopDiscovery 或定时停止。

参数 类型 默认 说明
mode 'ble' \| 'spp' ble 扫描模式
filterNameless boolean false 过滤 Unknown / 空名称
minRssi number 弱于该值不回调
nameKeywords string[] 名称包含任一关键词(不区分大小写)
connectableOnly boolean false 仅 BLE 可连接设备
services string[] BLE 服务 UUID 过滤

connect(options) — 连接 / 打开

BLE / SPP:

connect({
  mode: 'ble',
  deviceId: 'AA:BB:CC:DD:EE:FF',
  timeout: 15000,
  autoSelectCharacteristics: true,  // BLE 自动选读写特征,默认 true
  autoBond: false,                  // BLE 是否强制系统配对,默认 false
  // 手动指定 UUID(可选)
  serviceId: 'FFE0',
  writeCharacteristicId: 'FFE1',
  notifyCharacteristicId: 'FFE1',
  success: () => {},
  fail: (err) => console.error(err.errMsg)
})

硬件串口:

connect({
  mode: 'serial',
  path: '/dev/ttyS1',       // 也可用 deviceId 传路径
  baudRate: 9600,             // 默认 9600
  dataBits: 8,                // 默认 8
  stopBits: 1,                // 默认 1
  parity: 0,                  // 0无/1奇/2偶,默认 0
  flowCon: 0,
  flags: 0,
  success: () => {},
  fail: (err) => console.error(err.errMsg)
})
参数 类型 适用 说明
mode ConnectionMode 全部 连接模式
deviceId string ble/spp 设备 MAC
path string serial 串口路径,如 /dev/ttyS1
timeout number ble/spp 超时 ms,默认 10000
secure boolean spp 加密 RFCOMM,默认 false
serviceId string ble 服务 UUID,可短格式 FFE0
writeCharacteristicId string ble 写特征 UUID
notifyCharacteristicId string ble 通知特征 UUID
autoSelectCharacteristics boolean ble 自动选特征,默认 true
autoBond boolean ble 连接前强制配对,默认 false
baudRate number serial 波特率,默认 9600
dataBits number serial 数据位,默认 8
stopBits number serial 停止位,默认 1
parity number serial 校验位,默认 0
flowCon number serial 流控,默认 0
flags number serial 打开标志 O_RDWR,默认 0

send(options) — 发送

text / hex / data 三选一,优先级:hex > text > data

send({ text: 'AT\r\n' })
send({ hex: '50 0D 0A' })           // 支持空格分隔或连续 hex
send({ data: [0x50, 0x0D, 0x0A] })
send({ mode: 'serial', text: 'P\r\n' })  // 可显式指定 mode
参数 类型 说明
mode ConnectionMode 可选,默认最近一次 connect 的模式
text string 文本,默认 UTF-8
hex string 十六进制字符串
data number[] 字节数组
encoding string text 编码,默认 UTF-8

disconnect(options) — 断开

disconnect({ mode: 'ble' })    // 可省略 mode,使用当前活跃模式

listPorts(options) — 串口列表

listPorts({
  success: (res) => {
    console.log(res.paths)     // ["/dev/ttyS0", "/dev/ttyS1", ...]
    console.log(res.devices)   // [{ name, root, path }, ...]
  }
})

getConnectionState(options) — 状态查询

getConnectionState({
  mode: 'ble',
  success: (res) => {
    console.log(res.connected, res.ready, res.deviceId)
    // BLE 额外:res.serviceId, res.writeCharacteristicId, res.notifyCharacteristicId
    // serial 额外:res.baudRate, res.dataBits, res.stopBits, res.parity
  }
})

事件监听

监听 说明 适用模式
onDeviceFound / offDeviceFound 发现设备 ble / spp
onDiscoveryFinished / offDiscoveryFinished 扫描结束 ble / spp
onConnectionStateChange / offConnectionStateChange 连接/断开 全部
onDataReceived / offDataReceived 收到数据 全部
onBondStateChange / offBondStateChange 配对状态 ble / spp
onBluetoothAdapterStateChange / offBluetoothAdapterStateChange 蓝牙开关 ble / spp

onDataReceived 回调结构

onDataReceived((res) => {
  res.mode        // 'ble' | 'spp' | 'serial'
  res.deviceId    // MAC 或串口路径
  res.data        // number[] 原始字节
  res.text        // UTF-8 文本预览
  res.isSendEcho  // serial 专用:true 表示发送回显
})

配对状态 bondState

含义
10 未配对
11 配对中
12 已配对

场景示例

BLE 完整流程

import {
  scan, connect, send, disconnect,
  stopDiscovery, getConnectionState,
  onDeviceFound, onConnectionStateChange, onDataReceived
} from '@/uni_modules/lq-bluetooth'

onDeviceFound((res) => {
  console.log(res.device.name, res.device.deviceId, res.device.rssi)
})

onConnectionStateChange((res) => {
  console.log('连接', res.connected, res.ready)
})

onDataReceived((res) => {
  console.log('收←', res.text)
})

// 扫描
scan({ mode: 'ble', filterNameless: true, minRssi: -85 })
setTimeout(() => stopDiscovery({ mode: 'ble' }), 12000)

// 连接
connect({
  mode: 'ble',
  deviceId: 'AA:BB:CC:DD:EE:FF',
  timeout: 15000
})

// 发送
send({ text: 'AT\r\n' })

// 断开
disconnect({ mode: 'ble' })

SPP 经典蓝牙

connect({
  mode: 'spp',
  deviceId: 'AA:BB:CC:DD:EE:FF',
  secure: false,
  timeout: 15000
})

send({ text: 'hello\r\n' })

硬件串口(收银秤)

listPorts({
  success: (res) => console.log(res.paths)
})

connect({
  mode: 'serial',
  path: '/dev/ttyS1',
  baudRate: 9600
})

onDataReceived((res) => {
  if (res.isSendEcho != true) {
    console.log('称重数据', res.text)
  }
})

send({ text: 'P\r\n' })   // 常见询盘指令,以设备协议为准

disconnect({ mode: 'serial' })

BLE 进阶

手动指定 UUID

// 连接时指定
connect({
  mode: 'ble',
  deviceId: 'AA:BB:CC:DD:EE:FF',
  serviceId: 'FFE0',
  writeCharacteristicId: 'FFE1',
  notifyCharacteristicId: 'FFE1',
  autoSelectCharacteristics: false
})

// 或连接后动态指定
getBLEDeviceServices({
  success: (res) => {
    setBLECharacteristics({
      serviceId: '0000ffe0-0000-1000-8000-00805f9b34fb',
      writeCharacteristicId: '0000ffe1-0000-1000-8000-00805f9b34fb',
      notifyCharacteristicId: '0000ffe1-0000-1000-8000-00805f9b34fb'
    })
  }
})

短 UUID(如 FFE0)会自动补全为 128 位标准 UUID。

自动特征值选择策略

autoSelectCharacteristics: true(默认)时:

  1. 跳过通用 GATT 服务(0x18000x1801
  2. 优先 Nordic UART(6E40FFE0/FFE1)等常见串口 UUID
  3. 优先同一特征同时具备写 + Notify
  4. 自动写入 CCCD 启用 Notify

兼容 API(旧版)

以下 API 仍可用,内部已转发到推荐 API:

旧 API 等价推荐 API
connectDevice connect
disconnectDevice disconnect
sendString / sendData send
openBluetoothAdapter + startDiscovery scan

适配器

API 说明
openBluetoothAdapter 初始化蓝牙适配器
closeBluetoothAdapter 关闭适配器
getBluetoothAdapterState 可用 / 开启 / 扫描中

扫描

API 说明
startDiscovery 开始扫描(参数同 scan
stopDiscovery 停止扫描

配对

API 说明
getBondedDevices 已配对设备列表(SPP)
createBond 发起配对(SPP)
removeBond 取消配对(SPP)

BLE 专用

API 说明
getBLEDeviceServices 已发现 GATT 服务与特征值
setBLECharacteristics 手动指定读写/通知特征
setBLEMTU 请求 MTU(内部默认 512)

错误码

说明
0 成功
10000 蓝牙适配器未初始化
10001 蓝牙不可用或未开启
10002 未找到设备
10003 连接失败
10006 未连接 / 数据通道未就绪
10008 系统错误
10012 连接超时
10013 无效参数
10014 正在连接中
10015 已连接
10016 配对失败
10017 发送失败
10018 BLE 不支持
10019 未找到 BLE 服务
10020 未找到 BLE 特征值
10021 Notify 启用失败
10022 缺少蓝牙/位置权限
10023 串口无读写权限

Android 权限

插件已在 AndroidManifest.xml 声明:

权限 用途
BLUETOOTH / BLUETOOTH_ADMIN Android 11 及以下
BLUETOOTH_SCAN / BLUETOOTH_CONNECT Android 12+
ACCESS_FINE_LOCATION Android 6–11 BLE 扫描

业务层必须申请运行时权限,否则扫描/连接返回 10022。参考 Demo 中 UTSAndroid.requestSystemPermission

串口访问 /dev/ttyS* 需设备节点有读写权限(工业板通常出厂已授权;普通手机不可用)。


常见问题

扫描无设备 / 报权限错误
确认已授予 BLUETOOTH_SCAN + BLUETOOTH_CONNECT(Android 12+)或定位权限(Android 6–11),且蓝牙已开启。

BLE 已连接但收发失败
检查 getConnectionState().ready;为 false 时用 getBLEDeviceServices + setBLECharacteristics 手动指定 UUID。

串口打开报 10023
设备节点无读写权限,确认路径正确(常见 /dev/ttyS0/dev/ttyS1),在工业安卓板真机测试。

用蓝牙耳机测试无法发 AT
耳机走 A2DP 音频协议,请使用 BLE/SPP 串口模块或硬件串口设备。

Windows 编译 EBUSY
关闭调试进程与 Java 进程,删除 unpackage/cache/uts_custom_android 后重编基座。

不支持 Windows exe 桌面
本插件仅 Android 原生实现,无法打包为 Windows 安装包使用。


目录结构

uni_modules/lq-bluetooth/
├── index.d.ts
├── readme.md
├── package.json
└── utssdk/
    ├── interface.uts           # 类型与错误码
    ├── unierror.uts
    ├── app-android/
    │   ├── index.uts           # 入口(mode 分发 + 简洁 API)
    │   ├── ble-manager.uts     # BLE
    │   ├── manager.uts         # SPP
    │   ├── serial-manager.uts  # 硬件串口
    │   ├── permission.uts
    │   ├── libs/               # Android-SerialPort AAR
    │   └── AndroidManifest.xml
    ├── app-ios/                # 占位
    ├── app-harmony/            # 占位
    └── web/                    # 占位(UI 预览)

参考

隐私、权限声明

1. 本插件需要申请的系统权限列表:

蓝牙相关权限,位置权限

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

插件不采集任何数据

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

暂无用户评论。