目录
Controller与Controlee(控制器与受控设备)
UWB通信示例代码
参考链接: 示例代码:developer.android.com/guide/topic…
*注意:UWB当前仅支持Jetpack。
Controller与Controlee(控制器与受控设备)
UWB通信在两个设备间发生,一个为控制器(Controller),其他为受控端(Controlee)。(此为FiRa标准中的定义,控制器负责测距流程的执行)
从测距流程来又区分为Initiator与Responder,所以在FiRa设备的类型来说可以构成四种类型:
- Controller + Initiator (默认)
- Controlee + Responder(默认)
- Controller + Responder
- Controlee + Initiator
控制器决定complex channel(UwbComplexChannel),在两个设备之间共享。一个控制器可以与多个受控端工作,但受控端仅能与一个控制器通信。
通道选择(Channel selection)
对于测距中的受控端(Controlee),必须识别控制器的local address和complex channel。
local address提供控制器设备的上下文,而complex channel提供测距会话的上下文(为UWB通信中的实际物理信道,默认为9信道;另外一个参数为UWB前导码的编码,可以理解为虚拟信道,所以在Android的实现中,统一放到了一个类中进行实现)。
/** Complex channel used by UWB ranging. */
public class UwbComplexChannel {
@FiraParams.UwbChannel private final int mChannel;
@FiraParams.UwbPreambleCodeIndex private final int mPreambleIndex;
}
测距会话结束后,本地地址和复合信道都会轮换。
关于测距两端设备信息交互,在FiRa的标准中建议使用带外信道进行通信,通常建议使用BLE,以允许受控端了解控制器的本地地址和复合信道。
代码示例
此示例为受控端启动和终止UWB测距。
// The coroutineScope responsible for handling uwb ranging.
// This will be initialized when startRanging is called.
var job: Job?
// A code snippet that initiates uwb ranging for a controlee.
suspend fun startRanging() {
// Get the ranging parameter of a partnering controller using an OOB
// mechanism of choice.
val partnerAddress : Pair<UwbAddress, UwbComplexChannel> = listenForPartnersAddress()
// Create the ranging parameters.
val partnerParameters = RangingParameters(
uwbConfigType = UwbRangingParamters.UWB_CONFIG_ID_1,
// SessionKeyInfo is used to encrypt the ranging session.
sessionKeyInfo = null,
complexChannel = partnerAddress.second,
peerDevices = listOf(UwbDevice.createForAddress(partnerAddress.first)),
//自动更新率,屏幕常亮时为240ms周期,灭默认为4s
updateRateType = UwbRangingParamters.RANGING_UPDATE_RATE_AUTOMATIC
)
// Initiate a session that will be valid for a single ranging session.
val clientSession = uwbManager.clientSessionScope()
// Share the localAddress of the current session to the partner device.
broadcastMyParameters(clientSession.localAddress)
val sessionFlow = clientSession.prepareSession(partnerParameters)
// Start a coroutine(协程) scope that initiates ranging.
CoroutineScope(Dispatchers.Main.immediate).launch {
sessionFlow.collect {
when(it) {
is RangingResultPosition -> doSomethingWithPosition(it.position)
is RangingResultPeerDisconnected -> peerDisconnected(it)
}
}
}
}
// A code snippet that cancels uwb ranging.
fun cancelRanging() {
// Canceling the CoroutineScope will stop the ranging.
job?.let {
it.cancel()
}
}
UWB API
要使用UWB API,需要执行以下步骤:
确保设备在Android 12或更高版本上运行(当前为Android 13)。
确保设备支持使用
PackageManager#hasSystemFeature("android.hardware.uwb")
推荐:使用带外(OOB)机制发现支持UWB的对等设备,例如
BluetoothScanner
用于BLE扫描。推荐:使用OOB机制(如
`BluetoothGatt`
BLE GATT连接)交换本地设备的地址和对等设备的地址和复杂通道以用于会话。如果用户想停止会话,取消会话的范围即可(cancel the scope of the session)。
相关OOB信息可以参考之前的文章:FiRa标准——蓝牙OOB规范