File: websockets.py

package info (click to toggle)
python-aioairzone-cloud 0.6.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 396 kB
  • sloc: python: 3,600; makefile: 4
file content (263 lines) | stat: -rw-r--r-- 8,581 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
"""Airzone Cloud API."""

from __future__ import annotations

import asyncio
from asyncio import Event, Lock, Task
from datetime import datetime
from json import JSONDecodeError, loads as json_loads
import logging
from typing import TYPE_CHECKING, Any
import urllib.parse

from aiohttp import ClientSession, ClientWebSocketResponse, WSMessage, WSMsgType

from .const import (
    API_DEVICE_ID,
    API_V1,
    API_WS_ID,
    WS_ALIVE_PERIOD,
    WS_AUTH,
    WS_BODY,
    WS_CORR_ID,
    WS_DEVICE_STATE,
    WS_DEVICE_STATE_END,
    WS_DEVICES_UPDATES,
    WS_EVENT,
    WS_INSTALLATION,
    WS_INSTALLATION_ID,
    WS_URL,
    WS_WEBSERVER_UPDATES,
    WS_WEBSOCKETS,
)
from .device import Device
from .entity import EntityUpdate, UpdateType
from .installation import Installation
from .token import AirzoneCloudToken

if TYPE_CHECKING:
    from .cloudapi import AirzoneCloudApi

_LOGGER = logging.getLogger(__name__)


