仓颉 OpenHarmony 蓝牙连接状态枚举详解:ohos.bluetooth.constant 模块实战指南
仓颉 OpenHarmony 蓝牙连接状态枚举详解:ohos.bluetooth.constant 模块实战指南
本指南聚焦 OpenHarmony 蓝牙开发中 ohos.bluetooth.constant(蓝牙 constant 模块)的核心内容,系统讲解 ProfileConnectionState 连接状态枚举的四个取值、判等与字符串化运算符,并结合本仓库中 cj-apis-bluetooth-base_profile.md、cj-apis-bluetooth-a2dp.md、cj-apis-bluetooth-ble.md 与 GATT 开发指南中的实际用法,说明如何在仓颉工程中订阅连接状态变化事件、用状态枚举做连接判断,以及处理蓝牙服务子系统错误码。读完本文,你将能够在仓颉应用中准确识别蓝牙 profile 的连接生命周期,并写出状态机正确的蓝牙连接逻辑。
模块定位与导入方式
constant 模块是蓝牙能力中专门承载"常量定义"的模块,ProfileConnectionState 即用于描述蓝牙设备 profile(如 A2DP 音频、HFP 通话等)的连接状态。在仓颉工程中,通过以下方式导入:
import kit.ConnectivityKit.*
该模块下所有接口均要求系统能力 SystemCapability.Communication.Bluetooth.Core,起始版本为 22,即仅在支持该系统能力的 OpenHarmony 设备上可用。导入后,即可直接使用 ProfileConnectionState 类型及其成员。
ProfileConnectionState 枚举:四个状态成员
枚举完整声明如下(... 表示当前文档版本中未展开的预留成员):
public enum ProfileConnectionState <: Equatable<ProfileConnectionState> & ToString {
| StateDisconnected
| StateConnecting
| StateConnected
| StateDisconnecting
| ...
}
该枚举同时实现 Equatable<ProfileConnectionState>(可判等)与 ToString(可转字符串)两个父类型,因此可直接参与 ==、!= 比较,也可调用 toString() 输出可读文本。四个成员语义如下:
| 枚举成员 | 含义 | 典型场景 |
|---|---|---|
StateDisconnected |
profile 已断连 | 初始状态、断开完成后的稳定状态 |
StateConnecting |
profile 正在连接 | 已发起连接请求、等待握手完成 |
StateConnected |
profile 已连接 | 连接建立成功,可进行数据传输 |
StateDisconnecting |
profile 正在断开连接 | 已发起断开请求、等待连接释放 |
从连接生命周期看,状态一般按 StateDisconnected → StateConnecting → StateConnected → StateDisconnecting → StateDisconnected 循环跃迁。在 cj-gatt-development-guide.md 中,官方明确指出整个连接过程会涉及多种状态的跃迁,其中 StateConnected 表示已连接、StateDisconnected 表示已断连,这为状态判断提供了直接依据。
运算符与字符串化方法
ProfileConnectionState 除枚举成员外还提供三个实例方法,用于状态比较与日志输出。
判等运算符 ==
public operator func ==(other: ProfileConnectionState): Bool
对两个 profile 连接状态判等,状态相同返回 true,否则返回 false。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| other | ProfileConnectionState | 是 | - | 蓝牙设备的 profile 连接状态 |
返回值: Bool,状态相同返回 true,否则返回 false。
判不等运算符 !=
public operator func !=(other: ProfileConnectionState): Bool
对两个 profile 连接状态判不等,状态不同返回 true,否则返回 false。
参数:
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| other | ProfileConnectionState | 是 | - | 蓝牙设备的 profile 连接状态 |
返回值: Bool,状态不同返回 true,否则返回 false。
字符串化方法 toString()
public func toString(): String
返回 profile 连接状态的字符串表示,常用于日志输出,例如回调中打印 "profile connection state has change to ${connectionState}"。
返回值: String,profile 连接状态的字符串表示。
在 BaseProfile 中的实际应用
ProfileConnectionState 是 BaseProfile 接口体系中的核心返回类型:
public interface BaseProfile {
func getConnectedDevices(): Array<String>
func getConnectionState(deviceId: String): ProfileConnectionState
func on(eventType: ProfileCallbackType, callback: Callback1Argument<StateChangeParam>): Unit
func off(eventType: ProfileCallbackType, callback: CallbackObject): Unit
func off(eventType: ProfileCallbackType): Unit
}
其中 getConnectionState(deviceId) 返回指定设备的 ProfileConnectionState,调用方据此判断设备当前所处的连接阶段:
// index.cj
import ohos.business_exception.*
import kit.ConnectivityKit.*
import kit.PerformanceAnalysisKit.Hilog
try {
let a2dpSrc = createA2dpSrcProfile()
let retArray = a2dpSrc.getConnectionState("XX:XX:XX:XX:XX:XX")
} catch (e: BusinessException) {
Hilog.info(0, "Bluetooth", "errCode: ${e.code}, errMessage: ${e.message}")
}
同时,连接状态变化通过 on(ProfileCallbackType.ConnectionStateChange, callback) 以异步回调方式通知,回调入参 StateChangeParam 中即包含 state: ProfileConnectionState 字段(该类的完整定义见 cj-apis-bluetooth-base_profile.md)。完整订阅与取消订阅示例:
// index.cj
import ohos.callback_invoke.*
import ohos.business_exception.*
import kit.ConnectivityKit.*
import kit.PerformanceAnalysisKit.Hilog
class StateChangeCallback <: Callback1Argument<StateChangeParam> {
public func invoke(err: ?BusinessException, arg: StateChangeParam): Unit {
let connectionState = arg.state.toString()
Hilog.info(0, "Bluetooth", "profile connection state has change to ${connectionState}")
}
}
let changeCallBack = StateChangeCallback()
let a2dp = createA2dpSrcProfile()
try {
a2dp.on(ProfileCallbackType.ConnectionStateChange, changeCallBack)
a2dp.off(ProfileCallbackType.ConnectionStateChange)
} catch (e: BusinessException) {
Hilog.info(0, "Bluetooth", "errCode: ${e.code}, errMessage: ${e.message}")
}
A2DP、HFP 等具体 profile 类均继承自 BaseProfile,因此这些订阅、查询连接状态的模式在 cj-apis-bluetooth-a2dp.md 与 cj-apis-bluetooth-hfp.md 中保持一致。
用状态枚举构建 GATT 连接状态机
在 cj-gatt-development-guide.md 的完整示例中,客户端管理器用 ProfileConnectionState 作为内部状态字段,初始化为 StateDisconnected:
class GattClientManager {
var device: ?String = None<String>
var gattClient: ?GattClientDevice = None<GattClientDevice>
var connectState: ProfileConnectionState = ProfileConnectionState.StateDisconnected
...
}
其核心逻辑体现了状态枚举的两大典型用法:
1. 订阅回调中更新状态:连接状态变化回调将 stateInfo.state 写入 connectState 字段,保持本地状态与真实连接一致:
let onGattClientStateChange = BLEConnectionStateChangeCallback(){
err, stateInfo =>
Hilog.info(0, TAG, "onGattServerStateChange: device=" + stateInfo.deviceId + ", state=" + stateInfo.state.toString())
if (stateInfo.deviceId == this.device.getOrThrow()) {
this.connectState = stateInfo.state
}
}
2. 通过 !=/== 校验前置条件:发起连接前,仅当当前状态为 StateDisconnected 才允许执行,避免重复发起连接:
if (this.connectState != ProfileConnectionState.StateDisconnected) {
Hilog.error(1, TAG, 'startConnect failed')
return
}
而所有需要已连接前提的操作(如读写特征值、收发数据)均以 StateConnected 为门槛进行守卫,例如:
if (this.gattClient.isNone() || this.connectState != ProfileConnectionState.StateConnected) {
Hilog.error(1, TAG, 'gattClient does not exist or state not connected')
}
类似的初始化与守卫写法也出现在 cj-apis-bluetooth-ble.md 的客户端示例中(var connectState = ProfileConnectionState.StateDisconnected)。可见,将 ProfileConnectionState 与回调事件结合,是构建可靠蓝牙连接状态机、避免在未连接状态下误操作的标准做法。
异常处理与错误码对照
涉及连接状态查询与订阅的 API 均可能抛出 BusinessException,需结合通用错误码与蓝牙服务子系统错误码定位问题:
| 错误码 ID | 错误信息 | 说明与处理 |
|---|---|---|
| 201 | Permission denied. | 权限校验失败,需在工程中声明 ohos.permission.ACCESS_BLUETOOTH |
| 801 | Capability not supported. | 设备不支持此 API,需确认系统能力 |
| 2900001 | Service stopped. | 蓝牙服务已停止,重新执行打开或关闭蓝牙 |
| 2900003 | Bluetooth disabled. | 蓝牙开关已关闭,重新打开蓝牙开关 |
| 2900004 | Profile not supported. | 当前设备环境不支持该配置文件,检查设备能力后停止调用 |
| 2900099 | Operation failed. | 操作失败,请重试该操作 |
标准捕获写法:
try {
// 查询或订阅连接状态
} catch (e: BusinessException) {
Hilog.info(0, "Bluetooth", "errCode: ${e.code}, errMessage: ${e.message}")
}
权限与系统能力约束
- 权限:
ohos.permission.ACCESS_BLUETOOTH。凡涉及查询已连接设备、读取连接状态、订阅/取消订阅状态变化事件的 API 均要求此权限,未授权时抛出 201 错误。 - 系统能力:
SystemCapability.Communication.Bluetooth.Core,缺失时抛出 801 错误。 - 版本:
ProfileConnectionState及其全部成员、运算符方法起始版本均为 22,开发前需确认目标设备系统版本与系统能力声明。
小结
ohos.bluetooth.constant 模块的 ProfileConnectionState 通过 StateDisconnected、StateConnecting、StateConnected、StateDisconnecting 四个成员完整刻画了蓝牙 profile 的连接生命周期,并依托 Equatable 与 ToString 父类型提供 ==、!=、toString() 三个实用方法。在实战中,它与 BaseProfile.getConnectionState() 配合可主动查询连接状态,与 on/off 订阅机制结合可被动感知状态跃迁,配合 GATT 客户端/服务端的连接状态机模式,是仓颉蓝牙应用中不可绕过的核心类型。相关 API 详情可继续查阅 cj-apis-bluetooth-base_profile.md、cj-apis-bluetooth-a2dp.md、cj-apis-bluetooth-hfp.md 与 cj-gatt-development-guide.md。