Przewodnik po urządzeniach z routerem granicznym na iOS

Deweloperzy aplikacji na iOS mogą używać interfejsów Home API do zarządzania urządzeniem Thread Border Router (TBR).

GoogleBorderRouterDevice jest wdrażany za pomocą 2 głównych cech urządzenia: ThreadNetworkCapabilitiesTrait, która udostępnia atrybuty tylko do odczytu do sprawdzania funkcji border router, oraz ThreadNetworkManagementTrait, która obsługuje polecenia cyklu życia sieci i udostępnianie danych logowania za pomocą tymczasowego klucza wstępnego dla komisarza (ePSKc). Zasady dostępu do internetu na poziomie domu są zarządzane za pomocą cechy ThreadNetworkSettingsTrait.

Przed użyciem jakichkolwiek funkcji lub próbą aktualizacji atrybutów zawsze sprawdź, czy urządzenie obsługuje dany atrybut i polecenie. Więcej informacji znajdziesz w artykule Sterowanie urządzeniami naiOS.

Typ urządzenia w interfejsach API Google Home Cechy Przykładowa aplikacja Swift Przypadek użycia

Router graniczny

GoogleBorderRouterDeviceType

home.matter.6006.types.0161

Wymagane cechy
     google ThreadNetworkCapabilitiesTrait
     google ThreadNetworkManagementTrait

Router graniczny

Uzyskiwanie podstawowych informacji o urządzeniu

   Zaimplementowano w przykładowej aplikacji na iOS   

Atrybut BasicInformation zawiera informacje takie jak nazwa dostawcy, identyfikator dostawcy, identyfikator produktu, nazwa produktu (w tym informacje o modelu) i wersja oprogramowania urządzenia:

let vendorName = basicInfoTrait.attributes.vendorName!
let vendorID = basicInfoTrait.attributes.vendorID!
let productID = basicInfoTrait.attributes.productID!
let productName = basicInfoTrait.attributes.productName!
let softwareVersion = basicInfoTrait.attributes.softwareVersion!

Sprawdzanie możliwości routera granicznego

Możesz sprawdzić funkcje tylko do odczytu urządzenia border router (takie jak obsługa ePSKc i konfiguracja ustawień dostępu do internetu) za pomocą cechy ThreadNetworkCapabilitiesTrait.

func checkBorderRouterCapabilities(device: HomeDevice) async {
    // Filter for GoogleBorderRouterDevice device type
    guard let gtbrDevice = device.type(Google.GoogleBorderRouterDevice.self) else {
        print("Device is not a Google border router.")
        return
    }

    // Retrieve the ThreadNetworkCapabilitiesTrait
    guard let capabilitiesTrait = gtbrDevice.traits(Google.ThreadNetworkCapabilitiesTrait.self) else {
        print("ThreadNetworkCapabilitiesTrait not found on device.")
        return
    }

    do {
        let isEpskcSupported = try await capabilitiesTrait.epskcSupported.read()
        let internetAccessOption = try await capabilitiesTrait.internetAccessOption.read()
        let isIasSupported = internetAccessOption != .none

        print("ePSKc Supported: \(isEpskcSupported)")
        print("Internet Access Setting Supported: \(isIasSupported)")
    } catch {
        print("Failed to read capabilities: \(error)")
    }
}

Zarządzanie udostępnianiem danych logowania do sieci Thread (ePSKc)

Udostępnianie danych logowania Thread odbywa się za pomocą tymczasowego klucza PSK dla komisarza (ePSKc). Tryb ePSKc generuje tymczasowy, bezpieczny klucz dostępu, którego urządzenia zewnętrzne lub komisarze mogą używać do bezpiecznego uzyskiwania zbioru danych sieci Thread.

Aktywowanie trybu ePSKc

func startEpskcSession(device: HomeDevice, durationSeconds: Int16) async -> Google.ThreadNetworkManagementTrait.ActivateEpskcModeResponse? {
    guard let gtbrDevice = device.type(Google.GoogleBorderRouterDevice.self),
          let mgmtTrait = gtbrDevice.traits(Google.ThreadNetworkManagementTrait.self) else {
        print("ThreadNetworkManagementTrait not found.")
        return nil
    }

    do {
        var request = Google.ThreadNetworkManagementTrait.ActivateEpskcModeRequest()
        request.requestedDurationSeconds = durationSeconds

        let response = try await mgmtTrait.activateEpskcMode(request)

        print("ePSKc Session Activated!")
        print("Status: \(response.status)")
        print("Ephemeral PSKc: \(response.epskc)")
        print("Valid Duration (s): \(response.validDurationSeconds)")

        return response
    } catch {
        print("Failed to activate ePSKc mode: \(error)")
        return nil
    }
}

