iosignal 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
iosignal/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """IOSignal client for Python.
2
+
3
+ The byte layer (``mbp``, ``protocol``, ``boho``) also runs on MicroPython; the asyncio client and the
4
+ blocking wrapper are CPython only.
5
+ """
6
+
7
+ from . import boho, mbp, protocol
8
+ from .protocol import IOMsg, PayloadType, Signal, State
9
+
10
+ try:
11
+ from .client import AuthError, IOSignal, PingError, RpcError, RpcResponse
12
+ except (ImportError, SyntaxError): # MicroPython: the CPython client does not compile or import there
13
+ pass
14
+
15
+ __all__ = [
16
+ "boho", "mbp", "protocol", "IOSignal", "AuthError", "PingError", "RpcError", "RpcResponse",
17
+ "IOMsg", "PayloadType", "Signal", "State",
18
+ ]
19
+ __version__ = "0.1.0.dev0"
iosignal/board.py ADDED
@@ -0,0 +1,154 @@
1
+ """Starting a MicroPython board on IOSignal from its config files. ``main.py``:
2
+
3
+ import iosignal.board
4
+ iosignal.board.start()
5
+
6
+ Returns at once (the REPL stays free; nothing blocks the boot); Wi-Fi, clock and connection come up in the
7
+ link's timer callback, and come back by themselves when lost. Files on the board:
8
+
9
+ /iosignal.json {"server": "cong://io.iosignal.net:55488", "id": "mydev01", "name": "작업대 ESP32:실험실",
10
+ "repl": true, "device": {"type": "relay4.1", "pins": [16, 17, 18, 19], "invert": true}}
11
+ /device.json {"key": "<device key>"} login key of "id" (tools/mpy_board_setup.py, never printed)
12
+ /wifi.json {"ssid": "...", "password": "..."} (tools/mpy_wifi_setup.py)
13
+ /repl.json {"key": "<64 hex>"} REPL key (tools/mpy_repl_key.py); no key: no remote REPL
14
+
15
+ "device" (optional) makes the board a device driving pins (pin_device): light.1 (1 pin), dimmer.1 (1 PWM pin),
16
+ relay4.1 (4 pins), switch2.1/3.1/4.1/8.1 (2/3/4/8 pins); "invert" for outputs that are on at LOW (relay
17
+ modules). A main.py that calls board.device() itself replaces it.
18
+
19
+ Without "id" the board connects anonymously (its CID changes every time; only for trying things out).
20
+ """
21
+
22
+ import json
23
+
24
+ link = None
25
+ _name = None
26
+
27
+
28
+ def _load(path):
29
+ try:
30
+ with open(path) as f:
31
+ return json.load(f)
32
+ except (OSError, ValueError):
33
+ return None
34
+
35
+
36
+ def start(config="/iosignal.json"):
37
+ """Starts the link from the config files; returns it, or None (with the reason printed) when it cannot."""
38
+ global link, _name
39
+ cfg = _load(config)
40
+ if not cfg or "server" not in cfg:
41
+ print("iosignal: no %s with a server, not started" % config)
42
+ return None
43
+ wifi = _load("/wifi.json")
44
+ device = _load("/device.json") or {}
45
+ repl = _load("/repl.json") or {}
46
+ auth = (cfg["id"], device["key"]) if cfg.get("id") and device.get("key") else None
47
+ if cfg.get("id") and not auth:
48
+ print("iosignal: %s has an id but /device.json has no key, not started" % config)
49
+ return None
50
+ key = bytes.fromhex(repl["key"]) if cfg.get("repl", True) and repl.get("key") else None
51
+ if not key:
52
+ print("iosignal: no REPL key (/repl.json) or repl off: the remote REPL stays off (device only)")
53
+ from . import replpoll
54
+ link = replpoll.start(cfg["server"], key, auth,
55
+ wifi=(wifi["ssid"], wifi["password"]) if wifi else None,
56
+ name=cfg.get("name"))
57
+ _name = cfg.get("name")
58
+ del key, device, repl, wifi
59
+ if cfg.get("device"):
60
+ try:
61
+ pin_device(cfg["device"])
62
+ except Exception as e: # noqa: BLE001 - a bad device entry must not stop the link
63
+ print("iosignal: device not made:", e)
64
+ print("iosignal: starting as %s on %s" % (cfg.get("id") or "anonymous", cfg["server"]))
65
+ return link
66
+
67
+
68
+ def device(name=None, type="", state=None, buttons="", panel=None, view=None, on_command=None, # noqa: A002
69
+ on_change=None):
70
+ """Makes the board a device (device rules): see iosignal.mdevice. ``name`` defaults to the config's name.
71
+
72
+ lamp = board.device(type="light.1", state="on=0", on_change=lambda d: led.value(d.get("on") == "1"))
73
+ """
74
+ if link is None:
75
+ raise RuntimeError("iosignal.board is not started (main.py: iosignal.board.start())")
76
+ from .mdevice import Device
77
+ d = Device(name or _name or "MicroPython", type=type, state=state, buttons=buttons, panel=panel, view=view,
78
+ on_command=on_command, on_change=on_change)
79
+ link.set_device(d)
80
+ return d
81
+
82
+
83
+ # type -> state keys driven by pins (one pin per key; dimmer.1: one PWM pin for on+level)
84
+ PIN_TYPES = {
85
+ "light.1": ("on",),
86
+ "dimmer.1": ("on",),
87
+ "relay4.1": ("r1", "r2", "r3", "r4"),
88
+ "switch2.1": ("s1", "s2"),
89
+ "switch3.1": ("s1", "s2", "s3"),
90
+ "switch4.1": ("s1", "s2", "s3", "s4"),
91
+ "switch8.1": ("s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"),
92
+ }
93
+
94
+
95
+ def pin_device(spec):
96
+ """The device from an iosignal.json "device" entry: {"type", "pins", "invert"}. Outputs start off."""
97
+ from machine import Pin
98
+ kind = spec.get("type")
99
+ keys = PIN_TYPES.get(kind)
100
+ if keys is None:
101
+ raise ValueError("type %r is not one of %s" % (kind, ", ".join(sorted(PIN_TYPES))))
102
+ pins = [int(p) for p in spec.get("pins") or ()]
103
+ if len(pins) != len(keys):
104
+ raise ValueError("%s needs %d pins, got %d" % (kind, len(keys), len(pins)))
105
+ invert = bool(spec.get("invert"))
106
+ if kind == "dimmer.1":
107
+ from machine import PWM
108
+ pwm = PWM(Pin(pins[0]), freq=1000)
109
+
110
+ def apply(d):
111
+ try:
112
+ level = max(0, min(100, int(float(d.get("level", "0")))))
113
+ except ValueError:
114
+ level = 0
115
+ duty = level * 65535 // 100 if d.get("on") == "1" else 0
116
+ pwm.duty_u16(65535 - duty if invert else duty)
117
+ state = "on=0;level=50"
118
+ else:
119
+ outs = [Pin(p, Pin.OUT) for p in pins]
120
+
121
+ def apply(d):
122
+ for k, out in zip(keys, outs):
123
+ out.value(1 if (d.get(k) == "1") != invert else 0)
124
+ state = ";".join(k + "=0" for k in keys)
125
+ d = device(type=kind, state=state, on_change=apply)
126
+ apply(d)
127
+ return d
128
+
129
+
130
+ def subscribe(tag, fn):
131
+ """``fn(tag, value)`` for every signal on ``tag`` (e.g. another device's ``"abc-123@$state"``)."""
132
+ if link is None:
133
+ raise RuntimeError("iosignal.board is not started (main.py: iosignal.board.start())")
134
+ link.subscribe(tag, fn)
135
+
136
+
137
+ def signal(tag, text=""):
138
+ """Sends a TEXT signal, e.g. a command ``signal("abc-123@", "r1=1")``; False when not online."""
139
+ return link is not None and link.signal(tag, text)
140
+
141
+
142
+ def status():
143
+ """A short line about the link, for the USB REPL."""
144
+ if link is None:
145
+ return "not started"
146
+ l = link
147
+ phase = ("online" if l.ready else "logging in" if l.sock else "connecting" if l.pending
148
+ else "waiting for Wi-Fi" if l.wlan is not None and not l.wlan.isconnected()
149
+ else "setting the clock" if not l.clock_ok else "retrying")
150
+ dev = l.device
151
+ return "%s, cid %s, session %s, stats %s, recent errors %s%s" % (
152
+ phase, l.cid or "-", l.owner or "none", l.stats, l.errors,
153
+ ", device %s %s commands %d errors %s" % (dev.type or "-", dev.state.text(), dev.commands, dev.errors)
154
+ if dev else "")
iosignal/boho.py ADDED
@@ -0,0 +1,340 @@
1
+ """Boho 2.x session protocol (npm ``boho``, src/boho.js): login proof, ENC_488 session packets and ENC_PACK.
2
+
3
+ Byte layouts and hash inputs match the JavaScript implementation. Both sides are here: the client
4
+ (``auth_req``, ``verify_auth_res``) and the server (``server_time_nonce``, ``verify_auth_req``), so the
5
+ protocol can be tested without a server.
6
+
7
+ Packets:
8
+ SERVER_TIME_NONCE B0 | u32LE seconds | u16LE ms | u16LE counter | nonce4 13 bytes
9
+ AUTH_REQ B1 | id8 | nonce4 | sha256(key32 | salt12 | nonce4) 45 bytes
10
+ AUTH_RES B2 | sha256(key32 | salt12' | clientNonce) 33 bytes
11
+ ENC_488 B8 | u32LE len | clock8 | tag8 | xdata 21 + len
12
+ ENC_PACK B6 | u32LE len | salt12 | tag8 | xdata 25 + len
13
+
14
+ ``key32`` is sha256(key). Tags are the legacy prefix hash sha256(key32 | salt12 | data), not HMAC.
15
+ """
16
+
17
+ import hashlib
18
+ import os
19
+ import time
20
+
21
+ try:
22
+ import _thread
23
+ except ImportError: # a MicroPython build without threads
24
+ _thread = None
25
+
26
+ __all__ = [
27
+ "Boho", "SERVER_TIME_NONCE", "AUTH_REQ", "AUTH_RES", "AUTH_FAIL", "ENC_PACK", "ENC_E2E", "ENC_488",
28
+ "SERVER_TIME_NONCE_SIZE", "AUTH_REQ_SIZE", "AUTH_RES_SIZE", "ENC_PACK_META", "ENC_488_META", "sha256",
29
+ ]
30
+
31
+ SERVER_TIME_NONCE = 0xB0
32
+ AUTH_REQ = 0xB1
33
+ AUTH_RES = 0xB2
34
+ AUTH_FAIL = 0xB3
35
+ ENC_PACK = 0xB6
36
+ ENC_E2E = 0xB7
37
+ ENC_488 = 0xB8
38
+
39
+ SERVER_TIME_NONCE_SIZE = 13
40
+ AUTH_REQ_SIZE = 45
41
+ AUTH_RES_SIZE = 33
42
+ ENC_PACK_META = 25
43
+ ENC_488_META = 21
44
+
45
+
46
+
47
+ def _equal(a: bytes, b: bytes) -> bool:
48
+ """Compares tags without an early exit on the first difference (hmac.compare_digest is not on MicroPython)."""
49
+ if len(a) != len(b):
50
+ return False
51
+ diff = 0
52
+ for x, y in zip(a, b):
53
+ diff |= x ^ y
54
+ return diff == 0
55
+
56
+
57
+ class _RLock:
58
+ """Reentrant lock on _thread (threading.RLock is not on MicroPython). A no-op without threads."""
59
+
60
+ def __init__(self):
61
+ self._lock = _thread.allocate_lock() if _thread else None
62
+ self._owner = None
63
+ self._depth = 0
64
+
65
+ def __enter__(self):
66
+ if self._lock is None:
67
+ return self
68
+ me = _thread.get_ident()
69
+ if self._owner == me:
70
+ self._depth += 1
71
+ return self
72
+ self._lock.acquire()
73
+ self._owner, self._depth = me, 1
74
+ return self
75
+
76
+ def __exit__(self, *exc):
77
+ if self._lock is None:
78
+ return
79
+ self._depth -= 1
80
+ if self._depth == 0:
81
+ self._owner = None
82
+ self._lock.release()
83
+
84
+
85
+ def sha256(*parts: bytes) -> bytes:
86
+ h = hashlib.sha256()
87
+ for p in parts:
88
+ h.update(p)
89
+ return h.digest()
90
+
91
+
92
+ def _bytes(data) -> bytes:
93
+ return data.encode() if isinstance(data, str) else bytes(data)
94
+
95
+
96
+ # Some MicroPython ports count from 2000-01-01; Boho clocks are Unix epoch milliseconds.
97
+ _EPOCH_OFFSET_MS = 946684800000 if time.gmtime(0)[0] == 2000 else 0
98
+
99
+
100
+ def _now_ms() -> int:
101
+ """Unix epoch milliseconds. (MicroPython boards need the clock set, e.g. by ntptime: the server
102
+ refuses encrypted packets whose clock is more than 60 s off.)"""
103
+ if hasattr(time, "time_ns"):
104
+ return time.time_ns() // 1000000 + _EPOCH_OFFSET_MS
105
+ return int(time.time() * 1000) + _EPOCH_OFFSET_MS
106
+
107
+
108
+ class Boho:
109
+ """One Boho session. Senders and the socket reader may share it, so state changes hold a lock.
110
+
111
+ ``rand(n)`` and ``clock()`` (epoch milliseconds) can be replaced in tests.
112
+ """
113
+
114
+ def __init__(self, rand=os.urandom, clock=_now_ms):
115
+ self._rand = rand
116
+ self._clock = clock
117
+ self._lock = _RLock()
118
+ self.clear_auth()
119
+
120
+ # ---- key and ID
121
+
122
+ def clear_auth(self) -> None:
123
+ with self._lock:
124
+ self._id8 = bytes(8)
125
+ self._key32 = bytes(32)
126
+ self._has_key = False
127
+ self._salt12 = bytes(12)
128
+ self._auth_salt12 = bytes(12)
129
+ self.local_nonce = bytes(4)
130
+ self.remote_nonce = bytes(4)
131
+ self.counter = 0
132
+ self._last_send_time = 0
133
+ self.is_authorized = False
134
+
135
+ def set_id8(self, id_) -> None:
136
+ """The ID's first 8 UTF-8 bytes, zero padded."""
137
+ raw = _bytes(id_)[:8]
138
+ self._id8 = raw + bytes(8 - len(raw))
139
+
140
+ def set_key(self, key) -> None:
141
+ data = _bytes(key)
142
+ if not data:
143
+ raise ValueError("Key must not be empty")
144
+ self.copy_key(sha256(data))
145
+
146
+ def copy_key(self, key32: bytes) -> None:
147
+ if len(key32) != 32:
148
+ raise ValueError("copy_key requires exactly 32 bytes")
149
+ with self._lock:
150
+ self._key32 = bytes(key32)
151
+ self._has_key = True
152
+
153
+ def set_id_key(self, id_key: str) -> bool:
154
+ """Splits ``id.key`` at the first dot. False (nothing set) without a dot."""
155
+ if "." not in id_key:
156
+ return False
157
+ id_, key = id_key.split(".", 1)
158
+ self.set_id8(id_)
159
+ self.set_key(key)
160
+ return True
161
+
162
+ @property
163
+ def has_key(self) -> bool:
164
+ return self._has_key
165
+
166
+ # ---- primitives
167
+
168
+ def _require_key(self) -> None:
169
+ if not self._has_key:
170
+ raise RuntimeError("Set a key before encryption or authentication")
171
+
172
+ def _tag(self, data: bytes) -> bytes:
173
+ return sha256(self._key32, self._salt12, data)
174
+
175
+ def _xotp(self, data: bytes) -> bytes:
176
+ """XOR with sha256(otp32 | u32LE index) blocks, index from 1, otp32 = sha256(key32 | salt12)."""
177
+ otp32 = sha256(self._key32, self._salt12)
178
+ out = bytearray(data)
179
+ for block, offset in enumerate(range(0, len(out), 32), 1):
180
+ pad = sha256(otp32, block.to_bytes(4, "little"))
181
+ for i in range(min(32, len(out) - offset)):
182
+ out[offset + i] ^= pad[i]
183
+ return bytes(out)
184
+
185
+ def _set_clock_nonce(self, nonce: bytes) -> None:
186
+ """A monotonic clock and counter, with the peer's nonce, as the salt."""
187
+ now = max(self._clock(), self._last_send_time)
188
+ self.counter = (self.counter + 1) & 0xFFFF
189
+ if self.counter == 0 and now == self._last_send_time:
190
+ now += 1
191
+ if now < 0 or now // 1000 > 0xFFFFFFFF:
192
+ raise ValueError("Clock is outside the protocol range")
193
+ self._last_send_time = now
194
+ self._salt12 = ((now // 1000).to_bytes(4, "little") + (now % 1000).to_bytes(2, "little")
195
+ + self.counter.to_bytes(2, "little") + nonce)
196
+
197
+ @staticmethod
198
+ def _sized(packet: bytes, type_: int, meta: int, variable: bool) -> bool:
199
+ if len(packet) < meta or packet[0] != type_:
200
+ return False
201
+ if variable:
202
+ return int.from_bytes(packet[1:5], "little") == len(packet) - meta
203
+ return len(packet) == meta
204
+
205
+ # ---- login: client
206
+
207
+ def auth_req(self, challenge: bytes) -> bytes | None:
208
+ """AUTH_REQ answering a SERVER_TIME_NONCE challenge; None without a key or for a malformed challenge."""
209
+ with self._lock:
210
+ if not self._has_key or not self._sized(challenge, SERVER_TIME_NONCE, SERVER_TIME_NONCE_SIZE, False):
211
+ return None
212
+ if int.from_bytes(challenge[5:7], "little") >= 1000:
213
+ return None
214
+ self.is_authorized = False
215
+ self._salt12 = bytes(challenge[1:13])
216
+ self.local_nonce = self._rand(4)
217
+ self.remote_nonce = bytes(challenge[9:13])
218
+ return bytes([AUTH_REQ]) + self._id8 + self.local_nonce + self._tag(self.local_nonce)
219
+
220
+ def verify_auth_res(self, packet: bytes) -> bool:
221
+ """True when AUTH_RES proves the server knows the key; the session is then authorized."""
222
+ with self._lock:
223
+ if not self._has_key or not self._sized(packet, AUTH_RES, AUTH_RES_SIZE, False):
224
+ return False
225
+ self._salt12 = self.remote_nonce + self.local_nonce + self.remote_nonce
226
+ ok = _equal(self._tag(self.local_nonce), bytes(packet[1:33]))
227
+ if ok:
228
+ self.is_authorized = True
229
+ return ok
230
+
231
+ # ---- login: server
232
+
233
+ def server_time_nonce(self) -> bytes:
234
+ with self._lock:
235
+ now = self._clock()
236
+ self.local_nonce = self._rand(4)
237
+ self._auth_salt12 = ((now // 1000).to_bytes(4, "little") + (now % 1000).to_bytes(2, "little")
238
+ + self._rand(2) + self.local_nonce)
239
+ return bytes([SERVER_TIME_NONCE]) + self._auth_salt12
240
+
241
+ def id8_of(self, packet: bytes) -> bytes | None:
242
+ """The ID field of an AUTH_REQ, so a server can look up the key before verifying."""
243
+ return bytes(packet[1:9]) if self._sized(packet, AUTH_REQ, AUTH_REQ_SIZE, False) else None
244
+
245
+ def verify_auth_req(self, packet: bytes) -> bytes | None:
246
+ """AUTH_RES for a valid AUTH_REQ (the session is then authorized), else None."""
247
+ with self._lock:
248
+ if not self._has_key or not self._sized(packet, AUTH_REQ, AUTH_REQ_SIZE, False):
249
+ return None
250
+ nonce = bytes(packet[9:13])
251
+ self._salt12 = self._auth_salt12
252
+ if not _equal(self._tag(nonce), bytes(packet[13:45])):
253
+ return None
254
+ self.remote_nonce = nonce
255
+ self._salt12 = self.local_nonce + self.remote_nonce + self.local_nonce
256
+ self.is_authorized = True
257
+ return bytes([AUTH_RES]) + self._tag(nonce)
258
+
259
+ # ---- session packets
260
+
261
+ def deauthorize(self) -> None:
262
+ """A dropped connection needs a new login; the ID and key stay for it."""
263
+ self.is_authorized = False
264
+
265
+ def encrypt_488(self, data) -> bytes | None:
266
+ """ENC_488 packet; None before authentication."""
267
+ with self._lock:
268
+ if not self.is_authorized or not self._has_key:
269
+ return None
270
+ plain = _bytes(data)
271
+ self._set_clock_nonce(self.remote_nonce)
272
+ tag = self._tag(plain)
273
+ return (bytes([ENC_488]) + len(plain).to_bytes(4, "little") + self._salt12[:8] + tag[:8]
274
+ + self._xotp(plain))
275
+
276
+ def decrypt_488(self, packet: bytes) -> bytes | None:
277
+ """Plaintext of an ENC_488 packet, or of the encrypted header of an ENC_E2E packet.
278
+
279
+ None for a malformed, unauthenticated or forged packet.
280
+ """
281
+ with self._lock:
282
+ if not self.is_authorized or not self._has_key:
283
+ return None
284
+ p = bytes(packet)
285
+ if p[:1] == bytes([ENC_E2E]):
286
+ if len(p) < ENC_488_META:
287
+ return None
288
+ header_len = int.from_bytes(p[1:5], "little")
289
+ if header_len > len(p) - ENC_488_META:
290
+ return None
291
+ p = bytes([ENC_488]) + p[1:ENC_488_META + header_len]
292
+ if not self._sized(p, ENC_488, ENC_488_META, True):
293
+ return None
294
+ if int.from_bytes(p[9:11], "little") >= 1000: # the clock's milliseconds
295
+ return None
296
+ self._salt12 = p[5:13] + self.local_nonce
297
+ plain = self._xotp(p[ENC_488_META:])
298
+ if not _equal(self._tag(plain)[:8], p[13:21]):
299
+ return None
300
+ return plain
301
+
302
+ def encrypt_pack(self, data) -> bytes:
303
+ """ENC_PACK with this key and a random nonce; needs no login."""
304
+ with self._lock:
305
+ self._require_key()
306
+ plain = _bytes(data)
307
+ self._set_clock_nonce(self._rand(4))
308
+ tag = self._tag(plain)
309
+ return (bytes([ENC_PACK]) + len(plain).to_bytes(4, "little") + self._salt12 + tag[:8]
310
+ + self._xotp(plain))
311
+
312
+ def decrypt_pack(self, packet: bytes) -> bytes | None:
313
+ with self._lock:
314
+ if not self._has_key or not self._sized(bytes(packet), ENC_PACK, ENC_PACK_META, True):
315
+ return None
316
+ p = bytes(packet)
317
+ self._salt12 = p[5:17]
318
+ plain = self._xotp(p[ENC_PACK_META:])
319
+ if not _equal(self._tag(plain)[:8], p[17:25]):
320
+ return None
321
+ return plain
322
+
323
+ def encrypt_e2e(self, data, key) -> bytes:
324
+ """ENC_PACK with another key, leaving the session key and salt as they were."""
325
+ return self._with_key(key, lambda: self.encrypt_pack(data))
326
+
327
+ def decrypt_e2e(self, packet: bytes, key) -> bytes | None:
328
+ return self._with_key(key, lambda: self.decrypt_pack(packet))
329
+
330
+ def _with_key(self, key, operation):
331
+ k = _bytes(key)
332
+ if not k:
333
+ raise ValueError("Key must not be empty")
334
+ with self._lock:
335
+ saved = (self._key32, self._has_key, self._salt12)
336
+ try:
337
+ self._key32, self._has_key = sha256(k), True
338
+ return operation()
339
+ finally:
340
+ self._key32, self._has_key, self._salt12 = saved