File: state_updater.py

package info (click to toggle)
python-xknx 3.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,064 kB
  • sloc: python: 40,895; javascript: 8,556; makefile: 32; sh: 12
file content (282 lines) | stat: -rw-r--r-- 10,235 bytes parent folder | download
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""Module for keeping the value of a RemoteValue from KNX bus up to date."""

from __future__ import annotations

import asyncio
from collections.abc import Awaitable, Callable
from enum import Enum
import logging
from typing import TYPE_CHECKING, Any, NamedTuple

from xknx.core import XknxConnectionState
from xknx.remote_value import RemoteValue

if TYPE_CHECKING:
    from xknx.xknx import XKNX


logger = logging.getLogger("xknx.state_updater")

DEFAULT_UPDATE_INTERVAL = 60
MAX_UPDATE_INTERVAL = 1440


class TrackerOptions(NamedTuple):
    """Options for the state tracker."""

    tracker_type: StateTrackerType
    update_interval_min: int | float


TrackerOptionType = bool | int | float | str | TrackerOptions


class StateUpdater:
    """Class for keeping the states of RemoteValues up to date."""

    __slots__ = (
        "_default_tracker_option",
        "_semaphore",
        "_workers",
        "default_use_updater",
        "started",
        "xknx",
    )

    def __init__(
        self,
        xknx: XKNX,
        default_tracker_option: TrackerOptionType,
        parallel_reads: int = 2,
    ) -> None:
        """Initialize StateUpdater class."""
        self.xknx = xknx
        self.started = False
        self._workers: dict[int, _StateTracker] = {}
        self._semaphore = asyncio.Semaphore(value=parallel_reads)

        # used to determine if a RemoteValue shall register a tracker by default
        self.default_use_updater = bool(default_tracker_option)
        # set default before using it in `parse_tracker_options()`
        self._default_tracker_option = TrackerOptions(
            tracker_type=StateTrackerType.EXPIRE,
            update_interval_min=DEFAULT_UPDATE_INTERVAL,
        )
        #  Default options will be used if instantiated with `True` or `False`.
        self._default_tracker_option = self.parse_tracker_options(
            default_tracker_option, "default configuration"
        )

    def parse_tracker_options(
        self,
        tracker_options: TrackerOptionType,
        tracker_name: str,
    ) -> TrackerOptions:
        """Parse tracker type and expiration time."""

        def check_update_interval(update_interval: int | float) -> int | float:
            """Return valid update interval."""
            if update_interval > MAX_UPDATE_INTERVAL:
                logger.warning(
                    "StateUpdater interval of %s to long for %s. Using maximum of %s minutes (1 day)",
                    tracker_options,
                    tracker_name,
                    MAX_UPDATE_INTERVAL,
                )
                return MAX_UPDATE_INTERVAL
            if update_interval < 1:
                logger.warning(
                    "StateUpdater interval of %s to short for %s. Using minimum of 1 minute",
                    tracker_options,
                    tracker_name,
                )
                return 1
            return update_interval

        if isinstance(tracker_options, TrackerOptions):
            return TrackerOptions(
                tracker_type=tracker_options.tracker_type,
                update_interval_min=check_update_interval(
                    tracker_options.update_interval_min
                ),
            )
        if isinstance(tracker_options, bool):
            # `True` would be overwritten by the check for `int`
            return self._default_tracker_option

        tracker_type = self._default_tracker_option.tracker_type
        update_interval: int | float = self._default_tracker_option.update_interval_min

        if isinstance(tracker_options, int | float):
            update_interval = check_update_interval(tracker_options)
        elif isinstance(tracker_options, str):
            _options = tracker_options.split()
            if _options[0].upper() == "INIT":
                tracker_type = StateTrackerType.INIT
            elif _options[0].upper() == "EXPIRE":
                tracker_type = StateTrackerType.EXPIRE
            elif _options[0].upper() == "EVERY":
                tracker_type = StateTrackerType.PERIODICALLY
            else:
                logger.warning(
                    'Could not parse StateUpdater tracker_options "%s" for %s. Using default %s %s minutes.',
                    tracker_options,
                    tracker_name,
                    tracker_type,
                    update_interval,
                )
                return TrackerOptions(tracker_type, update_interval)
            try:
                if _options[1].isdigit():
                    update_interval = check_update_interval(int(_options[1]))
            except IndexError:
                pass  # No time given (no _options[1])

        return TrackerOptions(tracker_type, update_interval)

    def register_remote_value(
        self,
        remote_value: RemoteValue[Any],
        tracker_options: TrackerOptionType = True,
    ) -> None:
        """Register a RemoteValue to initialize its state and/or track for expiration."""

        async def read_state_mutex() -> None:
            """Schedule to read the state from the KNX bus - one at a time."""
            async with self._semaphore:
                # wait until there is nothing else to send to the bus
                await self.xknx.telegram_queue.outgoing_queue.join()
                logger.debug(
                    "StateUpdater reading %s for %s - %s",
                    remote_value.group_address_state,
                    remote_value.device_name,
                    remote_value.feature_name,
                )
                # shield from cancellation so update_received() don't cancel the
                # ValueReader leaving the telegram_received_cb until next telegram
                await asyncio.shield(remote_value.read_state(wait_for_result=True))

        tracker_options = self.parse_tracker_options(tracker_options, str(remote_value))
        tracker = _StateTracker(
            read_state_awaitable=read_state_mutex,
            tracker_options=tracker_options,
        )
        self._workers[id(remote_value)] = tracker

        logger.debug(
            "StateUpdater registered %s %s for %s",
            tracker_options.tracker_type,
            tracker_options.update_interval_min,
            remote_value,
        )
        if self.started:
            tracker.start()

    def unregister_remote_value(self, remote_value: RemoteValue[Any]) -> None:
        """Unregister a RemoteValue from StateUpdater."""
        self._workers.pop(id(remote_value)).stop()

    def update_received(self, remote_value: RemoteValue[Any]) -> None:
        """Reset the timer when a state update was received."""
        if self.started and id(remote_value) in self._workers:
            self._workers[id(remote_value)].update_received()

    def _start(self) -> None:
        """Start internal StateUpdater. Initialize states."""
        logger.debug("StateUpdater initializing values")
        self.started = True
        for worker in self._workers.values():
            worker.start()

    def _stop(self) -> None:
        """Stop internal StateUpdater."""
        logger.debug("StateUpdater stopping")
        self.started = False
        for worker in self._workers.values():
            worker.stop()

    def start(self) -> None:
        """Start StateUpdater."""
        self.xknx.connection_manager.register_connection_state_changed_cb(
            self.connection_state_change_callback
        )

        if self.xknx.connection_manager.state == XknxConnectionState.CONNECTED:
            self._start()

    def stop(self) -> None:
        """Stop StateUpdater."""
        self.xknx.connection_manager.unregister_connection_state_changed_cb(
            self.connection_state_change_callback
        )

        self._stop()

    def connection_state_change_callback(self, state: XknxConnectionState) -> None:
        """Start and stop StateUpdater via connection state update."""
        if state == XknxConnectionState.CONNECTED:
            if not self.started:
                self._start()
        elif self.started:
            self._stop()


class StateTrackerType(Enum):
    """Enum indicating the StateUpdater Type."""

    INIT = 1
    EXPIRE = 2
    PERIODICALLY = 3


class _StateTracker:
    """Keeps track of the age of the state from one RemoteValue."""

    __slots__ = ("_read_state", "_task", "tracker_type", "update_interval")

    def __init__(
        self,
        read_state_awaitable: Callable[[], Awaitable[None]],
        tracker_options: TrackerOptions,
    ) -> None:
        """Initialize StateTracker class."""
        self.tracker_type = tracker_options.tracker_type
        self.update_interval = tracker_options.update_interval_min * 60
        self._read_state = read_state_awaitable
        self._task: asyncio.Task[None] | None = None

    def start(self) -> None:
        """Start StateTracker - read state on call."""
        self.stop()
        self._task = asyncio.create_task(self._start_init())

    async def _start_init(self) -> None:
        """Initialize state, start update loop if appropriate."""
        await self._read_state()
        if self.tracker_type is not StateTrackerType.INIT:
            self.reset()

    def reset(self) -> None:
        """Start / Restart StateTracker timer - wait for value to expire."""
        self.stop()
        self._task = asyncio.create_task(self._update_loop())

    def stop(self) -> None:
        """Stop StateTracker."""
        if self._task:
            self._task.cancel()
            self._task = None

    def update_received(self) -> None:
        """Reset the timer if a telegram was received for a "expire" typed StateUpdater."""
        if self.tracker_type == StateTrackerType.EXPIRE:
            self.reset()

    async def _update_loop(self) -> None:
        """Wait for the update_interval to expire. Endless loop for updating states."""
        # for StateUpdaterType.EXPIRE:
        #   on successful read the while loop gets canceled when the callback calls update_received()
        #   when no telegram was received it will try again endlessly
        while True:
            await asyncio.sleep(self.update_interval)
            await self._read_state()