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
|
# ========================================================================== #
# #
# 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
from typing import Callable
from typing import Any
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
# =====
class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attributes
def __init__( # pylint: disable=too-many-arguments
self,
instance_name: str,
notifier: aiotools.AioNotifier,
url: str,
verify: bool,
user: str,
passwd: str,
mac: str,
switch_delay: float,
timeout: float,
state_poll: float,
) -> None:
super().__init__(instance_name, notifier)
self.__url = url
self.__verify = verify
self.__user = user
self.__passwd = passwd
self.__mac = mac
self.__switch_delay = switch_delay
self.__timeout = timeout
self.__state_poll = state_poll
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 | None) = None
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),
"switch_delay": Option(1.0, type=valid_float_f01),
"state_poll": Option(5.0, type=valid_float_f01),
"timeout": Option(5.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:
_ = initial
if pin.isnumeric():
self.__state[pin] = None
async def run(self) -> None:
prev_state: (dict | None) = None
while True:
if (await self.__ensure_login()):
try:
async with self.__ensure_http_session().get(
url=f"{self.__api_url}/stat/device/{self.__mac}",
headers=self.__make_headers(token=True, post_json=False),
) as response:
self.__handle_response(response)
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 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 = None
self.__csrf_token = None
async def read(self, pin: str) -> bool:
if not pin.isnumeric():
return False
if not (await self.__ensure_login()):
raise GpioDriverOfflineError(self)
return self.__state[pin] is not None and bool(self.__state[pin])
async def write(self, pin: str, state: bool) -> None:
if not (await self.__ensure_login()):
raise GpioDriverOfflineError(self)
try:
if pin.endswith(":cycle"):
await self.__cycle_device(pin, state)
else:
await self.__set_device(pin, state)
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()
# =====
async def __cycle_device(self, pin: str, state: bool) -> None:
if not state:
return
get_logger().info("Cycling device %s: port: %s", self.__mac, pin)
async with self.__ensure_http_session().post(
url=f"{self.__api_url}/cmd/devmgr",
json={
"cmd": "power-cycle",
"mac": self.__mac,
"port_idx": pin.split(":")[0],
},
headers=self.__make_headers(token=True, post_json=True),
) as response:
self.__handle_response(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: list[dict[str, Any]] = []
for po in self.__port_overrides.values():
if str(po["port_idx"]) == pin:
# Also modifies value in self.__port_overrides
po["poe_mode"] = ("auto" if state else "off")
port_overrides.append(po)
async with self.__ensure_http_session().put(
url=f"{self.__api_url}/rest/device/{self.__id}",
json={"port_overrides": port_overrides},
headers=self.__make_headers(token=True, post_json=True),
) as response:
self.__handle_response(response)
await asyncio.sleep(5)
self.__port_table[pin]["poe_enable"] = state
self.__port_table[pin]["poe_mode"] = ("auto" if state else "off")
self.__state[pin] = state
async def __ensure_login(self) -> bool:
if self.__csrf_token is None:
get_logger().info("Logging into Unifi")
try:
async with self.__ensure_http_session().post(
url=f"{self.__url}/api/auth/login",
json={
"username": self.__user,
"password": self.__passwd,
},
headers=self.__make_headers(token=False, post_json=True),
) as response:
self.__handle_response(response)
except Exception as err:
get_logger().error("Failed Unifi login request: %s", tools.efmt(err))
return False
return True
def __make_headers(self, token: bool, post_json: bool) -> dict[str, str]:
headers: dict[str, str] = {}
if token:
assert self.__csrf_token is not None
headers["X-CSRF-TOKEN"] = self.__csrf_token
if post_json:
headers["Content-Type"] = "application/json;charset=UTF-8"
return headers
def __handle_response(self, response: aiohttp.ClientResponse) -> None:
assert self.__http_session is not None
if response.status == 401:
get_logger().info("Unifi API request unauthorized, we will retry a login")
self.__csrf_token = None
self.__http_session.cookie_jar.clear()
htclient.raise_not_200(response)
if "X-CSRF-TOKEN" in response.headers:
self.__csrf_token = response.headers["X-CSRF-TOKEN"]
if response.cookies:
self.__http_session.cookie_jar.update_cookies(response.cookies)
def __ensure_http_session(self) -> aiohttp.ClientSession:
if not self.__http_session:
kwargs: dict = {
"headers": {
"Accept": "application/json",
"User-Agent": htclient.make_user_agent("KVMD"),
},
"cookie_jar": aiohttp.CookieJar(),
"timeout": aiohttp.ClientTimeout(total=self.__timeout),
}
if not self.__verify:
kwargs["connector"] = aiohttp.TCPConnector(ssl=False)
self.__http_session = aiohttp.ClientSession(**kwargs)
return self.__http_session
def __str__(self) -> str:
return f"Unifi({self._instance_name})"
__repr__ = __str__
|