在 Android 適用的 Home API 中,您可以使用 Kotlin 的流程,觀察住家狀態的變化。如要觀察 Home API 中結構、房間、裝置中繼資料和裝置狀態的變化,可以使用任何從 HomeObjectsFlow
介面繼承的 API。方法是從資料流收集資料。
當集合中的任何項目新增、刪除或修改時,系統會傳回集合的最新快照。
開發人員必須比較這個快照與舊副本,才能推斷具體變更。Home API 中每個父項物件類型提供的 id
欄位可用於此用途。
如何使用流程
以下是透過 Home API 中的流程收集資料的一些基本範例。
在下列範例中,存取主畫面中的集合前,必須先建立 Home
的執行個體:
val context = LocalContext.current
val homeManager = Home.getClient(context)
追蹤結構的變更
結構發生下列變更時,系統會觸發這項集合:
- 結構名稱
homeManager.structures().map { it.firstOrNull() }.collect {
println("Structure ${it.id} updated to ${it}")
}
val structure = homeManager.structures().list().firstOrNull()!!
追蹤特定裝置的變更
裝置發生下列變更時,系統會觸發收集作業:
structure
.devices()
.map { devices -> device.filter { it.name == "Bedroom Lamp" }.single() }
.collect {
println("The bedroom lamp has changed!")
}
val device = structure.devices().list().firstOrNull { it.name == "Bedroom Lamp" }!!
追蹤裝置上特定特徵的變更
使用裝置和 Google Home API 支援的任何特徵。如需完整清單,請參閱 Trait
。
val trait = device.type(DimmableLightDevice)?.map { it.trait(OnOff)}.first()
trait?.collect {
if (it != null) {
println("Got new state update! ${it.onOff}")
}
}
追蹤裝置上特定類型的變更
裝置類型發生下列變更時,系統會觸發這項收集作業:
- 產生的裝置類型中任何特徵的變更
使用 Home API 支援的任何 Matter 裝置類型。如需完整清單,請參閱 DeviceType
。
device.type(DimmableLightDevice).collect { type ->
println("Got new state update! ${type.trait(LevelControl)?.currentLevel}")
}
追蹤結構中聊天室的變更
如果會議室發生下列變更,系統就會觸發這項收集作業:
如要追蹤裝置何時新增至房間或從房間移除,請使用 devices()
流程。
structure.rooms().collect {
println("Got a new updated set of rooms!")
for (room in it) {
println("Got room $room")
}
}
訂閱活動
在 Home API 中,事件用於偵測裝置狀態的變化。
如要訂閱特定裝置上的事件,請呼叫下列其中一個函式:HomeDevice
。events
函式,每個函式都會傳回 Flow<Event>
:
events(event: EventFactory<T>)
會傳回特定類型事件的流程:val eventFlow = homeDevice.type(DoorLockDevice).first().events(DoorLock.DoorLockAlarmEvent)
events(trait: TraitFactory<T>)
會傳回特徵傳送的所有事件資料流:val eventflow = homeDevice.type(DoorLockDevice).first().events(DoorLock)
events()
會傳回物件可用的事件流程:val eventflow = homeDevice.type(DoorLockDevice).first().events()
如要從資料流使用事件,請使用 flow.collect()
函式:
eventflow.collect { event ->
if (event != null) {
logger.atInfo().log("Received event %s", event)
// do something
}
}
訂閱實體關係事件
您可以監聽實體 (例如結構、房間、裝置或自動化動作) 新增、移除或更新時發出的事件。這些事件是 HomeObjectChangeEvent
的執行個體,並攜帶變更實體的 ID。
如要取得產生所需事件的資料流,請在對應的 Flow 方法產生的 HomeObjectsFlow<T>
上呼叫 stream()
方法:
實體 | 介面 | 流程方法 |
---|---|---|
Structure
|
HasStructures
|
structures()
|
Room
|
HasRooms
|
rooms()
|
HomeDevice
|
HasHomeDevices
|
devices()
|
Automation
|
HasAutomations
|
automations()
|
舉例來說,您可以按照下列方式處理裝置變更:
val devicesStream = home.devices().stream() // Collect and react to device changes. devicesStream.collect { deviceEvent -> when (deviceEvent) { is HomeObjectAddedEvent -> println("New device now available with id: ${deviceEvent.id}") is HomeObjectUpdatedEvent -> println("Device ${deviceEvent.id} has been updated") is HomeObjectRemovedEvent -> println("Device is removed from your account") else -> {} } }