检查 trait 是否支持某个命令
您还可以查看 trait 命令是否受支持。此外,您还可以使用 trait 级 supports
函数检查特定设备是否支持某个命令。
例如,如需检查设备是否支持开/关 trait 的 toggle
命令,请执行以下操作:
// Check if the OnOff trait supports the toggle command. if (onOffTrait.supports(OnOff.Command.Toggle)) { println("onOffTrait supports toggle command") } else { println("onOffTrait does not support stateful toggle command") }
向设备发送命令
发送命令与从 trait 读取状态属性类似。如需开启或关闭设备,请使用 OnOff
trait 的“切换”命令,该命令在 Google Home 生态系统数据模型中定义为 toggle()
。如果 onOff
为 true
,则此方法会将其更改为 false
;如果 onOff
为 false
,则会将其更改为 true
:
// Calling a command on a trait. try { onOffTrait.toggle() } catch (e: HomeException) { // Code for handling the exception }
所有 trait 命令都是 suspend
函数,只有在 API 返回响应(例如确认设备状态已更改)时才会完成。如果命令检测到执行流程存在问题,则可能会返回异常。作为开发者,您应使用 try-catch
块来妥善处理这些异常,并在错误可供用户采取行动时向用户显示详细信息。未处理的异常会停止应用运行时,并可能导致应用崩溃。
或者,使用 off()
或 on()
命令明确设置状态:
onOffTrait.off() onOffTrait.on()
发送用于更改状态的命令后,当命令完成时,您可以按照读取设备状态中所述的方式读取状态,以便在应用中进行处理。或者,您也可以使用观察状态中所述的流程,这是首选方法。
发送带参数的命令
某些命令可能会使用参数,例如 OnOff
或 LevelControl
trait 中的参数:
// Turn off the light using the DyingLight effect. onOffTrait.offWithEffect( effectIdentifier = OnOffTrait.EffectIdentifierEnum.DyingLight, effectVariant = 0u, )
// Change the brightness of the light to 50% levelControlTrait.moveToLevel( level = 127u.toUByte(), transitionTime = null, optionsMask = LevelControlTrait.OptionsBitmap(), optionsOverride = LevelControlTrait.OptionsBitmap(), )
某些命令具有可选实参,这些实参位于必需实参之后。
例如,FanControl
trait 的 step
命令有两个可选参数:
val fanControlTraitFlow: Flow<FanControl?> = device.type(FanDevice).map { it.standardTraits.fanControl }.distinctUntilChanged() val fanControl = fanControlTraitFlow.firstOrNull() // Calling a command with optional parameters not set. fanControl?.step(direction = FanControlTrait.StepDirectionEnum.Increase) // Calling a command with optional parameters. fanControl?.step(direction = FanControlTrait.StepDirectionEnum.Increase) { wrap = true }
检查 trait 是否支持属性
某些设备可能支持 Matter trait,但不支持特定属性。例如,映射到 Matter 的 Cloud-to-cloud 设备可能不支持所有 Matter 属性。如需处理此类情况,请使用 trait 级 supports
函数和 trait 的 Attribute
枚举来检查特定设备是否支持该属性。
例如,如需检查设备是否支持开/关 trait 的 onOff
属性,请执行以下操作:
// Check if the OnOff trait supports the onOff attribute. if (onOffTrait.supports(OnOff.Attribute.onOff)) { println("onOffTrait supports onOff state") } else { println("onOffTrait is for a command only device!") }
Matter 规范或 Cloud-to-cloud smart home 架构中的某些属性是可为 null 的。对于这些属性,您可以通过使用 isNullable
和 supports
,确定属性返回 null 是由于设备未报告该值,还是属性的值实际上为 null
:
// Check if a nullable attribute is set or is not supported. if (onOffTrait.supports(OnOff.Attribute.startUpOnOff)) { // The device supports startupOnOff, it is safe to expect this value in the trait. if (OnOff.Attribute.startUpOnOff.isNullable && onOffTrait.startUpOnOff == null) { // This value is nullable and set to null. Check the specification as to // what null in this case means println("onOffTrait supports startUpOnOff and it is null") } else { // This value is nullable and set to a value. println("onOffTrait supports startUpOnOff and it is set to ${onOffTrait.startUpOnOff}") } } else { println("onOffTrait does not support startUpOnOff!") }
更新 trait 属性
如果您想更改给定属性的值,但 trait 的任何命令都无法执行此操作,则该属性可能支持显式设置其值。
属性的值能否更改取决于以下两个因素:
- 该属性是否可写入?
- 发送 trait 命令会导致属性值发生变化吗?
有关 trait 及其属性的参考文档提供了此类信息。
因此,决定属性值可能如何更改的属性组合如下:
只读,不受其他命令的影响。这意味着该属性的值不会发生变化。例如,
Switch
trait 的currentPosition
属性。只读,且会受其他命令影响。这意味着,属性值的唯一更改方式是发送命令。例如,
LevelControl
Matter trait 的currentLevel
属性是只读的,但其值可以通过moveToLevel
等命令进行更改。可写入,且不受其他命令的影响。这意味着,您可以使用 trait 的
update
函数直接更改属性的值,但没有任何命令会影响属性的值。例如,DoorLock
trait 的WrongCodeEntryLimit
属性。可写入,并受其他命令影响。这意味着,您可以使用 trait 的
update
函数直接更改属性的值,并且属性的值可能会因发送命令而发生变化。例如,可以写入Thermostat
trait 的occupiedCoolingSetpoint
属性,也可以使用setpointRaiseLower
命令更新该属性。
使用 update 函数更改属性值的示例
以下示例展示了如何显式设置 DoorLockTrait.WrongCodeEntryLimit
属性的值。
如需设置属性值,请调用 trait 的 update
函数,并向其传递用于设置新值的修饰符函数。
最好先验证 trait 是否支持属性。
例如:
var doorLockDevice = home.devices().list().first { device -> device.has(DoorLock) } val traitFlow: Flow<DoorLock?> = doorLockDevice.type(DoorLockDevice).map { it.standardTraits.doorLock }.distinctUntilChanged() val doorLockTrait: DoorLock = traitFlow.first()!! if (doorLockTrait.supports(DoorLock.Attribute.wrongCodeEntryLimit)) { val unused = doorLockTrait.update { setWrongCodeEntryLimit(3u) } }
一次发送多个命令
借助批处理 API,客户端可以在单个载荷中发送多个 Home API 设备命令。这些命令会批量打包到单个载荷中并并行执行,类似于使用并行节点构建 Home API 自动化操作的方式,例如在日出前打开百叶窗示例。不过,与 Automation API 相比,Batching API 支持更复杂、更精细的行为,例如能够根据任何条件在运行时动态选择设备。
一批命令可定位多个设备、多个房间和多个结构中的多个 trait。
批量发送命令可让设备同时执行操作,而如果命令以单独的请求顺序发送,则无法实现这一点。使用批量命令实现的行为可让开发者将一组设备的状态设置为与预定的汇总状态匹配。
使用批处理 API
通过批处理 API 调用命令涉及以下三个基本步骤:
- 调用
Home.sendBatchedCommands()
方法。 - 在
sendBatchedCommands()
代码块的正文中,指定要包含在批处理中的命令。 - 检查发送的命令的结果,了解它们是成功还是失败。
调用 sendBatchedCommands() 方法
调用 Home.sendBatchedCommands()
方法。在后台,此方法会在特殊批处理上下文中设置 lambda 表达式。
home.sendBatchedCommands() {
指定批处理命令
在 sendBatchedCommands()
代码块的正文中,填充可批处理的命令。可批处理的命令是现有 Device API 命令的“影子”版本,可在批处理上下文中使用,并且名称中添加了后缀 Batchable
。例如,LevelControl
trait 的 moveToLevel()
命令有一个名为 moveToLevelBatchable()
的对应命令。
示例:
val response1 = add(command1)
val response2 = add(command2)
将所有命令添加到批处理上下文并执行离开上下文后,系统会自动发送批处理。
响应会捕获在 DeferredResponse<T>
对象中。
DeferredResponse<T>
实例可以收集到任何类型的对象中,例如 Collection
或您定义的数据类。无论您选择使用哪种类型的对象来组装响应,sendBatchedCommands()
都会返回该类型的对象。例如,批量上下文可以在 Pair
中返回两个 DeferredResponse
实例:
val (response1, response2) = homeClient.sendBatchedComamnds {
val response1 = add(someCommandBatched(...))
val response2 = add(someOtherCommandBatched(...))
Pair(response1, response2)
}
或者,批处理上下文也可以返回自定义数据类中的 DeferredResponse
实例:
// Custom data class
data class SpecialResponseHolder(
val response1: DeferredResponse<String>,
val response2: DeferredResponse<Int>,
val other: OtherResponses
)
data class OtherResponses(...)
检查每条回答
在 sendBatchedCommands()
代码块之外,检查响应以确定相应命令是成功还是失败。为此,您可以调用 DeferredResponse.getOrThrow()
,该函数会执行以下操作之一:
- 返回已执行命令的结果,
- 如果批处理范围尚未完成或命令未成功执行,则抛出错误。
您应仅在 sendBatchedCommands()
lambda 作用域之外检查结果。
示例
假设您要构建一个应用,该应用使用批处理 API 设置“晚安”场景,以便在所有人都入睡时,配置住宅中的所有设备。此应用应关闭灯光并锁上前门和后门。
下面介绍了一种完成此任务的方法:
val lightDevices: List<OnOffLightDevice>
val doorlockDevices: List<DoorLockDevice>
// Send all the commands
val responses: List<DeferredResponse<Unit>> = home.sendBatchedCommands {
// For each light device, send a Batchable command to turn it on
val lightResponses: List<DeferredResponse<Unit>> = lightDevices.map { lightDevice ->
add(lightDevice.standardTraits.onOff.onBatchable())
}
// For each doorlock device, send a Batchable command to lock it
val doorLockResponse: List<DeferredResponse<Unit>> = doorlockDevices.map { doorlockDevice ->
add(doorlockDevice.standardTraits.doorLock.lockDoorBatchable())
}
lightResponses + doorLockResponses
}
// Check that all responses were successful
for (response in responses) {
response.getOrThrow()
}