File: websocket.py

package info (click to toggle)
python-aioambient 2024.1.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 472 kB
  • sloc: python: 755; sh: 41; makefile: 5
file content (245 lines) | stat: -rw-r--r-- 7,867 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
"""Define an object to interact with the Websocket API."""
from __future__ import annotations

import asyncio
import logging
from collections.abc import Awaitable, Callable
from typing import Any

from aiohttp.client_exceptions import ClientConnectionError
from socketio import AsyncClient
from socketio.exceptions import SocketIOError

from .const import DEFAULT_API_VERSION, LOGGER
from .errors import WebsocketError

DEFAULT_WATCHDOG_TIMEOUT = 900

WEBSOCKET_API_BASE = "https://rt2.ambientweather.net"


class WebsocketWatchdog:
    """Define a watchdog to kick the websocket connection at intervals."""

    def __init__(
        self,
        logger: logging.Logger,
        action: Callable[..., Awaitable],
        *,
        timeout_seconds: int = DEFAULT_WATCHDOG_TIMEOUT,
    ):
        """Initialize.

        Args:
            logger: The logger to use.
            action: The coroutine function to call when the watchdog expires.
            timeout_seconds: The number of seconds before the watchdog times out.
        """
        self._action = action
        self._logger = logger
        self._loop = asyncio.get_event_loop()
        self._timeout = timeout_seconds
        self._timer_task: asyncio.TimerHandle | None = None

    def cancel(self) -> None:
        """Cancel the watchdog."""
        if self._timer_task:
            self._timer_task.cancel()
            self._timer_task = None

    async def on_expire(self) -> None:
        """Log and act when the watchdog expires."""
        self._logger.info("Watchdog expired - calling %s", self._action.__name__)
        await self._action()

    async def trigger(self) -> None:
        """Trigger the watchdog."""
        self._logger.info("Watchdog triggered - sleeping for %s seconds", self._timeout)

        if self._timer_task:
            self._timer_task.cancel()

        self._timer_task = self._loop.call_later(
            self._timeout, lambda: asyncio.create_task(self.on_expire())
        )


class Websocket:  # pylint: disable=too-many-instance-attributes
    """Define the websocket."""

    def __init__(
        self,
        application_key: str,
        api_key: str | list[str],
        *,
        api_version: int = DEFAULT_API_VERSION,
        logger: logging.Logger = LOGGER,
    ) -> None:
        """Initialize.

        Args:
            application_key: An Ambient Weather application key.
            api_key: An Ambient Weather API key.
            api_version: The version of the API to query.
            logger: The logger to use.
        """
        if isinstance(api_key, str):
            api_key = [api_key]

        self._api_key = api_key
        self._api_version = api_version
        self._app_key = application_key
        self._async_user_connect_handler: Callable[..., Awaitable[None]] | None = None
        self._logger = logger
        self._sio = AsyncClient(logger=logger, engineio_logger=logger)
        self._user_connect_handler: Callable[..., None] | None = None
        self._watchdog = WebsocketWatchdog(logger, self.reconnect)

    async def _init_connection(self) -> None:
        """Perform automatic initialization upon connecting."""
        await self._sio.emit("subscribe", {"apiKeys": self._api_key})
        await self._watchdog.trigger()

        if self._async_user_connect_handler:
            await self._async_user_connect_handler()
        elif self._user_connect_handler:
            self._user_connect_handler()

    def async_on_connect(self, target: Callable[..., Awaitable[None]]) -> None:
        """Define a coroutine to be called when connecting.

        Args:
            target: The coroutine function to call upon websocket connect.
        """
        self._async_user_connect_handler = target
        self._user_connect_handler = None

    def on_connect(self, target: Callable[..., None]) -> None:
        """Define a method to be called when connecting.

        Args:
            target: The function to call upon websocket connect.
        """
        self._async_user_connect_handler = None
        self._user_connect_handler = target

    def async_on_data(
        self, target: Callable[[dict[str, Any]], Awaitable[None]]
    ) -> None:
        """Define a coroutine to be called when data is received.

        Args:
            target: The coroutine function to call when receiving websocket data.
        """

        async def _async_on_data(data: dict[str, Any]) -> None:
            """Act on the data.

            Args:
                data: The websocket data received.
            """
            await self._watchdog.trigger()
            await target(data)

        self._sio.on("data", _async_on_data)

    def on_data(self, target: Callable[[dict[str, Any]], None]) -> None:
        """Define a method to be called when data is received.

        Args:
            target: The function to call when receiving websocket data.
        """

        async def _async_on_data(data: dict[str, Any]) -> None:
            """Act on the data.

            Args:
                data: The websocket data received.
            """
            await self._watchdog.trigger()
            target(data)

        self._sio.on("data", _async_on_data)

    def async_on_disconnect(self, target: Callable[..., Awaitable[None]]) -> None:
        """Define a coroutine to be called when disconnecting.

        Args:
            target: The coroutine function to call upon websocket connect.
        """
        self._sio.on("disconnect", target)

    def on_disconnect(self, target: Callable[..., None]) -> None:
        """Define a method to be called when disconnecting.

        Args:
            target: The function to call upon websocket connect.
        """
        self._sio.on("disconnect", target)

    def async_on_subscribed(
        self, target: Callable[[dict[str, Any]], Awaitable[None]]
    ) -> None:
        """Define a coroutine to be called when subscribed.

        Args:
            target: The coroutine function to call when receiving websocket data.
        """

        async def _async_on_subscribed(data: dict[str, Any]) -> None:
            """Act on subscribe.

            Args:
                data: The websocket data received.
            """
            await self._watchdog.trigger()
            await target(data)

        self._sio.on("subscribed", _async_on_subscribed)

    def on_subscribed(self, target: Callable[[dict[str, Any]], None]) -> None:
        """Define a method to be called when subscribed.

        Args:
            target: The function to call when receiving websocket data.
        """

        async def _async_on_subscribed(data: dict[str, Any]) -> None:
            """Act on subscribe.

            Args:
                data: The websocket data received.
            """
            await self._watchdog.trigger()
            target(data)

        self._sio.on("subscribed", _async_on_subscribed)

    async def connect(self) -> None:
        """Connect to the socket.

        Raises:
            WebsocketError: Raised upon any issue with the websocket.
        """
        try:
            self._sio.on("connect", self._init_connection)
            await self._sio.connect(
                (
                    f"{WEBSOCKET_API_BASE}/?api={self._api_version}"
                    f"&applicationKey={self._app_key}"
                ),
                transports=["websocket"],
            )
        except (ClientConnectionError, SocketIOError) as err:
            raise WebsocketError(err) from err

    async def disconnect(self) -> None:
        """Disconnect from the socket."""
        await self._sio.disconnect()
        self._watchdog.cancel()

    async def reconnect(self) -> None:
        """Reconnect the websocket connection."""
        await self.disconnect()
        await asyncio.sleep(1)
        await self.connect()