-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathespresense_wrapper.py
More file actions
155 lines (135 loc) · 5.34 KB
/
espresense_wrapper.py
File metadata and controls
155 lines (135 loc) · 5.34 KB
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
import json
import time
from typing import Any, Dict, Optional
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlparse
from urllib.request import Request, urlopen
from websocket import WebSocketException, WebSocketTimeoutException, create_connection
class ESPresenseWrapperError(Exception):
pass
class ESPresenseWrapper:
def __init__(self, base_url: str, timeout_seconds: float = 5.0):
self.base_url = base_url.rstrip("/")
self.timeout_seconds = timeout_seconds
def start_enrollment(self, device_type: str, name: str) -> Dict[str, Any]:
payload = f"{device_type}|{name}"
return self._send_command("enroll", payload)
def cancel_enrollment(self) -> Dict[str, Any]:
return self._send_command("cancelEnroll")
def update_filters(
self, include: Optional[str] = None, exclude: Optional[str] = None
) -> Dict[str, Any]:
form: Dict[str, str] = {}
if include is not None:
form["include"] = include
if exclude is not None:
form["exclude"] = exclude
if not form:
return {
"ok": False,
"error": "invalid_request",
"message": "At least one of include or exclude is required.",
}
return self._post_form("/wifi/extras", form)
def _send_command(
self, command: str, payload: Optional[str] = None
) -> Dict[str, Any]:
ws_url = self._build_ws_url()
message: Dict[str, Any] = {"command": command}
if payload is not None:
message["payload"] = payload
try:
ws = create_connection(ws_url, timeout=self.timeout_seconds)
except (WebSocketException, OSError) as exc:
raise ESPresenseWrapperError(
f"Failed to connect to ESPresense websocket at {ws_url}"
) from exc
try:
ws.send(json.dumps(message))
deadline = time.time() + self.timeout_seconds
while time.time() < deadline:
try:
raw = ws.recv()
except WebSocketTimeoutException:
continue
parsed = self._safe_json(raw)
if command == "enroll":
state = parsed.get("state", {}) if isinstance(parsed, dict) else {}
if state.get("enrolling") is True:
return {
"ok": True,
"command": command,
"request": message,
"ack": parsed,
}
elif command == "cancelEnroll":
state = parsed.get("state", {}) if isinstance(parsed, dict) else {}
if state.get("enrolling") is False:
return {
"ok": True,
"command": command,
"request": message,
"ack": parsed,
}
return {
"ok": False,
"command": command,
"request": message,
"ack": None,
"error": "timeout",
"message": "Command sent but no matching state ack before timeout.",
}
except WebSocketException as exc:
raise ESPresenseWrapperError(
"Failed while sending/receiving websocket messages"
) from exc
finally:
ws.close()
def _build_ws_url(self) -> str:
parsed = urlparse(self.base_url)
scheme = "wss" if parsed.scheme == "https" else "ws"
host = parsed.netloc
if not host:
host = parsed.path
return f"{scheme}://{host}/ws"
def _build_http_url(self, path: str) -> str:
return f"{self.base_url}{path}"
def _post_form(self, path: str, form: Dict[str, str]) -> Dict[str, Any]:
url = self._build_http_url(path)
body = urlencode(form).encode("utf-8")
req = Request(
url=url,
data=body,
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST",
)
try:
with urlopen(req, timeout=self.timeout_seconds) as res:
raw = res.read().decode("utf-8", errors="replace")
return {
"ok": True,
"path": path,
"request": form,
"status": getattr(res, "status", 200),
"body": raw,
}
except HTTPError as exc:
raise ESPresenseWrapperError(
f"Failed POST {path} with status {exc.code}"
) from exc
except URLError as exc:
raise ESPresenseWrapperError(f"Failed to connect to {url}") from exc
@staticmethod
def _safe_json(raw: Any) -> Dict[str, Any]:
if isinstance(raw, bytes):
raw = raw.decode("utf-8", errors="replace")
if not isinstance(raw, str):
return {}
try:
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else {}
except json.JSONDecodeError:
return {}
if __name__ == "__main__":
client = ESPresenseWrapper("http://10.251.10.179")
print(client.start_enrollment("s", "s"))