Android 上的 Structure API

您可以透過 Home API for Android 存取 Structure API。將下列套件匯入應用程式:

import com.google.home.Home
import com.google.home.Id
import com.google.home.Structure

錯誤處理

Home API 中的任何方法都可能擲回 HomeException,因此建議您使用 try-catch 區塊,在所有呼叫中擷取 HomeException。

處理 HomeException 時,請檢查其 error.code 和 error.message 欄位,瞭解發生什麼錯誤。此外,也可能會有子錯誤代碼,因此請呼叫 getSubErrorCodes() 方法並檢查結果。

任何未處理的例外狀況都會導致應用程式當機。

詳情請參閱「錯誤處理」。

範例呼叫

取得住家結構體清單

初始化後,structures() 呼叫會傳回您可以存取的結構流程:

// Get a flow of all structures accessible to the user
val allStructuresFlow: HomeObjectsFlow<Structure> = home.structures()

// Calling list() on a HomeObjectsFlow returns the first Set of elements.
val allStructures: Set<Structure> = allStructuresFlow.list()

structures() API 是一種流程,可能不會立即傳回有效的結構清單。如果應用程式是反應式,且訂閱該流程來驅動 UI,最終應會傳回有效的結構清單。在其他情況下,系統也可能傳回空白結構清單,例如使用者的手機失去連線能力,或使用者撤銷應用程式的權限。請務必在應用程式中處理這些情況。

或者,如果必須使用指令式程式設計,而非反應式程式設計,則可使用終端流程運算子:

val everyStructure = withTimeout(5000) { home.structures().first { it.isNotEmpty() } }

這項呼叫會等待有效的結構清單通過流程,如果未在應用程式指定的逾時時間內收到清單,就會逾時。

取得結構體屬性

取得結構清單後,即可存取其屬性:

// Get a flow on a structure. Flow emits new values on structure metadata changes: name.
val structureFlow: Flow<Structure> = home.structures().itemFlow(myStructureId)

// Get a snapshot of the structure.
val structure: Structure = structureFlow.first()

// Get structure properties
println("id ${structure.id}")
println("name ${structure.name}")

依名稱尋找住家結構體

如果您知道結構體的名稱,也可以使用 name 屬性存取:

val myHome = home.structures().list().first { it.name == "My home" }

您可以在這裡存取每個住家結構體的房地產、房間和裝置。

使用多個住家結構體

如要使用多個結構,請分別取得每個結構的參照:

var structure1: Structure? = null
var structure2: Structure? = null

try {
  structure1 = home.structures().list().firstOrNull { it.name == "Main House" }
} catch (e: HomeException) {
  // Code for handling the exception
}
try {
  structure2 = home.structures().list().firstOrNull { it.name == "Guest Cottage" }
} catch (e: HomeException) {
  // Code for handling the exception
}

取得聊天室清單

取得結構後,您可以取得房間清單並存取其屬性:

val allRoomsFlow: HomeObjectsFlow<Room> = structure.rooms()
val allRooms: Set<Room> = allRoomsFlow.list()
val room: Room = allRooms.first()

println("id ${room.id}")
println("name ${room.name}")

建立聊天室

如要建立新房間,請按照下列步驟操作:

val testName = "Test Room Name"
val newRoom: Room = structure.createRoom(testName)

刪除房間

或者,你也可以刪除房間:

val roomToDelete = structure.rooms().list().filter { it.name == "room_id1" }.firstOrNull()
    structure.deleteRoom(roomToDelete!!)

您也可以只使用 ID 刪除聊天室:

val roomToDelete1 = allRooms.filter { it.id == testRoomId }.firstOrNull()
structure.deleteRoom(roomToDelete1!!)

如果刪除含有裝置的房間,裝置仍會保留在住家中,但不會再指派給任何房間。

將裝置移到其他房間

建立住家結構體後,可以將裝置移到該結構體中的其他房間:

val room2 = structure.rooms().get(Id("room_id_other_structure"))
    val device1 = structure.devices().get(Id("device_id1"))
    structure.moveDevicesToRoom(room2!!, listOf(device1!!))

如果只有裝置和房間 ID,也可以移動裝置:

structure.moveDevicesToRoom(Id("room_id_other_structure"), listOf(Id("device_id1")))

變更房間名稱

呼叫 setName() 方法,變更房間名稱:

livingRoom.setName("Living Room")

如果名稱超過 60 個 Unicode 碼點 (字元) 限制,系統會截斷名稱,且不會擲回任何錯誤。開發人員必須負責處理過長的名稱,例如決定是否要通知使用者名稱會遭到截斷。

在 Google Home 生態系統中,使用者可以一次授予某個裝置類型中所有裝置的權限。如果是機密或受限制的裝置類型 (例如智慧門鎖、攝影機或門鈴),使用者必須個別授予權限。

如要判斷使用者是否已授予存取機密或受限裝置類型的權限,請使用住家層級的 consentedDeviceTypes() 函式:

import com.google.home.Structure
import com.google.home.DeviceType
import com.google.home.DeviceTypeFactory
import com.google.home.consentedDeviceTypes // Extension function from the SDK
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * Example of how an app may monitor which device types have been granted access by a user.
 */
