Update Ring to 0.6.0 (#30748)
* Update Ring to 0.6.0 * Update sensor tests * update -> async_update * Delete temp files * Address comments * Final tweaks * Remove stale print
This commit is contained in:
1 parent
8e5f46d5b5
commit
4bc520c724
19 files changed
+417
-418
No files matched your search
@@ -4,15 +4,17 @@ from datetime import timedelta
|
||||
from functools import partial
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from time import time
|
||||
|
||||
from ring_doorbell import Auth, Ring
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, __version__
|
||||
from homeassistant.core import callback
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.dispatcher import dispatcher_send
|
||||
from homeassistant.helpers.event import track_time_interval
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send, dispatcher_send
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
from homeassistant.util.async_ import run_callback_threadsafe
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -22,14 +24,14 @@ ATTRIBUTION = "Data provided by Ring.com"
|
||||
NOTIFICATION_ID = "ring_notification"
|
||||
NOTIFICATION_TITLE = "Ring Setup"
|
||||
|
||||
DATA_RING_DOORBELLS = "ring_doorbells"
|
||||
DATA_RING_STICKUP_CAMS = "ring_stickup_cams"
|
||||
DATA_RING_CHIMES = "ring_chimes"
|
||||
DATA_HISTORY = "ring_history"
|
||||
DATA_HEALTH_DATA_TRACKER = "ring_health_data"
|
||||
DATA_TRACK_INTERVAL = "ring_track_interval"
|
||||
|
||||
DOMAIN = "ring"
|
||||
DEFAULT_ENTITY_NAMESPACE = "ring"
|
||||
SIGNAL_UPDATE_RING = "ring_update"
|
||||
SIGNAL_UPDATE_HEALTH_RING = "ring_health_update"
|
||||
|
||||
SCAN_INTERVAL = timedelta(seconds=10)
|
||||
|
||||
@@ -88,51 +90,42 @@ async def async_setup_entry(hass, entry):
|
||||
),
|
||||
).result()
|
||||
|
||||
auth = Auth(entry.data["token"], token_updater)
|
||||
auth = Auth(f"HomeAssistant/{__version__}", entry.data["token"], token_updater)
|
||||
ring = Ring(auth)
|
||||
|
||||
await hass.async_add_executor_job(finish_setup_entry, hass, ring)
|
||||
await hass.async_add_executor_job(ring.update_data)
|
||||
|
||||
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = ring
|
||||
|
||||
for component in PLATFORMS:
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, component)
|
||||
)
|
||||
|
||||
return True
|
||||
if hass.services.has_service(DOMAIN, "update"):
|
||||
return True
|
||||
|
||||
|
||||
def finish_setup_entry(hass, ring):
|
||||
"""Finish setting up entry."""
|
||||
devices = ring.devices
|
||||
hass.data[DATA_RING_CHIMES] = chimes = devices["chimes"]
|
||||
hass.data[DATA_RING_DOORBELLS] = doorbells = devices["doorbells"]
|
||||
hass.data[DATA_RING_STICKUP_CAMS] = stickup_cams = devices["stickup_cams"]
|
||||
|
||||
ring_devices = chimes + doorbells + stickup_cams
|
||||
|
||||
def service_hub_refresh(service):
|
||||
hub_refresh()
|
||||
|
||||
def timer_hub_refresh(event_time):
|
||||
hub_refresh()
|
||||
|
||||
def hub_refresh():
|
||||
"""Call ring to refresh information."""
|
||||
_LOGGER.debug("Updating Ring Hub component")
|
||||
|
||||
for camera in ring_devices:
|
||||
_LOGGER.debug("Updating camera %s", camera.name)
|
||||
camera.update()
|
||||
|
||||
dispatcher_send(hass, SIGNAL_UPDATE_RING)
|
||||
async def refresh_all(_):
|
||||
"""Refresh all ring accounts."""
|
||||
await asyncio.gather(
|
||||
*[
|
||||
hass.async_add_executor_job(api.update_data)
|
||||
for api in hass.data[DOMAIN].values()
|
||||
]
|
||||
)
|
||||
async_dispatcher_send(hass, SIGNAL_UPDATE_RING)
|
||||
|
||||
# register service
|
||||
hass.services.register(DOMAIN, "update", service_hub_refresh)
|
||||
hass.services.async_register(DOMAIN, "update", refresh_all)
|
||||
|
||||
# register scan interval for ring
|
||||
hass.data[DATA_TRACK_INTERVAL] = track_time_interval(
|
||||
hass, timer_hub_refresh, SCAN_INTERVAL
|
||||
hass.data[DATA_TRACK_INTERVAL] = async_track_time_interval(
|
||||
hass, refresh_all, SCAN_INTERVAL
|
||||
)
|
||||
hass.data[DATA_HEALTH_DATA_TRACKER] = HealthDataUpdater(hass)
|
||||
hass.data[DATA_HISTORY] = HistoryCache(hass)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass, entry):
|
||||
@@ -148,13 +141,103 @@ async def async_unload_entry(hass, entry):
|
||||
if not unload_ok:
|
||||
return False
|
||||
|
||||
await hass.async_add_executor_job(hass.data[DATA_TRACK_INTERVAL])
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
|
||||
if len(hass.data[DOMAIN]) != 0:
|
||||
return True
|
||||
|
||||
# Last entry unloaded, clean up
|
||||
hass.data.pop(DATA_TRACK_INTERVAL)()
|
||||
hass.data.pop(DATA_HEALTH_DATA_TRACKER)
|
||||
hass.data.pop(DATA_HISTORY)
|
||||
hass.services.async_remove(DOMAIN, "update")
|
||||
|
||||
hass.data.pop(DATA_RING_DOORBELLS)
|
||||
hass.data.pop(DATA_RING_STICKUP_CAMS)
|
||||
hass.data.pop(DATA_RING_CHIMES)
|
||||
hass.data.pop(DATA_TRACK_INTERVAL)
|
||||
return True
|
||||
|
||||
return unload_ok
|
||||
|
||||
class HealthDataUpdater:
|
||||
"""Data storage for health data."""
|
||||
|
||||
def __init__(self, hass):
|
||||
"""Track devices that need health data updated."""
|
||||
self.hass = hass
|
||||
self.devices = {}
|
||||
self._unsub_interval = None
|
||||
|
||||
async def track_device(self, config_entry_id, device):
|
||||
"""Track a device."""
|
||||
if not self.devices:
|
||||
self._unsub_interval = async_track_time_interval(
|
||||
self.hass, self.refresh_all, SCAN_INTERVAL
|
||||
)
|
||||
|
||||
key = (config_entry_id, device.device_id)
|
||||
|
||||
if key not in self.devices:
|
||||
self.devices[key] = {
|
||||
"device": device,
|
||||
"count": 1,
|
||||
}
|
||||
else:
|
||||
self.devices[key]["count"] += 1
|
||||
|
||||
await self.hass.async_add_executor_job(device.update_health_data)
|
||||
|
||||
@callback
|
||||
def untrack_device(self, config_entry_id, device):
|
||||
"""Untrack a device."""
|
||||
key = (config_entry_id, device.device_id)
|
||||
self.devices[key]["count"] -= 1
|
||||
|
||||
if self.devices[key]["count"] == 0:
|
||||
self.devices.pop(key)
|
||||
|
||||
if not self.devices:
|
||||
self._unsub_interval()
|
||||
self._unsub_interval = None
|
||||
|
||||
def refresh_all(self, _):
|
||||
"""Refresh all registered devices."""
|
||||
for info in self.devices.values():
|
||||
info["device"].update_health_data()
|
||||
|
||||
dispatcher_send(self.hass, SIGNAL_UPDATE_HEALTH_RING)
|
||||
|
||||
|
||||
class HistoryCache:
|
||||
"""Helper to fetch history."""
|
||||
|
||||
STALE_AFTER = 10 # seconds
|
||||
|
||||
def __init__(self, hass):
|
||||
"""Initialize history cache."""
|
||||
self.hass = hass
|
||||
self.cache = {}
|
||||
|
||||
async def async_get_history(self, config_entry_id, device):
|
||||
"""Get history of a device."""
|
||||
key = (config_entry_id, device.device_id)
|
||||
|
||||
if key in self.cache:
|
||||
info = self.cache[key]
|
||||
|
||||
# We're already fetching data, join that task
|
||||
if "task" in info:
|
||||
return await info["task"]
|
||||
|
||||
# We have valid cache info, return that
|
||||
if time() - info["created_at"] < self.STALE_AFTER:
|
||||
return info["data"]
|
||||
|
||||
self.cache.pop(key)
|
||||
|
||||
# Fetch data
|
||||
task = self.hass.async_add_executor_job(partial(device.history, limit=10))
|
||||
|
||||
self.cache[key] = {"task": task}
|
||||
|
||||
data = await task
|
||||
|
||||
self.cache[key] = {"created_at": time(), "data": data}
|
||||
|
||||
return data
|
||||
Reference in new issue
Block a user