Guia do dispositivo roteador de borda para Android

Os desenvolvedores de apps Android podem usar as APIs Home para gerenciar um Thread Border Router (TBR).

O GoogleBorderRouterDevice é implementado usando dois atributos principais do dispositivo: ThreadNetworkCapabilities, que fornece atributos somente leitura para inspecionar os recursos do border router, e ThreadNetworkManagement, que processa comandos de ciclo de vida da rede e compartilhamento de credenciais usando uma chave pré-compartilhada temporária para o comissário (ePSKc). As políticas de acesso à Internet no nível da estrutura são gerenciadas usando o atributo ThreadNetworkSettings.

Sempre verifique se o dispositivo é compatível com atributos e comandos antes de usar qualquer recurso ou tentar atualizar atributos. Consulte Controlar dispositivos no Android para mais informações.

Tipo de dispositivo das APIs Home Características App de exemplo em Kotlin Caso de uso

Roteador de borda

GoogleBorderRouterDevice

home.matter.6006.types.0161

Atributos obrigatórios
     google ThreadNetworkCapabilities
     google ThreadNetworkManagement

Roteador de borda

Receber informações básicas sobre um dispositivo

   Implementado no app de exemplo para Android   

O atributo BasicInformation inclui informações como nome do fornecedor, ID do fornecedor, ID do produto, nome do produto (inclui informações do modelo) e versão do software de um dispositivo:

// Get device basic information. All general information traits are on the RootNodeDevice type.
    device.type(RootNodeDevice).first().standardTraits.basicInformation?.let { basicInformation ->
        println("vendorName ${basicInformation.vendorName}")
        println("vendorId ${basicInformation.vendorId}")
        println("productId ${basicInformation.productId}")
        println("productName ${basicInformation.productName}")
        println("softwareVersion ${basicInformation.softwareVersion}")
    }

Inspecionar os recursos do roteador de borda

É possível examinar os recursos somente leitura de um border router, como suporte a ePSKc e configuração de acesso à Internet, usando o atributo ThreadNetworkCapabilities.

suspend fun checkBorderRouterCapabilities(device: HomeDevice) {
    // Filter for GoogleBorderRouterDevice device type
    val gtbrDevice = device.type(GoogleBorderRouterDevice).firstOrNull()
    if (gtbrDevice == null) {
        println("Device is not a Google border router.")
        return
    }

    // Retrieve the ThreadNetworkCapabilities trait
    val capabilitiesTrait = gtbrDevice.trait(ThreadNetworkCapabilities)
    if (capabilitiesTrait == null) {
        println("ThreadNetworkCapabilities trait not found on device.")
        return
    }

    val isEpskcSupported = capabilitiesTrait.epskcSupported ?: false
    val internetAccessOption = capabilitiesTrait.internetAccessOption?.name ?: "None"
    val isIasSupported = !internetAccessOption.equals("None", ignoreCase = true)

    println("ePSKc Supported: $isEpskcSupported")
    println("Internet Access Setting Supported: $isIasSupported")
}

Gerenciar o compartilhamento de credenciais do Thread (ePSKc)

O compartilhamento de credenciais do Thread é feito usando uma chave pré-compartilhada temporária para o comissário (ePSKc). O modo ePSKc gera uma chave de acesso temporária e segura que dispositivos externos ou comissários podem usar para receber o conjunto de dados da rede Thread com segurança.

Ativar o modo ePSKc

suspend fun startEpskcSession(device: HomeDevice, durationSeconds: Short): ActivateEpskcModeCommand.Response? {
    val gtbrDevice = device.type(GoogleBorderRouterDevice).firstOrNull()
    val mgmtTrait = gtbrDevice?.trait(ThreadNetworkManagement)

    if (mgmtTrait == null) {
        println("ThreadNetworkManagement trait not found.")
        return null
    }

    return try {
        val response = mgmtTrait.activateEpskcMode(
            optionalArgs = { this.requestedDurationSeconds = durationSeconds }
        )

        println("ePSKc Session Activated!")
        println("Status: ${response.status}")
        println("Ephemeral PSKc: ${response.epskc}")
        println("Valid Duration (s): ${response.validDurationSeconds}")

        response
    } catch (e: Exception) {
        println("Failed to activate ePSKc mode: ${e.message}")
        null
    }
}

