Add Google local indicator (#66610)

This commit is contained in:
Paulus Schoutsen 2022-02-16 07:54:59 -08:00 committed by GitHub
parent 3d1cad9f67
commit cd5b69d02e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 26 additions and 1 deletions

View file

@ -441,6 +441,7 @@ async def _account_data(hass: HomeAssistant, cloud: Cloud):
"email": claims["email"], "email": claims["email"],
"google_entities": client.google_user_config["filter"].config, "google_entities": client.google_user_config["filter"].config,
"google_registered": google_config.has_registered_user_agent, "google_registered": google_config.has_registered_user_agent,
"google_local_connected": google_config.is_local_connected,
"logged_in": True, "logged_in": True,
"prefs": client.prefs.as_dict(), "prefs": client.prefs.as_dict(),
"remote_certificate": certificate, "remote_certificate": certificate,

View file

@ -4,6 +4,7 @@ from __future__ import annotations
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from asyncio import gather from asyncio import gather
from collections.abc import Mapping from collections.abc import Mapping
from datetime import datetime, timedelta
from http import HTTPStatus from http import HTTPStatus
import logging import logging
import pprint import pprint
@ -26,6 +27,7 @@ from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.helpers.event import async_call_later from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.network import get_url from homeassistant.helpers.network import get_url
from homeassistant.helpers.storage import Store from homeassistant.helpers.storage import Store
from homeassistant.util.dt import utcnow
from . import trait from . import trait
from .const import ( from .const import (
@ -104,6 +106,7 @@ class AbstractConfig(ABC):
self._store = None self._store = None
self._google_sync_unsub = {} self._google_sync_unsub = {}
self._local_sdk_active = False self._local_sdk_active = False
self._local_last_active: datetime | None = None
async def async_initialize(self): async def async_initialize(self):
"""Perform async initialization of config.""" """Perform async initialization of config."""
@ -149,6 +152,15 @@ class AbstractConfig(ABC):
"""Return if states should be proactively reported.""" """Return if states should be proactively reported."""
return False return False
@property
def is_local_connected(self) -> bool:
"""Return if local is connected."""
return (
self._local_last_active is not None
# We get a reachable devices intent every minute.
and self._local_last_active > utcnow() - timedelta(seconds=70)
)
def get_local_agent_user_id(self, webhook_id): def get_local_agent_user_id(self, webhook_id):
"""Return the user ID to be used for actions received via the local SDK. """Return the user ID to be used for actions received via the local SDK.
@ -336,6 +348,7 @@ class AbstractConfig(ABC):
# pylint: disable=import-outside-toplevel # pylint: disable=import-outside-toplevel
from . import smart_home from . import smart_home
self._local_last_active = utcnow()
payload = await request.json() payload = await request.json()
if _LOGGER.isEnabledFor(logging.DEBUG): if _LOGGER.isEnabledFor(logging.DEBUG):

View file

@ -281,7 +281,7 @@ async def async_devices_identify(hass, data: RequestData, payload):
async def async_devices_reachable(hass, data: RequestData, payload): async def async_devices_reachable(hass, data: RequestData, payload):
"""Handle action.devices.REACHABLE_DEVICES request. """Handle action.devices.REACHABLE_DEVICES request.
https://developers.google.com/actions/smarthome/create#actiondevicesdisconnect https://developers.google.com/assistant/smarthome/develop/local#implement_the_reachable_devices_handler_hub_integrations_only
""" """
google_ids = {dev["id"] for dev in (data.devices or [])} google_ids = {dev["id"] for dev in (data.devices or [])}

View file

@ -424,6 +424,7 @@ async def test_websocket_status(
"exclude_entities": [], "exclude_entities": [],
}, },
"google_registered": False, "google_registered": False,
"google_local_connected": False,
"remote_domain": None, "remote_domain": None,
"remote_connected": False, "remote_connected": False,
"remote_certificate": None, "remote_certificate": None,

View file

@ -94,7 +94,9 @@ async def test_config_local_sdk(hass, hass_client):
client = await hass_client() client = await hass_client()
assert config.is_local_connected is False
config.async_enable_local_sdk() config.async_enable_local_sdk()
assert config.is_local_connected is False
resp = await client.post( resp = await client.post(
"/api/webhook/mock-webhook-id", "/api/webhook/mock-webhook-id",
@ -122,6 +124,14 @@ async def test_config_local_sdk(hass, hass_client):
"requestId": "mock-req-id", "requestId": "mock-req-id",
}, },
) )
assert config.is_local_connected is True
with patch(
"homeassistant.components.google_assistant.helpers.utcnow",
return_value=dt.utcnow() + timedelta(seconds=90),
):
assert config.is_local_connected is False
assert resp.status == HTTPStatus.OK assert resp.status == HTTPStatus.OK
result = await resp.json() result = await resp.json()
assert result["requestId"] == "mock-req-id" assert result["requestId"] == "mock-req-id"