-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcoordinator.py
74 lines (61 loc) · 2.56 KB
/
coordinator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Data coordinator for receiving LD2450B updates."""
from datetime import datetime
import logging
import time
from .ld2450_ble import LD2450BLE, LD2450BLEState, LD2450BLEConfig
from homeassistant.core import CALLBACK_TYPE, HassJob, HomeAssistant, callback
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
NEVER_TIME = -86400.0
DEBOUNCE_SECONDS = 1.0
class LD2450BLECoordinator(DataUpdateCoordinator[None]):
"""Data coordinator for receiving LD2450 updates."""
def __init__(self, hass: HomeAssistant, ld2450_ble: LD2450BLE) -> None:
"""Initialise the coordinator."""
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
)
self._ld2450_ble = ld2450_ble
ld2450_ble.register_callback(self._async_handle_update)
ld2450_ble.register_disconnected_callback(self._async_handle_disconnect)
self.connected = False
self._last_update_time = NEVER_TIME
self._debounce_cancel: CALLBACK_TYPE | None = None
self._debounced_update_job = HassJob(
self._async_handle_debounced_update,
f"LD2450 {ld2450_ble.address} BLE debounced update",
)
@callback
def _async_handle_debounced_update(self, _now: datetime) -> None:
"""Handle debounced update."""
self._debounce_cancel = None
self._last_update_time = time.monotonic()
self.async_set_updated_data(None)
@callback
def _async_handle_update(self, state: [LD2450BLEState, LD2450BLEConfig]) -> None:
"""Just trigger the callbacks."""
self.connected = True
previous_last_updated_time = self._last_update_time
self._last_update_time = time.monotonic()
if self._last_update_time - previous_last_updated_time >= DEBOUNCE_SECONDS:
self.async_set_updated_data(None)
return
if self._debounce_cancel is None:
self._debounce_cancel = async_call_later(
self.hass, DEBOUNCE_SECONDS, self._debounced_update_job
)
@callback
def _async_handle_disconnect(self) -> None:
"""Trigger the callbacks for disconnected."""
self.connected = False
self.async_update_listeners()
async def async_shutdown(self) -> None:
"""Shutdown the coordinator."""
if self._debounce_cancel is not None:
self._debounce_cancel()
self._debounce_cancel = None
await super().async_shutdown()