更新记录

1.2.0(2026-06-16)

当前已实现能力:

  • 扫描设备
  • 停止扫描
  • 连接设备
  • 断开设备
  • 写入字节数组
  • 写入字符串
  • 蓝牙状态监听
  • 扫描到设备监听
  • 蓝牙连接状态监听
  • 蓝牙数据回传监听
  • 数据写入完成监听

平台兼容性

uni-app(5.0)

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

uni-app x(5.0)

Chrome Safari Android iOS 鸿蒙 鸿蒙插件版本 微信小程序
× × × × 1.2.0 ×

gh-harmonybluetooth

鸿蒙蓝牙 BLE 中心端 UTS 插件。

当前已实现能力:

  • 扫描设备
  • 停止扫描
  • 连接设备
  • 断开设备
  • 写入字节数组
  • 写入字符串
  • 蓝牙状态监听
  • 扫描到设备监听
  • 蓝牙连接状态监听
  • 蓝牙数据回传监听
  • 数据写入完成监听

平台说明

  • 当前原生实现仅支持 HarmonyOS
  • Android / iOS 目录已保留同名导出,但会直接返回“不支持当前平台”错误

导出 API

import {
  startBluetoothDevicesDiscovery,
  stopBluetoothDevicesDiscovery,
  createBLEConnection,
  closeBLEConnection,
  writeBLECharacteristicValue,
  writeBLEStringValue,
  onBluetoothAdapterStateChange,
  offBluetoothAdapterStateChange,
  onBluetoothDeviceFound,
  offBluetoothDeviceFound,
  onBLEConnectionStateChange,
  offBLEConnectionStateChange,
  onBLECharacteristicValueChange,
  offBLECharacteristicValueChange,
  onBLEWriteComplete,
  offBLEWriteComplete
} from '@/uni_modules/gh-harmonybluetooth'

连接流程建议

  1. 先注册 onBluetoothAdapterStateChangeonBluetoothDeviceFound
  2. 调用 startBluetoothDevicesDiscovery
  3. 找到目标设备后调用 stopBluetoothDevicesDiscovery
  4. 调用 createBLEConnection
  5. createBLEConnection.success 返回的 services 中拿到可写服务和特征值
  6. 如果设备有通知特征值,可在 createBLEConnection 时传 notifyServiceIdnotifyCharacteristicId 自动订阅
  7. 调用 writeBLECharacteristicValuewriteBLEStringValue

使用示例

import {
  startBluetoothDevicesDiscovery,
  stopBluetoothDevicesDiscovery,
  createBLEConnection,
  closeBLEConnection,
  writeBLECharacteristicValue,
  writeBLEStringValue,
  onBluetoothAdapterStateChange,
  onBluetoothDeviceFound,
  onBLEConnectionStateChange,
  onBLECharacteristicValueChange,
  onBLEWriteComplete
} from '@/uni_modules/gh-harmonybluetooth'

let currentDeviceId = ''
let writeServiceId = ''
let writeCharacteristicId = ''

onBluetoothAdapterStateChange((res) => {
  console.log('蓝牙状态变化', res)
})

onBluetoothDeviceFound((res) => {
  console.log('扫描结果', res.devices)
  if (res.devices.length > 0 && currentDeviceId.length == 0) {
    currentDeviceId = res.devices[0].deviceId
    stopBluetoothDevicesDiscovery()
  }
})

onBLEConnectionStateChange((res) => {
  console.log('连接状态变化', res)
})

onBLECharacteristicValueChange((res) => {
  console.log('收到蓝牙数据', res)
})

onBLEWriteComplete((res) => {
  console.log('写入完成', res)
})

startBluetoothDevicesDiscovery({
  allowDuplicatesKey: false,
  success(res) {
    console.log('开始扫描成功', res)
  },
  fail(err) {
    console.error('开始扫描失败', err)
  }
})

createBLEConnection({
  deviceId: currentDeviceId,
  notifyServiceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
  notifyCharacteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
  success(res) {
    console.log('连接成功', res)
    if (res.services.length > 0 && res.services[0].characteristics.length > 0) {
      writeServiceId = res.services[0].characteristics[0].serviceId
      writeCharacteristicId = res.services[0].characteristics[0].characteristicId
    }
  }
})

writeBLECharacteristicValue({
  deviceId: currentDeviceId,
  serviceId: writeServiceId,
  characteristicId: writeCharacteristicId,
  value: [0x01, 0x02, 0x03, 0x04]
})