Dezaktywuj tryb ePSKc

func stopEpskcSession(device: HomeDevice) async {
    guard let gtbrDevice = device.type(Google.GoogleBorderRouterDevice.self),
          let mgmtTrait = gtbrDevice.traits(Google.ThreadNetworkManagementTrait.self) else {
        return
    }

    do {
        try await mgmtTrait.deactivateEpskcMode(Google.ThreadNetworkManagementTrait.DeactivateEpskcModeRequest())
        print("ePSKc mode deactivated.")
    } catch {
        print("Failed to deactivate ePSKc mode: \(error)")
    }
}

Obserwowanie zdarzeń dezaktywacji ePSKc

TBR emitują zdarzenia po zakończeniu sesji ePSKc (np. gdy klucz został użyty, sesja wygasła lub została anulowana ręcznie).

func observeEpskcEvents(device: HomeDevice) async {
    guard let gtbrDevice = device.type(Google.GoogleBorderRouterDevice.self),
          let mgmtTrait = gtbrDevice.traits(Google.ThreadNetworkManagementTrait.self) else {
        return
    }

    do {
        for try await event in mgmtTrait.epskcModeDeactivatedEvent.stream() {
            print("ePSKc Session Ended. Reason: \(event.reason)")
            switch event.reason {
            case .keyUsed:
                print("Key was successfully used to commission a device.")
            case .expired:
                print("Session timed out before the key was used.")
            case .cancelled:
                print("Session was manually cancelled.")
            @unknown default:
                print("Unknown deactivation reason.")
            }
        }
    } catch {
        print("Error streaming ePSKc events: \(error)")
    }
}

Zarządzanie członkostwem w sieci Thread

Możesz wydać urządzeniu TBR polecenie dołączenia do nowej sieci Thread, podając aktywne TLV operacyjnego zbioru danych, lub polecenie opuszczenia bieżącej sieci.

func joinNetwork(device: HomeDevice, datasetTlvs: Data) async {
    guard let gtbrDevice = device.type(Google.GoogleBorderRouterDevice.self),
          let mgmtTrait = gtbrDevice.traits(Google.ThreadNetworkManagementTrait.self) else {
        return
    }

    do {
        var request = Google.ThreadNetworkManagementTrait.JoinNetworkRequest()
        request.operationalDatasetTlvs = datasetTlvs

        let response = try await mgmtTrait.joinNetwork(request)
        print("Join network command sent. Status: \(response.status)")
    } catch {
        print("Join network failed: \(error)")
    }
}

func leaveNetwork(device: HomeDevice) async {
    guard let gtbrDevice = device.type(Google.GoogleBorderRouterDevice.self),
          let mgmtTrait = gtbrDevice.traits(Google.ThreadNetworkManagementTrait.self) else {
        return
    }

    do {
        try await mgmtTrait.leaveNetwork(Google.ThreadNetworkManagementTrait.LeaveNetworkRequest())
        print("Leave network command sent successfully.")
    } catch {
        print("Leave network failed: \(error)")
    }
}

Konfigurowanie dostępu do internetu na poziomie domu

Cecha ThreadNetworkSettings to cecha, którą można aktualizować, powiązana z Structure (reprezentującym dom lub budynek). Pozwala deweloperom skonfigurować zasady dostępu do internetu w całej strukturze dla TBR.

func updateStructureInternetAccess(structure: Structure, enableInternetAccess: Bool) async {
    guard let settingsTrait = structure.traits(Google.ThreadNetworkSettingsTrait.self) else {
        print("ThreadNetworkSettingsTrait not found on structure.")
        return
    }

    let option: Google.ThreadNetworkSettingsTrait.InternetAccessOption = enableInternetAccess ? .internetAccessOptionAll : .internetAccessOptionNone

    do {
        try await settingsTrait.update { mutator in
            mutator.internetAccessOption = option
        }
        print("Successfully updated Thread internet access policy.")
    } catch {
        print("Failed to update Thread internet access policy: \(error)")
    }
}