fun monitorDeviceConsent(structure: Structure, myScope: CoroutineScope) {
    // Obtain the flow of consented device type factories
    val consentedTypesFlow: Flow<Set<DeviceTypeFactory<out DeviceType>>> =
        structure.consentedDeviceTypes()

    myScope.launch {
        consentedTypesFlow.collect { consentedSet ->
            // Check if the user has consented to share a specific restricted
            // type, such as a Doorbell or Camera.
            val hasCameraAccess = consentedSet.any {
                it.toString() == "matter.google.type.GoogleDoorbellDevice"
            }

            if (hasCameraAccess) {
                // Enable features that require camera access
            } else {
                // Inform the user or disable camera-specific features
            }
        }
    }
}

裝置群組

裝置群組代表使用者在單一結構中定義的裝置集合。Google 服務會保留群組成員資格,住家結構體的其他成員和有權存取住家結構體的其他應用程式,都能看到這項資訊。

裝置群組和實體房間一樣,都屬於單一住家結構體。但與房間不同的是,裝置群組是邏輯分組。一部裝置可以同時屬於多個裝置群組。裝置群組最多可包含 100 部裝置。

裝置群組由 DeviceGroup 實體表示,與 HomeDevice 不同。如要查詢裝置群組並與其互動,請在初始化 FactoryRegistry 時,將 DeviceGroup 納入 entityTypes 清單,並加入 Group、GroupManagement 和 GroupMembership 特性。

如要與群組中的裝置互動,可以直接疊代成員裝置 (請參閱「與群組成員裝置互動」),也可以指定 DeviceGroup 上的裝置類型部分 (請參閱「控制裝置群組」)。

取得裝置群組清單

如要觀察住家結構中的所有裝置群組,請呼叫 home.entities(DeviceGroup),並依住家結構的 ID 篩選:

home.entities(DeviceGroup).collect { allGroups ->
  val structureGroups = allGroups.filter { it.structureId == structure.id }
  for (group in structureGroups) {
    val groupName = group.trait(Group)?.Name
    println("Found group: $groupName with ID: ${group.id.id}")
  }
}

與群組成員裝置互動

使用 group.devices() 疊代群組的成員裝置,可精細控管個別成員、在單一要求中批次處理指令,以及匯總或寫入成員的屬性。

舉例來說,如要傳送單一批次要求,其中包含群組中所有相容成員的特徵指令,請按照下列步驟操作:

val members = group.devices(enableMultipartDevices = true).first()
val onOffTraits = members.mapNotNull { device ->
  device.partOrNull(OnOffLightDevice).first()?.standardTraits?.onOff
}

val responses = home.sendBatchedCommands {
  onOffTraits.map { onOff ->
    add(onOff.onBatchable())
  }
}

for (response in responses) {
  response.getOrThrow()
}

您也可以更新群組中所有相符成員裝置的屬性 (例如將所有 DimmableLightDevice 成員的 onTransitionTime 設為 1u),並在期限內等待完成:

val members = group.devices(enableMultipartDevices = true).first()

withTimeout(5.seconds) {
  members.map { device ->
    async {
      val light = device.partOrNull(DimmableLightDevice).first()
      val levelControl = light?.standardTraits?.levelControl
      if (
        levelControl?.supports(
          LevelControl.Attribute.onTransitionTime
        ) == true
      ) {
        levelControl.update { setOnTransitionTime(1u) }
      }
    }
  }.awaitAll()
}

如要匯總群組成員的屬性,例如找出群組中所有色溫燈的最低 colorTempPhysicalMaxMireds,請按照下列步驟操作:

val members = group.devices(enableMultipartDevices = true).first()
val minMaxMireds: UShort? = members.mapNotNull { device ->
  val light = device.partOrNull(ColorTemperatureLightDevice).first()
  light?.standardTraits?.colorControl?.colorTempPhysicalMaxMireds
}.minOrNull()

建立裝置群組

在住家結構上使用 GroupManagement 建立裝置群組:

val groupManagement = structure.trait(GroupManagementTrait)
val response = groupManagement?.createUserDefinedGroup(
  name = "Living room lights",
  memberDeviceObjectIds = listOf(light1.id.id, light2.id.id)
)

管理群組成員

如要將成員新增至現有群組,請按照下列步驟操作:

structure.trait(GroupManagementTrait)?.addGroupMembers(
  groupObjectId = group.id.id,
  memberDeviceObjectIds = listOf(light3.id.id)
)

如要將成員從群組中移除,請按照下列步驟操作:

structure.trait(GroupManagementTrait)?.removeGroupMembers(
  groupObjectId = group.id.id,
  memberDeviceObjectIds = listOf(light1.id.id)
)

變更裝置群組名稱

如要重新命名裝置群組,請更新群組 GroupTrait 的名稱屬性:

group.trait(GroupTrait)?.update {
  name = "Movie corner"
}

刪除裝置群組

如何從住家中刪除裝置群組:

structure.trait(GroupManagementTrait)?.deleteGroup(
  groupObjectId = group.id.id
)

自動化動作

Automation API 的進入點是透過結構體。如要進一步瞭解 Home API 中的自動化動作,請參閱「Android 的 Automation API 總覽」。