Hub Activation API on Android

‫Hub Activation API מאפשר לגלות ולהפעיל רכזת Google Home באופן פרוגרמטי. האפשרות הזו שימושית במיוחד כשאין למשתמש דרך אחרת להפעיל את הרכזת, כמו במקרה של רכזת ללא מסך.

שימוש ב-Hub Activation API

באמצעות Hub Activation API, אפשר ליצור אפליקציה שיכולה לגלות רכזות ולהפעיל אותן.

  1. מקבלים הפניה אל HubManagementTrait במבנה:

    val hubManagementTrait =
      hubManagementTraitFlow.firstOrNull {
        it.metadata.sourceConnectivity?.connectivityState == ConnectivityState.ONLINE
      }
    if (hubManagementTrait == null) {
      errorsEmitter.emit(HomeException.notFound("HubManagement trait isn't online"))
    }
    
  2. מזהים מכשירים עם יכולת של רכזת ברשת ה-Wi-Fi:

    try {
      val unused = hubManagementTrait.discoverAvailableHubs()
    } catch (e: Exception) {
      Log.d(TAG_HUB_DISCOVERY, "Error discovering hubs $e")
      errorsEmitter.emit(e)
    }
    
    val hubManagementTraitFlow = structureFlow.flatMapLatest { it.trait(HubManagement) }
    
    val discoveredHubs =
      hubManagementTraitFlow
        .map { it.discoveredHubsList }
        .handleErrors()
        .flowOn(ioDispatcher)
        .stateIn(
          scope = CoroutineScope(viewModelScope.coroutineContext + ioDispatcher),
          started = SharingStarted.WhileSubscribed(),
          listOf(),
        )
    
  3. הפעלת מכשיר עם יכולת רכזת:

    try {
      val unused = hubManagementTrait.activateHub(hub)
    } catch (e: Exception) {
      Log.d("Hub Activation", "Error activating hub $e")
    }