summaryrefslogtreecommitdiff
path: root/kvmd/plugins/ugpio/unifi.py
blob: c4d572e9098a226ea70f8e26e3b30ca887366aa9 (plain)
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# ========================================================================== #
#                                                                            #
#    KVMD - The main PiKVM daemon.                                           #
#                                                                            #
#    Copyright (C) 2018-2023  Maxim Devaev <[email protected]>               #
#                                                                            #
#    This program is free software: you can redistribute it and/or modify    #
#    it under the terms of the GNU General Public License as published by    #
#    the Free Software Foundation, either version 3 of the License, or       #
#    (at your option) any later version.                                     #
#                                                                            #
#    This program is distributed in the hope that it will be useful,         #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#    GNU General Public License for more details.                            #
#                                                                            #
#    You should have received a copy of the GNU General Public License       #
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.  #
#                                                                            #
# ========================================================================== #


import asyncio
import functools
import json

from typing import Callable
from typing import Any

from multidict import CIMultiDict, CIMultiDictProxy

import aiohttp

from ...logging import get_logger

from ... import tools
from ... import aiotools
from ... import htclient

from ...yamlconf import Option

from ...validators.basic import valid_stripped_string_not_empty
from ...validators.basic import valid_bool
from ...validators.basic import valid_float_f01

from . import BaseUserGpioDriver
from . import GpioDriverOfflineError


# =====

def set_poe_mode(pin: str, state: bool, port_override: dict[str, Any]) -> dict[str, Any]:
    port_idx = str(port_override["port_idx"])
    if port_idx == pin:
        port_override["poe_mode"] = "auto" if state else "off"
    return port_override