Desativar o modo ePSKc

suspend fun stopEpskcSession(device: HomeDevice) {
    val gtbrDevice = device.type(GoogleBorderRouterDevice).firstOrNull()
    val mgmtTrait = gtbrDevice?.trait(ThreadNetworkManagement)

    mgmtTrait?.deactivateEpskcMode()
    println("ePSKc mode deactivated.")
}

Observar eventos de desativação de ePSKc

Os TBRs emitem eventos quando uma sessão de ePSKc termina (por exemplo, porque a chave foi usada, a sessão expirou ou foi cancelada manualmente).

suspend fun observeEpskcEvents(device: HomeDevice) {
    val gtbrDevice = device.type(GoogleBorderRouterDevice).firstOrNull()
    val mgmtTrait = gtbrDevice?.trait(ThreadNetworkManagement)

    mgmtTrait?.epskcModeDeactivatedEventFlow()?.collect { event ->
        println("ePSKc Session Ended. Reason: ${event.reason}")
        when (event.reason?.name) {
            "KeyUsed" -> println("Key was successfully used to commission a device.")
            "Expired" -> println("Session timed out before the key was used.")
            "Cancelled" -> println("Session was manually cancelled.")
        }
    }
}

Gerenciar a participação na rede Thread

É possível comandar um TBR para que ele entre em uma nova rede Thread fornecendo os TLVs do conjunto de dados operacionais ativos ou comandar que ele saia da rede atual.

suspend fun joinNetwork(device: HomeDevice, datasetTlvs: ByteArray) {
    val gtbrDevice = device.type(GoogleBorderRouterDevice).firstOrNull()
    val mgmtTrait = gtbrDevice?.trait(ThreadNetworkManagement)

    try {
        val response = mgmtTrait?.joinNetwork(operationalDatasetTlvs = datasetTlvs)
        println("Join network command sent. Status: ${response?.status}")
    } catch (e: Exception) {
        println("Join network failed: ${e.message}")
    }
}

suspend fun leaveNetwork(device: HomeDevice) {
    val gtbrDevice = device.type(GoogleBorderRouterDevice).firstOrNull()
    val mgmtTrait = gtbrDevice?.trait(ThreadNetworkManagement)

    try {
        mgmtTrait?.leaveNetwork()
        println("Leave network command sent successfully.")
    } catch (e: Exception) {
        println("Leave network failed: ${e.message}")
    }
}

Configurar o acesso à Internet no nível da estrutura

O atributo ThreadNetworkSettings é atualizável e está anexado a um Structure (que representa uma casa ou um edifício). Ele permite que os desenvolvedores configurem a política de acesso à Internet em toda a estrutura para TBRs.

suspend fun updateStructureInternetAccess(structure: Structure, enableInternetAccess: Boolean) {
    // Retrieve the ThreadNetworkSettings trait for the structure
    val settingsTrait = structure.trait(ThreadNetworkSettings).firstOrNull()
    if (settingsTrait == null) {
        println("ThreadNetworkSettings trait not found on structure.")
        return
    }

    val option = if (enableInternetAccess) {
        InternetAccessOption.InternetAccessOptionAll
    } else {
        InternetAccessOption.InternetAccessOptionNone
    }

    try {
        settingsTrait.update {
            setInternetAccessOption(option)
        }
        println("Successfully updated Thread internet access policy to: ${option.name}")
    } catch (e: Exception) {
        println("Failed to update Thread internet access policy: ${e.message}")
    }
}