writeBLEStringValue({
  deviceId: currentDeviceId,
  serviceId: writeServiceId,
  characteristicId: writeCharacteristicId,
  value: 'hello bluetooth'
})

closeBLEConnection({
  deviceId: currentDeviceId
})

API 详细说明

1. startBluetoothDevicesDiscovery(options)

用途:开始扫描附近 BLE 设备。

常用场景:

  • 搜索附近蓝牙打印机
  • 按服务 UUID 筛选特定设备
  • 开始连接流程前做设备发现

参数说明:

  • serviceUuids?: string[]
    • 按服务 UUID 过滤扫描结果
    • 适合只想扫描某一类 BLE 设备的场景
  • deviceId?: string
    • 按设备地址过滤
    • 已知目标地址时可减少无关结果
  • name?: string
    • 按设备名称过滤
  • allowDuplicatesKey?: boolean
    • 是否允许重复上报同一设备
    • false:默认更适合“设备列表展示”
    • true:适合需要持续观察 RSSI 或广播变化的场景
  • interval?: number
    • 扫描间隔,直接透传给 Harmony BLE 扫描参数
  • success?: (res) => void
    • 成功回调,返回 { errMsg: 'startBluetoothDevicesDiscovery:ok' }
  • fail?: (err) => void
    • 失败回调,常见原因是蓝牙未开启、权限未授予
  • complete?: (res) => void
    • 无论成功失败都会回调

示例:

startBluetoothDevicesDiscovery({
  allowDuplicatesKey: false,
  success(res) {
    console.log('开始扫描成功', res.errMsg)
  },
  fail(err) {
    console.error('开始扫描失败', err.errCode, err.errMsg)
  }
})

按服务 UUID 过滤:

startBluetoothDevicesDiscovery({
  serviceUuids: ['0000FFF0-0000-1000-8000-00805F9B34FB'],
  allowDuplicatesKey: true
})

注意事项:

  • 调用前插件会自动申请 ohos.permission.ACCESS_BLUETOOTH
  • 重复调用时,插件内部会先尝试停止上一次扫描,再启动新扫描
  • 真正的设备数据通过 onBluetoothDeviceFound 回调获取

2. stopBluetoothDevicesDiscovery(options?)

用途:停止 BLE 扫描。

参数说明:

  • options 可省略
  • success?: (res) => void
    • 成功回调,返回 { errMsg: 'stopBluetoothDevicesDiscovery:ok' }
  • fail?: (err) => void
  • complete?: (res) => void

示例:

stopBluetoothDevicesDiscovery({
  success(res) {
    console.log('停止扫描成功', res.errMsg)
  }
})

3. createBLEConnection(options)

用途:连接目标 BLE 设备,并返回该设备的服务与特征值列表。

参数说明:

  • deviceId: string
    • 必填,目标设备地址
  • timeout?: number
    • 连接超时,默认 10000ms
  • mtu?: number
    • 连接成功后尝试设置 MTU
  • notifyServiceId?: string
    • 可选,自动订阅通知时使用的服务 UUID
  • notifyCharacteristicId?: string
    • 可选,自动订阅通知时使用的特征 UUID
  • success?: (res) => void
    • 成功后会返回:
    • deviceId
    • connected
    • services
  • fail?: (err) => void
  • complete?: (res) => void

成功回调返回结构示例:

{
  errMsg: 'createBLEConnection:ok',
  deviceId: 'AA:BB:CC:DD:EE:FF',
  connected: true,
  services: [
    {
      serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
      isPrimary: true,
      characteristics: [
        {
          serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
          characteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
          properties: {
            write: true,
            writeNoResponse: false,
            read: false,
            notify: true,
            indicate: false
          }
        }
      ]
    }
  ]
}

示例:

createBLEConnection({
  deviceId: currentDeviceId,
  timeout: 12000,
  notifyServiceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
  notifyCharacteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
  success(res) {
    console.log('连接成功', res)
    const writeService = res.services.find(item => item.characteristics.some(c => c.properties.write || c.properties.writeNoResponse))
    const writeCharacteristic = writeService?.characteristics.find(c => c.properties.write || c.properties.writeNoResponse)
    if (writeService && writeCharacteristic) {
      writeServiceId = writeService.serviceId
      writeCharacteristicId = writeCharacteristic.characteristicId
    }
  },
  fail(err) {
    console.error('连接失败', err)
  }
})