# pylint: disable=too-many-instance-attributes disable=too-many-arguments
class Plugin(BaseUserGpioDriver):
    def __init__(
        self,
        instance_name: str,
        notifier: aiotools.AioNotifier,

        url: str,
        verify: bool,
        user: str,
        passwd: str,
        mac: str,

        timeout: float,
        switch_delay: float,
        state_poll: float,
    ) -> None:

        super().__init__(instance_name, notifier)

        self.__url = url
        self.__user = user
        self.__passwd = passwd
        self.__mac = mac
        self.__state_poll = state_poll

        self.__switch_delay = switch_delay

        self.__initial: dict[str, (bool | None)] = {}

        self.__state: dict[str, (bool | None)] = {}

        self.__port_table: dict[str, dict[str, Any]] = {}
        self.__port_overrides: dict[str, dict[str, Any]] = {}

        self.__update_notifier = aiotools.AioNotifier()

        self.__http_session: aiohttp.ClientSession = self.__get_client_session(timeout, verify)

        self.__csrf_token: (str | None) = None
        self.__id: (str | None) = None
        self.__api_url: str = f"{self.__url}/proxy/network/api/s/default"

    @classmethod
    def get_plugin_options(cls) -> dict[str, Option]:
        return {
            "url":        Option("",   type=valid_stripped_string_not_empty),
            "verify":     Option(True, type=valid_bool),
            "user":       Option(""),
            "passwd":     Option(""),
            "mac":        Option("",   type=valid_stripped_string_not_empty),
            "state_poll": Option(5.0,  type=valid_float_f01),
            "timeout":    Option(5.0,  type=valid_float_f01),
            "switch_delay": Option(1.0,  type=valid_float_f01),
        }

    @classmethod
    def get_pin_validator(cls) -> Callable[[Any], Any]:
        return valid_stripped_string_not_empty

    def register_input(self, pin: str, debounce: float) -> None:
        _ = debounce
        self.__state[pin] = None

    def register_output(self, pin: str, initial: (bool | None)) -> None:
        if pin.isnumeric():
            self.__initial[pin] = initial
            self.__state[pin] = None

    def prepare(self) -> None:
        for (pin, state) in self.__initial.items():
            if pin.isnumeric():
                if state is not None:
                    self.__state[pin] = state

    async def run(self) -> None:
        prev_state: (dict | None) = None
        while True:
            try:
                if self.__csrf_token is None:
                    get_logger().info(
                        "Logging into UNIFI"
                    )
                    await self.login()
                async with self.__http_session.get(
                    url=f"{self.__api_url}/stat/device/{self.__mac}",
                    headers=self.__get_headers()
                ) as response:
                    htclient.raise_not_200(response)
                    self.__handle_headers(response.headers)

                    status = (await response.json())["data"][0]
                    if self.__id is None or self.__id != status["_id"]:
                        self.__id = status["_id"]

                    port_overrides = dict(map(
                        lambda port: (str(port["port_idx"]), port),
                        status["port_overrides"]))

                    for port_key, port in port_overrides.items():
                        self.__port_overrides[port_key] = port

                    port_table = dict(
                        map(lambda port: (str(port["port_idx"]), port),
                            list(filter(lambda p: p["port_poe"] is True,
                                        status["port_table"]))))

                    for port_key, port in port_table.items():
                        self.__port_table[port_key] = port

                    for pin in self.__state:
                        if pin is not None:
                            port = self.__port_table[pin]
                            self.__state[pin] = port["poe_mode"] == "auto"

            except aiohttp.ClientResponseError as err:
                await self.__handle_client_response_error(err)
            except Exception as err:
                get_logger().error("Failed UNIFI bulk GET request: %s",
                                   tools.efmt(err))
                self.__state = dict.fromkeys(self.__state, None)

            if self.__state != prev_state:
                self._notifier.notify()
                prev_state = self.__state

            await self.__update_notifier.wait(self.__state_poll)

    async def cleanup(self) -> None:
        if self.__http_session:
            await self.__http_session.close()
            self.__http_session = aiohttp.ClientSession()
            self.__csrf_token = None

    async def read(self, pin: str) -> bool:
        if pin.isnumeric() is False:
            return False
        try:
            if self.__csrf_token is None:
                get_logger().info(
                    "Logging into UNIFI"
                )
                await self.login()
            return await self.__inner_read(pin)
        except aiohttp.ClientResponseError as err:
            await self.__handle_client_response_error(err)
        except Exception:
            raise GpioDriverOfflineError(self)
        return False

    async def write(self, pin: str, state: bool) -> None:
        try:
            if self.__csrf_token is None:
                get_logger().info(
                    "Logging into UNIFI"
                )
                await self.login()
            if pin.endswith(":cycle"):
                await self.__cycle_device(pin, state)
            else:
                await self.__inner_write(pin, state)
        except aiohttp.ClientResponseError as err:
            await self.__handle_client_response_error(err)
        except Exception as err:
            get_logger().error(
                "Failed UNIFI PUT request | pin : %s | Error: %s",
                pin,
                tools.efmt(err)
            )
        await asyncio.sleep(self.__switch_delay)  # Slowdown
        self.__update_notifier.notify()

    # =====

    def __get_client_session(self, timeout: float, verify: bool) -> aiohttp.ClientSession:
        kwargs: dict = {
            "headers": {
                "Accept": "application/json",
                "User-Agent": htclient.make_user_agent("KVMD"),
            },
            "timeout": aiohttp.ClientTimeout(total=timeout),
            "connector": aiohttp.TCPConnector(verify_ssl=verify),
            "cookie_jar": aiohttp.CookieJar(),
        }

        return aiohttp.ClientSession(**kwargs)

    async def __inner_read(self, pin: str) -> bool:
        return self.__state[pin] is not None and bool(self.__state[pin])

    async def __inner_write(self, pin: str, state: bool) -> None:
        await self.__set_device(pin, state)

    async def __cycle_device(self, pin: str, state: bool) -> None:
        if state is False:
            return
        get_logger().info("Cycling device %s: port: %s", self.__mac, pin)
        async with self.__http_session.post(
            url=f"{self.__api_url}/cmd/devmgr",
            json={
                "cmd": "power-cycle",
                "mac": self.__mac,
                "port_idx": pin.split(":")[0],
            },
            headers=self.__get_headers()
        ) as response:
            self.__handle_headers(response.headers)
            htclient.raise_not_200(response)

    async def __set_device(self, pin: str, state: bool) -> None:
        get_logger().info("Setting device %s: port: %s, state: %s", self.__mac, pin, state)

        port_overrides = map(
            functools.partial(set_poe_mode, pin, state),
            self.__port_overrides.values()
        )

        data = {
            "port_overrides": list(port_overrides)
        }

        get_logger().info("Posting content %s:\n%s\n", pin, json.dumps(data).encode("utf-8"))

        async with self.__http_session.put(
            url=f"{self.__api_url}/rest/device/{self.__id}",
            json=data,
            headers={
                "Accept": "application/json",
                "Content-Type": "application/json;charset=UTF-8",
                "X-CSRF-TOKEN": self.__csrf_token,
                "User-Agent": htclient.make_user_agent("KVMD"),
            }
        ) as response:
            htclient.raise_not_200(response)

            for header in response.headers:
                if header.upper() == "X-CSRF-TOKEN":
                    self.__csrf_token = response.headers[header]

            if response.cookies:
                self.__http_session.cookie_jar.update_cookies(
                    response.cookies
                )

        result = await asyncio.sleep(5, result=state)

        self.__port_table[pin]["poe_enable"] = result
        self.__port_table[pin]["poe_mode"] = "auto" if result else "off"
        self.__state[pin] = result

    def __get_headers(self,
                      extra: (dict | None) = None
                      ) -> CIMultiDictProxy[str]:
        kwargs: dict = {
            "Accept": "application/json",
            "X-CSRF-TOKEN": self.__csrf_token,
        }
        headers: CIMultiDict[str] = CIMultiDict(**kwargs)
        if extra is not None:
            headers.update(**extra)
        return CIMultiDictProxy(headers)

    def __handle_headers(self, response_headers: CIMultiDictProxy[str]) -> None:
        for header in response_headers:
            if header.upper() == "X-CSRF-TOKEN":
                self.__csrf_token = response_headers.get(header)

    async def __handle_client_response_error(self,
                                             err: aiohttp.ClientResponseError
                                             ) -> None:
        if err.status == 401:
            get_logger().info(
                "UNIFI API request unauthorized. Attempting to refresh session"
            )
            try:
                await self.login()
            except Exception as login_err:
                get_logger().error("Failed UNIFI login request: %s",
                                   tools.efmt(login_err))

    async def login(self) -> None:
        try:
            response = await self.__http_session.post(
                url=f"{self.__url}/api/auth/login",
                json={
                    "username": self.__user,
                    "password": self.__passwd
                },
                headers={
                    "Accept": "application/json",
                    "User-Agent": htclient.make_user_agent("KVMD"),
                    "Content-Type": "application/json;charset=UTF-8",
                }
            )

            htclient.raise_not_200(response)

            for header in response.headers:
                if header.upper() == "X-CSRF-TOKEN":
                    self.__csrf_token = response.headers[header]

            if response.cookies:
                self.__http_session.cookie_jar.update_cookies(
                    response.cookies
                )
        except Exception as err:
            get_logger().error(
                "Failed UNIFI login request: %s",
                tools.efmt(err)
            )

    def __str__(self) -> str:
        return f"UNIFI({self._instance_name})"

    __repr__ = __str__