class AirzoneCloudIWS:
    """Airzone Cloud Installation WebSockets."""

    def __init__(
        self,
        cloudapi: AirzoneCloudApi,
        installation: Installation,
    ):
        """Airzone Cloud WebSockets init."""
        self.alive_dt: datetime | None = None
        self.cloudapi: AirzoneCloudApi = cloudapi
        self.device_data_lock = Lock()
        self.device_data: dict[str, Any] = {}
        self.inst_id: str = installation.get_id()
        self.session: ClientSession = cloudapi.session or ClientSession()
        self.state_end: Event = Event()
        self.task: Task[None] | None = None
        self.token: AirzoneCloudToken = cloudapi.token

    async def _connect(self) -> None:
        """WebSockets connection."""
        params = {
            WS_INSTALLATION_ID: self.inst_id,
        }
        inst_params = urllib.parse.urlencode(params)
        url = f"{WS_URL}/{API_V1}/{WS_WEBSOCKETS}/{WS_INSTALLATION}?{inst_params}"

        await self.state_init()

        async with self.session.ws_connect(
            url,
            headers=self.token.headers(),
            autoclose=False,
            autoping=False,
        ) as ws:
            async for msg in ws:
                await self.handler(ws, msg)

    def connect(self) -> bool:
        """WebSockets task creation."""
        if self.task is not None:
            return self.is_connected()

        self.state_end.clear()
        self.task = asyncio.ensure_future(self._connect())

        return True

    def disconnect(self) -> bool:
        """WebSockets task deletion."""
        self.state_end.clear()

        task = self.task
        if task is None:
            return True

        res = task.cancel()
        self.task = None

        return res

    def reconnect(self) -> bool:
        """WebSockets reconnect."""
        _LOGGER.warning("WS[%s]: reconnecting...", self.inst_id)
        self.disconnect()
        return self.connect()

    def get_device_data(self, device: Device) -> dict[str, Any] | None:
        """Return WebSockets device data."""
        return self.device_data.get(device.get_id())

    async def handler_auth(
        self, ws: ClientWebSocketResponse, data: dict[str, Any]
    ) -> None:
        """WebSockets AUTH handler."""
        corr_id = data.get(WS_CORR_ID)
        if corr_id is not None:
            auth = {
                WS_CORR_ID: corr_id,
                WS_BODY: self.token.jwt(),
            }
            _LOGGER.debug("WS[%s]: AUTH[%s]", self.inst_id, corr_id)
            await ws.send_json(auth)
        else:
            _LOGGER.error("WS[%s]: AUTH error -> %s", self.inst_id, data)

    async def handler_close(self, ws: ClientWebSocketResponse) -> None:
        """WebSockets CLOSE handler."""
        _LOGGER.debug("WS[%s]: CLOSE", self.inst_id)
        await ws.close()

    async def handler_device_state(self, data: dict[str, Any]) -> None:
        """WebSockets DEVICE_STATE handler."""
        body: dict[str, Any] = data.get(WS_BODY, {})
        update = EntityUpdate(UpdateType.WS_FULL, body)
        dev_id: str | None = body.get(API_DEVICE_ID)

        _LOGGER.debug("WS[%s]: DEVICE_STATE[%s]", self.inst_id, dev_id)

        device = self.cloudapi.get_device_id(dev_id)
        if device is not None:
            async with self.device_data_lock:
                self.device_data[device.get_id()] = body

            await device.update(update)

    def handler_device_state_end(self, data: dict[str, Any]) -> None:
        """WebSockets DEVICE_STATE_END handler."""
        body: str | None = data.get(WS_BODY)

        if body == self.inst_id:
            _LOGGER.debug("WS[%s]: DEVICE_STATE_END", self.inst_id)
            self.state_end.set()
        else:
            _LOGGER.error("WS[%s]: DEVICE_STATE_END mismatch (%s)", self.inst_id, body)

    async def handler_devices_update(self, data: dict[str, Any]) -> None:
        """WebSockets DEVICES_UPDATES handler."""
        body: dict[str, Any] = data.get(WS_BODY, {})
        update = EntityUpdate(UpdateType.WS_PARTIAL, body)
        dev_id: str | None = body.get(API_DEVICE_ID)

        _LOGGER.debug("WS[%s]: DEVICES_UPDATES[%s]", self.inst_id, dev_id)

        device = self.cloudapi.get_device_id(dev_id)
        if device is not None:
            await device.update(update)

    async def handler_error(self, msg: WSMessage) -> None:
        """WebSockets ERROR handler."""
        _LOGGER.error("WS[%s]: ERROR -> %s", self.inst_id, msg)

    async def handler_ping(self, ws: ClientWebSocketResponse) -> None:
        """WebSockets PING handler."""
        _LOGGER.debug("WS[%s]: PING (%s)", self.inst_id, datetime.now())
        await ws.pong()

    async def handler_text(
        self, ws: ClientWebSocketResponse, data: dict[str, Any]
    ) -> None:
        """WebSockets TEXT handler."""
        event: str = data.get(WS_EVENT, "")
        if event == WS_AUTH:
            await self.handler_auth(ws, data)
        elif event == WS_DEVICE_STATE:
            await self.handler_device_state(data)
        elif event == WS_DEVICE_STATE_END:
            self.handler_device_state_end(data)
        elif event.startswith(WS_DEVICES_UPDATES):
            await self.handler_devices_update(data)
            self.cloudapi.update_callback()
        elif event.startswith(WS_WEBSERVER_UPDATES):
            await self.handler_webserver_updates(data)
            self.cloudapi.update_callback()
        else:
            _LOGGER.warning("WS[%s]: EVENT[%s] -> %s", self.inst_id, event, data)

    async def handler_webserver_updates(self, data: dict[str, Any]) -> None:
        """WebSockets WEBSERVER_UPDATES handler."""
        body: dict[str, Any] = data.get(WS_BODY, {})
        update = EntityUpdate(UpdateType.WS_PARTIAL, body)
        ws_id: str | None = body.get(API_WS_ID)

        _LOGGER.debug("WS[%s]: WEBSERVER_UPDATES[%s]", self.inst_id, ws_id)

        webserver = self.cloudapi.get_webserver_id(ws_id)
        if webserver is not None:
            await webserver.update(update)

    async def handler(self, ws: ClientWebSocketResponse, msg: WSMessage) -> None:
        """WebSockets message handler."""
        if msg.type == WSMsgType.TEXT:
            json_data = None
            try:
                json_data = json_loads(msg.data)
            except (JSONDecodeError, TypeError) as err:
                _LOGGER.error(err)

            if json_data is not None:
                self.set_alive()
                await self.handler_text(ws, json_data)
        elif msg.type == WSMsgType.PING:
            self.set_alive()
            await self.handler_ping(ws)
        elif msg.type == WSMsgType.CLOSE:
            await self.handler_close(ws)
        elif msg.type == WSMsgType.ERROR:
            await self.handler_error(msg)
        else:
            _LOGGER.warning("Unknown WS msg: %s", msg)

    def is_alive(self) -> bool:
        """WebSockets connection alive."""
        return (
            self.alive_dt is not None
            and (datetime.now() - self.alive_dt) <= WS_ALIVE_PERIOD
        )

    def is_connected(self) -> bool:
        """WebSockets connection status."""
        task = self.task

        if task is None:
            return False

        return not task.done()

    def set_alive(self) -> None:
        """WebSockets alive status update."""
        self.alive_dt = datetime.now()

    async def state_init(self) -> None:
        """WebSockets state init."""
        _LOGGER.debug("WS[%s]: DEVICE_STATE_INIT", self.inst_id)

        async with self.device_data_lock:
            self.device_data.clear()

        self.alive_dt = None
        self.state_end.clear()