注意事项:

  • 如果设备未连接成功,会进入 fail
  • 如果传了 notifyServiceIdnotifyCharacteristicId,插件会尝试自动订阅通知或指示
  • 建议优先从 services 中动态挑选可写特征值,而不是写死 UUID

4. closeBLEConnection(options)

用途:断开 BLE 连接并释放当前设备上下文。

参数说明:

  • deviceId: string
  • success?: (res) => void
    • 返回 { errMsg: 'closeBLEConnection:ok', deviceId, disconnected: true }
  • fail?: (err) => void
  • complete?: (res) => void

示例:

closeBLEConnection({
  deviceId: currentDeviceId,
  success(res) {
    console.log('断开成功', res)
  }
})

5. writeBLECharacteristicValue(options)

用途:向指定特征值写入字节数组。

适合场景:

  • 已经有完整 ESC/POS 字节数据
  • 需要自己精确控制二进制命令
  • 图片、条码、原始指令下发

参数说明:

  • deviceId: string
  • serviceId: string
  • characteristicId: string
  • value: number[]
    • 必填,字节数组
    • 每一项范围必须在 0-255
  • withResponse?: boolean
    • false 时写入模式为 WRITE_NO_RESPONSE
    • 不传或 true 时使用 WRITE
  • success?: (res) => void
  • fail?: (err) => void
  • complete?: (res) => void

示例:

writeBLECharacteristicValue({
  deviceId: currentDeviceId,
  serviceId: writeServiceId,
  characteristicId: writeCharacteristicId,
  value: [0x1B, 0x40, 0x0D, 0x0A],
  withResponse: true,
  success(res) {
    console.log('字节写入成功', res)
  }
})

注意事项:

  • 该接口不会自动分包
  • 如果设备一次只能接收 20 字节左右,需业务侧自行拆包后多次调用
  • 写入结果也会通过 onBLEWriteComplete 回调通知

6. writeBLEStringValue(options)

用途:向指定特征值写入字符串,并由插件内部完成编码和分包。

适合场景:

  • 打印文本内容
  • 发送由字符串拼成的 ESC/POS 指令流
  • 需要按指定编码发送中文内容

参数说明:

  • deviceId: string
  • serviceId: string
  • characteristicId: string
  • value: string
    • 必填,待写入的字符串
  • encoding?: string
    • 字符串编码,默认 utf-8
    • 打印中文常见可传 gb18030
  • withResponse?: boolean
    • 是否使用有响应写入
  • packetSize?: number
    • 插件内部自动分包大小
    • 默认 20
  • packetInterval?: number
    • 每包之间的发送间隔,单位毫秒
    • 默认 0
  • success?: (res) => void
  • fail?: (err) => void
  • complete?: (res) => void

示例 1:发送普通文本

writeBLEStringValue({
  deviceId: currentDeviceId,
  serviceId: writeServiceId,
  characteristicId: writeCharacteristicId,
  value: 'hello bluetooth',
  success(res) {
    console.log('字符串写入成功', res)
  }
})

示例 2:发送中文打印内容

writeBLEStringValue({
  deviceId: currentDeviceId,
  serviceId: writeServiceId,
  characteristicId: writeCharacteristicId,
  value: '测试中文打印\r\n',
  encoding: 'gb18030',
  packetSize: 20,
  packetInterval: 40,
  withResponse: false
})

示例 3:发送字符串拼接的 ESC 指令

const ESC = String.fromCharCode(0x1B)
const LF = String.fromCharCode(0x0D, 0x0A)

writeBLEStringValue({
  deviceId: currentDeviceId,
  serviceId: writeServiceId,
  characteristicId: writeCharacteristicId,
  value: `${ESC}@打印标题${LF}`,
  encoding: 'gb18030',
  packetSize: 20,
  packetInterval: 30
})

注意事项:

  • 该接口会先编码,再按 packetSize 自动拆包
  • 如果你发送的是打印机字符串命令,建议中文内容使用 gb18030
  • 如果你已经有精确字节数据,请优先使用 writeBLECharacteristicValue

7. onBluetoothAdapterStateChange(callback) / offBluetoothAdapterStateChange(callback)

用途:监听蓝牙适配器状态变化。

回调结果:

{
  available: true,
  discovering: false,
  state: 5
}

示例:

const adapterStateHandler = (res) => {
  console.log('蓝牙状态变化', res.available, res.discovering, res.state)
}

onBluetoothAdapterStateChange(adapterStateHandler)

// 结束监听
offBluetoothAdapterStateChange(adapterStateHandler)

8. onBluetoothDeviceFound(callback) / offBluetoothDeviceFound(callback)

用途:监听扫描到的 BLE 设备。

回调结果:

{
  devices: [
    {
      deviceId: 'AA:BB:CC:DD:EE:FF',
      name: 'Printer',
      RSSI: -56,
      advertisData: ArrayBuffer,
      connectable: true
    }
  ]
}

示例:

const deviceFoundHandler = (res) => {
  console.log('扫描到设备', res.devices)
}

onBluetoothDeviceFound(deviceFoundHandler)

// 结束监听
offBluetoothDeviceFound(deviceFoundHandler)

9. onBLEConnectionStateChange(callback) / offBLEConnectionStateChange(callback)

用途:监听指定设备的连接状态变化。

回调结果:

{
  deviceId: 'AA:BB:CC:DD:EE:FF',
  connected: true,
  state: 2
}

示例:

const connectionHandler = (res) => {
  console.log('连接状态变化', res.deviceId, res.connected, res.state)
}

onBLEConnectionStateChange(connectionHandler)
offBLEConnectionStateChange(connectionHandler)

10. onBLECharacteristicValueChange(callback) / offBLECharacteristicValueChange(callback)

用途:监听设备通知、指示或回传的数据。

回调结果:

{
  deviceId: 'AA:BB:CC:DD:EE:FF',
  serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
  characteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
  value: ArrayBuffer
}

示例:

const valueChangeHandler = (res) => {
  console.log('收到设备数据', res)
}

onBLECharacteristicValueChange(valueChangeHandler)
offBLECharacteristicValueChange(valueChangeHandler)

11. onBLEWriteComplete(callback) / offBLEWriteComplete(callback)

用途:监听每次写入完成结果。

回调结果:

{
  deviceId: 'AA:BB:CC:DD:EE:FF',
  serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
  characteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
  success: true,
  writeType: 2,
  errMsg: 'writeBLECharacteristicValue:ok'
}

示例:

const writeCompleteHandler = (res) => {
  console.log('写入完成', res)
}

onBLEWriteComplete(writeCompleteHandler)
offBLEWriteComplete(writeCompleteHandler)

12. 监听注销补充说明

  • off* 传入同一个 callback,可移除对应监听
  • 插件底层也支持传 null 清空该类型的全部监听

示例:

offBluetoothDeviceFound(null)
offBLEConnectionStateChange(null)
offBLECharacteristicValueChange(null)
offBLEWriteComplete(null)

常见接入模板

import {
  startBluetoothDevicesDiscovery,
  stopBluetoothDevicesDiscovery,
  createBLEConnection,
  writeBLEStringValue,
  onBluetoothDeviceFound
} from '@/uni_modules/gh-harmonybluetooth'

let deviceId = ''
let serviceId = ''
let characteristicId = ''

onBluetoothDeviceFound((res) => {
  const target = res.devices.find(item => item.name?.includes('Printer'))
  if (!target) {
    return
  }
  deviceId = target.deviceId
  stopBluetoothDevicesDiscovery()

  createBLEConnection({
    deviceId,
    success(connectionRes) {
      const writeService = connectionRes.services.find(item => item.characteristics.some(c => c.properties.write || c.properties.writeNoResponse))
      const writeChar = writeService?.characteristics.find(c => c.properties.write || c.properties.writeNoResponse)
      if (!writeService || !writeChar) {
        return
      }

      serviceId = writeService.serviceId
      characteristicId = writeChar.characteristicId

      writeBLEStringValue({
        deviceId,
        serviceId,
        characteristicId,
        value: '测试中文打印\r\n',
        encoding: 'gb18030',
        packetSize: 20,
        packetInterval: 40,
        withResponse: false
      })
    }
  })
})

startBluetoothDevicesDiscovery({
  allowDuplicatesKey: false
})

权限说明

插件已在 utssdk/app-harmony/module.json5 中声明:

  • ohos.permission.ACCESS_BLUETOOTH

首次调用蓝牙能力时,插件会自动请求系统权限。

隐私、权限声明

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

BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_FINE_LOCATION

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

插件不采集任何数据

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

暂无用户评论。