pyvisionect 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.
Files changed (58) hide show
  1. pyvisionect/__init__.py +120 -0
  2. pyvisionect/devices/__init__.py +92 -0
  3. pyvisionect/devices/enums.py +403 -0
  4. pyvisionect/devices/panels.py +242 -0
  5. pyvisionect/devices/tclv.py +460 -0
  6. pyvisionect/imaging/README.md +175 -0
  7. pyvisionect/imaging/__init__.py +181 -0
  8. pyvisionect/imaging/checksum.py +114 -0
  9. pyvisionect/imaging/constants.py +131 -0
  10. pyvisionect/imaging/data/blue_noise_64.npy +0 -0
  11. pyvisionect/imaging/decode.py +172 -0
  12. pyvisionect/imaging/dither.py +357 -0
  13. pyvisionect/imaging/encoder.py +594 -0
  14. pyvisionect/imaging/geometry.py +129 -0
  15. pyvisionect/imaging/grey.py +104 -0
  16. pyvisionect/imaging/interlace.py +244 -0
  17. pyvisionect/imaging/pack.py +142 -0
  18. pyvisionect/imaging/panel.py +339 -0
  19. pyvisionect/imaging/partial.py +931 -0
  20. pyvisionect/imaging/rects.py +466 -0
  21. pyvisionect/io/__init__.py +33 -0
  22. pyvisionect/io/tcp.py +795 -0
  23. pyvisionect/io/usb/__init__.py +237 -0
  24. pyvisionect/io/usb/cli.py +278 -0
  25. pyvisionect/io/usb/commands.py +781 -0
  26. pyvisionect/io/usb/console.py +730 -0
  27. pyvisionect/io/usb/device.py +914 -0
  28. pyvisionect/io/usb/discovery.py +260 -0
  29. pyvisionect/io/usb/encryption.py +262 -0
  30. pyvisionect/io/usb/errors.py +175 -0
  31. pyvisionect/io/usb/fake.py +292 -0
  32. pyvisionect/io/usb/parsers.py +1464 -0
  33. pyvisionect/io/usb/provisioning.py +502 -0
  34. pyvisionect/packets/__init__.py +135 -0
  35. pyvisionect/packets/control.py +95 -0
  36. pyvisionect/packets/file.py +325 -0
  37. pyvisionect/packets/image.py +234 -0
  38. pyvisionect/packets/misc.py +202 -0
  39. pyvisionect/packets/param.py +284 -0
  40. pyvisionect/packets/status.py +518 -0
  41. pyvisionect/packets/stored.py +217 -0
  42. pyvisionect/py.typed +0 -0
  43. pyvisionect/session/__init__.py +100 -0
  44. pyvisionect/session/connection.py +1043 -0
  45. pyvisionect/session/device.py +587 -0
  46. pyvisionect/session/events.py +196 -0
  47. pyvisionect/session/filetransfer.py +251 -0
  48. pyvisionect/session/pending.py +425 -0
  49. pyvisionect/wire/__init__.py +91 -0
  50. pyvisionect/wire/blocks.py +350 -0
  51. pyvisionect/wire/checksum.py +115 -0
  52. pyvisionect/wire/errors.py +176 -0
  53. pyvisionect/wire/framing.py +334 -0
  54. pyvisionect-0.1.0.dist-info/METADATA +1030 -0
  55. pyvisionect-0.1.0.dist-info/RECORD +58 -0
  56. pyvisionect-0.1.0.dist-info/WHEEL +4 -0
  57. pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
  58. pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
pyvisionect/io/tcp.py ADDED
@@ -0,0 +1,795 @@
1
+ """asyncio TCP listener -- the only networking code in the library.
2
+
3
+ The sign is a **client**: it dials out to TCP 11113 and speaks first. So the
4
+ server's job is to listen, accept whatever connects, and let the sans-io
5
+ :class:`~pyvisionect.session.connection.DeviceConnection` do the rest.
6
+
7
+ There is no auth and no handshake, so this listener accepts every connection.
8
+ Put it somewhere only your signs can reach.
9
+
10
+ The vendor's gateway sniffs the first 6 bytes for a TLS ClientHello
11
+ (``b[0] == 0x16``, ``b[1] == 0x03``, ``b[2] in 1..4``, ``b[5] == 0x01``) and
12
+ opportunistically upgrades, so plaintext and TLS devices share one port. So do
13
+ we: pass *ssl_context* (or *certfile* / *keyfile*) and the same 6 bytes decide,
14
+ per connection, which protocol this one is. With no context configured the
15
+ listener is plaintext-only, exactly as before.
16
+
17
+ The sniff runs either way, because the one realistic way to strand a sign is to
18
+ set TCLV 145 (``TLS mode: 0=disabled, 1=TLS 1.3``) against a listener that has
19
+ no certificate. That failure is otherwise invisible -- the frame decoder just
20
+ rejects the ClientHello as a bad header -- so the peek happens even when TLS is
21
+ off, purely to log it and count it in :attr:`ServerStats.tls_unsupported`.
22
+
23
+ Memory note: a full-screen push to the 32" panel is a single ~1.84 MB write.
24
+ Between the encoded rectangles, the block chain and the socket buffer, budget
25
+ roughly 6-8 MB of transient peak per device being pushed to. The write itself
26
+ is a ``write`` + ``drain`` and is fine on the event loop; the *encoding* is not
27
+ (see :mod:`pyvisionect.imaging`).
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import asyncio
33
+ import contextlib
34
+ import logging
35
+ import ssl
36
+ import time
37
+ from dataclasses import dataclass, field
38
+ from typing import Awaitable, Callable
39
+
40
+ from ..packets.file import (
41
+ DEVICE_FILE_READ_CHUNK,
42
+ FILE_LIST_LENGTH,
43
+ FILE_LIST_PATH,
44
+ FileListEntry,
45
+ parse_file_listing,
46
+ )
47
+ from ..session import DeviceConnection, DeviceStateStore
48
+ from ..session.connection import ConnectionConfig
49
+ from ..session.events import Event
50
+ from ..session.filetransfer import FileRead
51
+ from ..wire.errors import ListenError, VisionectError
52
+
53
+ __all__ = [
54
+ "DEFAULT_PORT",
55
+ "DEFAULT_FILE_TIMEOUT",
56
+ "TLS_PEEK_BYTES",
57
+ "FileReadError",
58
+ "ServerStats",
59
+ "VisionectServer",
60
+ "EventHandler",
61
+ "looks_like_client_hello",
62
+ "server_ssl_context",
63
+ ]
64
+
65
+ DEFAULT_FILE_TIMEOUT = 30.0
66
+ """Seconds to wait for one file reply before giving up on it.
67
+
68
+ Generous on purpose: a 1 KiB reply takes ~420 ms in the steady state, but the
69
+ device is also drawing panels and talking to wifi, and a reply that is merely
70
+ slow is not worth restarting a nine-minute transfer for.
71
+ """
72
+
73
+
74
+ class FileReadError(VisionectError):
75
+ """A device file read did not complete."""
76
+
77
+ DEFAULT_PORT = 11113
78
+ """``main.init`` registers ``flag.String("port", "11113", ...)``; it is not in
79
+ ``config.json``."""
80
+
81
+ READ_CHUNK = 65536
82
+
83
+ TLS_PEEK_BYTES = 6
84
+ """How many bytes the vendor's gateway peeks before deciding TLS or plaintext.
85
+
86
+ Six, because ``b[5]`` is the handshake-message type and that is the last byte
87
+ the test looks at.
88
+ """
89
+
90
+ log = logging.getLogger(__name__)
91
+
92
+
93
+ def looks_like_client_hello(head: bytes) -> bool:
94
+ """The vendor gateway's ClientHello test, byte for byte.
95
+
96
+ ``head[0] == 0x16`` (a handshake record), ``head[1] == 0x03`` and
97
+ ``head[2] in 1..4`` (TLS 1.0 through 1.3 in the legacy record version), and
98
+ ``head[5] == 0x01`` (``ClientHello``).
99
+
100
+ It cannot collide with a plaintext frame: a ``ProtocolHeader`` opens with
101
+ ``Version`` as a little-endian ``uint32``, so the only version this library
102
+ speaks, 3, puts ``03 00 00 00`` on the wire and fails the first test. For a
103
+ header to pass, ``Version`` would have to be ``0x01030316`` -- about 17
104
+ million, which the decoder rejects anyway.
105
+
106
+ Fewer than :data:`TLS_PEEK_BYTES` bytes is False: a connection that closed
107
+ mid-peek is not a TLS connection, it is a connection that closed.
108
+ """
109
+ return (
110
+ len(head) >= TLS_PEEK_BYTES
111
+ and head[0] == 0x16
112
+ and head[1] == 0x03
113
+ and head[2] in (1, 2, 3, 4)
114
+ and head[5] == 0x01
115
+ )
116
+
117
+
118
+ def server_ssl_context(
119
+ certfile: str, keyfile: str | None = None, *, password: str | None = None
120
+ ) -> ssl.SSLContext:
121
+ """A server context matching the vendor gateway's TLS settings.
122
+
123
+ TLS 1.3 only, which is what the gateway's ``MinVersion: 0x0304`` and the
124
+ device parameter's own description (``"TLS mode: 0=disabled, 1=TLS 1.3"``)
125
+ both say, and no client certificate: the protocol has no device identity to
126
+ check one against.
127
+
128
+ The gateway also names three curves -- P-521, P-384, P-256 -- which this
129
+ deliberately does **not** narrow to. OpenSSL's default group list is a
130
+ superset of those three, and pinning it to the vendor's list could only
131
+ ever reject a device, never admit one.
132
+ """
133
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
134
+ context.minimum_version = ssl.TLSVersion.TLSv1_3
135
+ context.verify_mode = ssl.CERT_NONE
136
+ context.load_cert_chain(certfile, keyfile, password=password)
137
+ return context
138
+
139
+ EventHandler = Callable[[DeviceConnection, list[Event]], Awaitable[None] | None]
140
+
141
+
142
+ @dataclass
143
+ class ServerStats:
144
+ """Counters for telling apart the two ways this silently does nothing.
145
+
146
+ "Nothing ever reaches the port" and "something connects but is not a sign"
147
+ need opposite troubleshooting advice, and neither produces an exception.
148
+ These counters are the cheapest way to tell them apart:
149
+
150
+ * ``accepted == 0`` -> nothing is reaching the port at all. Check that the
151
+ sign is pointed here (``server_tcp_set``, or the DNS name it holds),
152
+ that the host firewall allows 11113, and that no other process holds it.
153
+ * ``accepted > 0`` but ``identified == 0`` -> something is connecting but
154
+ never sends a valid first status packet. Could be a port scanner, a
155
+ health check, or a sign speaking a protocol version we do not handle.
156
+ * ``accepted > silent_connections`` and ``identified > 0`` -> it works.
157
+
158
+ One caveat worth knowing before you treat a counter as an error: the capture
159
+ shows a connection that **opened and closed carrying zero protocol bytes**,
160
+ from the real sign, in normal operation. ``silent_connections`` counts
161
+ those and they are not a fault.
162
+ """
163
+
164
+ accepted: int = 0
165
+ """Connections accepted, including ones that sent nothing."""
166
+
167
+ identified: int = 0
168
+ """Connections that produced a valid first status packet (and so a UUID)."""
169
+
170
+ silent_connections: int = 0
171
+ """Accepted connections that closed without sending a single byte.
172
+
173
+ Normal: observed from the real sign in the reference capture.
174
+ """
175
+
176
+ rejected: int = 0
177
+ """Connections closed on a protocol violation."""
178
+
179
+ tls_accepted: int = 0
180
+ """Connections whose TLS handshake completed."""
181
+
182
+ tls_failed: int = 0
183
+ """Connections that offered a ClientHello and then failed the handshake.
184
+
185
+ A device that **rejects our certificate** lands here, and the logged
186
+ ``SSLError`` names the alert it sent.
187
+ """
188
+
189
+ tls_unsupported: int = 0
190
+ """ClientHellos that arrived while no ``ssl_context`` was configured.
191
+
192
+ Non-zero means something -- almost certainly a sign with TCLV 145 set to 1
193
+ -- is trying to speak TLS to a plaintext-only listener and getting nowhere.
194
+ It is the counter that makes that specific mistake visible; see the module
195
+ docstring.
196
+ """
197
+
198
+ # Both are counted *inside* any TLS tunnel, so they measure the protocol
199
+ # rather than the wire: record framing and handshake traffic are excluded.
200
+ bytes_in: int = 0
201
+ bytes_out: int = 0
202
+
203
+ last_accept_at: float | None = None
204
+ last_seen: dict[bytes, float] = field(default_factory=dict)
205
+ """UUID -> clock value of the last frame received from it."""
206
+
207
+ def last_seen_uuid(self) -> dict[str, float]:
208
+ """:attr:`last_seen` keyed on the canonical UUID string."""
209
+ out = {}
210
+ for device_id, when in self.last_seen.items():
211
+ h = device_id.hex()
212
+ out[f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"] = when
213
+ return out
214
+
215
+
216
+ class _TlsStream:
217
+ """TLS over a stream whose first bytes have already been read.
218
+
219
+ The sniff is why this exists. ``loop.start_tls()`` hands the socket to
220
+ OpenSSL and OpenSSL reads from the socket, so the six ClientHello bytes we
221
+ consumed to *recognise* the ClientHello would be lost and the handshake
222
+ would fail on a malformed record. Driving an :class:`ssl.SSLObject` over a
223
+ pair of :class:`ssl.MemoryBIO` instead puts us in charge of what OpenSSL
224
+ sees, and the first thing it sees is those six bytes.
225
+
226
+ The cost is that we pump bytes by hand. The upside is that the object
227
+ quacks exactly like the ``StreamReader``/``StreamWriter`` pair the read loop
228
+ already uses -- ``read``, ``write``, ``drain``, ``close``, ``wait_closed``,
229
+ ``get_extra_info`` -- so nothing above it knows the difference.
230
+ """
231
+
232
+ def __init__(
233
+ self,
234
+ reader: asyncio.StreamReader,
235
+ writer: asyncio.StreamWriter,
236
+ context: ssl.SSLContext,
237
+ head: bytes,
238
+ ) -> None:
239
+ self._reader = reader
240
+ self._writer = writer
241
+ self._incoming = ssl.MemoryBIO()
242
+ self._outgoing = ssl.MemoryBIO()
243
+ self._tls = context.wrap_bio(
244
+ self._incoming, self._outgoing, server_side=True
245
+ )
246
+ self._incoming.write(head)
247
+ self._eof = False
248
+
249
+ def get_extra_info(self, name: str, default: object = None) -> object:
250
+ if name == "ssl_object":
251
+ return self._tls
252
+ return self._writer.get_extra_info(name, default)
253
+
254
+ # -- the byte pump ---------------------------------------------------
255
+
256
+ async def _send_pending(self) -> None:
257
+ """Flush whatever OpenSSL wants on the wire."""
258
+ data = self._outgoing.read()
259
+ if data:
260
+ self._writer.write(data)
261
+ await self._writer.drain()
262
+
263
+ async def _receive_more(self) -> bool:
264
+ """Feed one socket read into OpenSSL. False at EOF."""
265
+ if self._eof:
266
+ return False
267
+ data = await self._reader.read(READ_CHUNK)
268
+ if not data:
269
+ self._eof = True
270
+ self._incoming.write_eof()
271
+ return False
272
+ self._incoming.write(data)
273
+ return True
274
+
275
+ async def handshake(self) -> None:
276
+ """Complete the handshake, or raise.
277
+
278
+ Raises:
279
+ ssl.SSLError: the handshake failed. If the device rejected our
280
+ certificate this is where it shows up, and the message carries
281
+ the alert the device sent.
282
+ ssl.SSLEOFError: the device hung up mid-handshake, which is what a
283
+ stack that dislikes the certificate but sends no alert looks
284
+ like.
285
+ """
286
+ while True:
287
+ try:
288
+ self._tls.do_handshake()
289
+ except ssl.SSLWantReadError:
290
+ await self._send_pending()
291
+ if not await self._receive_more():
292
+ raise ssl.SSLEOFError(
293
+ "the device closed the connection during the TLS handshake"
294
+ )
295
+ else:
296
+ await self._send_pending()
297
+ return
298
+
299
+ # -- the StreamReader / StreamWriter surface -------------------------
300
+
301
+ async def read(self, n: int = READ_CHUNK) -> bytes:
302
+ """Up to *n* plaintext bytes; ``b""`` at end of stream."""
303
+ while True:
304
+ try:
305
+ return self._tls.read(n)
306
+ except ssl.SSLWantReadError:
307
+ await self._send_pending()
308
+ if not await self._receive_more():
309
+ return b""
310
+ except (ssl.SSLZeroReturnError, ssl.SSLSyscallError):
311
+ return b""
312
+
313
+ def write(self, data: bytes) -> None:
314
+ """Encrypt *data* into the outgoing BIO. ``drain()`` puts it on the wire.
315
+
316
+ The loop is for a full-screen push: ``SSL_write`` reports how much it
317
+ took, and a 1.84 MB frame is not something to assume it swallows whole.
318
+ """
319
+ view = memoryview(data)
320
+ while view:
321
+ view = view[self._tls.write(view) :]
322
+
323
+ async def drain(self) -> None:
324
+ await self._send_pending()
325
+
326
+ def close(self) -> None:
327
+ # close_notify is best-effort: unwrap() wants a round trip we are not
328
+ # going to wait for on a teardown path, and the device does not care.
329
+ with contextlib.suppress(Exception):
330
+ self._tls.unwrap()
331
+ with contextlib.suppress(Exception):
332
+ data = self._outgoing.read()
333
+ if data:
334
+ self._writer.write(data)
335
+ self._writer.close()
336
+
337
+ async def wait_closed(self) -> None:
338
+ await self._writer.wait_closed()
339
+
340
+
341
+ class VisionectServer:
342
+ """Accepts device connections and drives a ``DeviceConnection`` per socket.
343
+
344
+ Args:
345
+ on_events: called with ``(connection, events)`` after every read and
346
+ every timer tick. May be sync or async.
347
+ store: the shared per-UUID state map. One is created if omitted; share
348
+ your own if you want state to outlive the server object.
349
+ config: passed to each :class:`DeviceConnection`.
350
+ host / port: where to listen.
351
+ ssl_context: enables opportunistic TLS on the **same** port. Each
352
+ connection is sniffed for a ClientHello and wrapped only if it is
353
+ one, so plaintext signs keep working while TLS signs are added.
354
+ Omit it and the listener is plaintext-only, which is the default
355
+ because the vendor's own image ships no certificate and the device
356
+ side needs TCLV 145 set before any sign will offer a ClientHello.
357
+ certfile / keyfile: a shorthand for
358
+ ``ssl_context=server_ssl_context(certfile, keyfile)``. Mutually
359
+ exclusive with *ssl_context*.
360
+ clock: seconds-valued monotonic clock. Injectable for tests; this is the
361
+ **only** place the library reads a clock.
362
+
363
+ Example:
364
+ >>> async def main():
365
+ ... async def handle(conn, events):
366
+ ... for e in events:
367
+ ... print(e)
368
+ ... server = VisionectServer(on_events=handle)
369
+ ... await server.serve_forever()
370
+ """
371
+
372
+ def __init__(
373
+ self,
374
+ *,
375
+ on_events: EventHandler,
376
+ store: DeviceStateStore | None = None,
377
+ config: ConnectionConfig | None = None,
378
+ host: str = "0.0.0.0",
379
+ port: int = DEFAULT_PORT,
380
+ ssl_context: ssl.SSLContext | None = None,
381
+ certfile: str | None = None,
382
+ keyfile: str | None = None,
383
+ clock: Callable[[], float] = time.monotonic,
384
+ ) -> None:
385
+ self.on_events = on_events
386
+ self.store = store if store is not None else DeviceStateStore()
387
+ self.config = config or ConnectionConfig()
388
+ self.host = host
389
+ self.port = port
390
+ if ssl_context is not None and certfile is not None:
391
+ raise ValueError("pass ssl_context or certfile, not both")
392
+ if ssl_context is None and certfile is not None:
393
+ ssl_context = server_ssl_context(certfile, keyfile)
394
+ self.ssl_context = ssl_context
395
+ self.clock = clock
396
+ self.stats = ServerStats()
397
+ self._server: asyncio.AbstractServer | None = None
398
+ self._connections: dict[bytes, DeviceConnection] = {}
399
+ self._writers: dict[bytes, asyncio.StreamWriter] = {}
400
+ self._listeners: list[EventHandler] = []
401
+
402
+ @property
403
+ def connections(self) -> dict[bytes, DeviceConnection]:
404
+ """Live connections keyed on the device UUID.
405
+
406
+ Keyed on the UUID and nothing else: a reconnect comes from a different
407
+ source port with its packet counter reset to 1.
408
+ """
409
+ return dict(self._connections)
410
+
411
+ def connection_for(self, device_id: bytes) -> DeviceConnection | None:
412
+ """The live connection for *device_id*, or None if it is not connected.
413
+
414
+ **None is the common case.** A battery sign is absent most of the time.
415
+ Queue work on ``store.queue(device_id)`` instead of waiting for this to
416
+ be non-None; see :class:`~pyvisionect.session.pending.PendingWork`.
417
+ """
418
+ return self._connections.get(device_id)
419
+
420
+ async def start(self) -> None:
421
+ """Bind and start accepting.
422
+
423
+ Raises:
424
+ ListenError: instead of a bare :class:`OSError`, so a caller can
425
+ branch on ``errno`` to tell "port busy" from "cannot bind that
426
+ address".
427
+ """
428
+ try:
429
+ self._server = await asyncio.start_server(
430
+ self._handle_client, self.host, self.port
431
+ )
432
+ except OSError as exc:
433
+ raise ListenError(self.host, self.port, exc) from exc
434
+ log.info("listening for Visionect devices on %s:%d", self.host, self.port)
435
+
436
+ async def serve_forever(self) -> None:
437
+ if self._server is None:
438
+ await self.start()
439
+ assert self._server is not None
440
+ async with self._server:
441
+ await self._server.serve_forever()
442
+
443
+ async def close(self, *, abort: bool = False) -> None:
444
+ """Stop accepting, close live device connections, and wait.
445
+
446
+ **The ``close_clients()`` call is load-bearing, and leaving it out
447
+ hangs forever on this hardware.** Since Python 3.12,
448
+ ``Server.wait_closed()`` waits until the server is closed *and all
449
+ active connections have finished* -- and a mains-powered Visionect sign
450
+ holds its TCP connection open permanently. So ``close()`` followed by
451
+ ``wait_closed()`` never returns, and wrapping it in
452
+ ``contextlib.suppress`` does nothing for a hang.
453
+
454
+ The ordering is the one Python's own documentation mandates:
455
+ ``close()`` *before* ``close_clients()``, "to avoid races with new
456
+ clients connecting".
457
+
458
+ There is no precedent to copy here: ``close_clients`` appears zero times
459
+ in all of Home Assistant core, because no core integration hosts a
460
+ listener for devices that hold connections open indefinitely.
461
+
462
+ Args:
463
+ abort: use ``abort_clients()`` instead of ``close_clients()``, which
464
+ drops connections without draining pending writes. Worth it on a
465
+ shutdown path, where finishing a half-written 1.84 MB frame is
466
+ not worth waiting for.
467
+ """
468
+ if self._server is None:
469
+ return
470
+ server, self._server = self._server, None
471
+ server.close()
472
+ # Python 3.13+ has both; guard anyway so the failure mode is a logged
473
+ # warning rather than an AttributeError during shutdown.
474
+ closer = getattr(server, "abort_clients" if abort else "close_clients", None)
475
+ if closer is not None:
476
+ closer()
477
+ else: # pragma: no cover - only on an unexpectedly old runtime
478
+ log.warning(
479
+ "asyncio.Server has no close_clients(); wait_closed() may hang "
480
+ "while a device holds its connection open"
481
+ )
482
+ with contextlib.suppress(Exception):
483
+ await server.wait_closed()
484
+
485
+ # --------------------------------------------------------------------
486
+
487
+ async def _peek(self, reader: asyncio.StreamReader) -> bytes:
488
+ """The first :data:`TLS_PEEK_BYTES` bytes, or fewer at EOF.
489
+
490
+ ``readexactly`` is wrong here: a connection that closes having sent
491
+ nothing is **normal** on this hardware (see
492
+ :attr:`ServerStats.silent_connections`), and that must not arrive as an
493
+ ``IncompleteReadError``.
494
+ """
495
+ head = b""
496
+ while len(head) < TLS_PEEK_BYTES:
497
+ chunk = await reader.read(TLS_PEEK_BYTES - len(head))
498
+ if not chunk:
499
+ break
500
+ head += chunk
501
+ return head
502
+
503
+ async def _handle_client(
504
+ self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
505
+ ) -> None:
506
+ peer = writer.get_extra_info("peername")
507
+ conn = DeviceConnection(store=self.store, config=self.config)
508
+ self.stats.accepted += 1
509
+ self.stats.last_accept_at = self.clock()
510
+ log.info("device connected from %s", peer)
511
+ registered: bytes | None = None
512
+ received_any = False
513
+
514
+ # The sniff, before anything else and before the timers start: this is
515
+ # the only point at which the connection's protocol is still undecided.
516
+ head = await self._peek(reader)
517
+ if looks_like_client_hello(head):
518
+ if self.ssl_context is None:
519
+ self.stats.tls_unsupported += 1
520
+ log.error(
521
+ "device %s offered a TLS ClientHello but this listener has "
522
+ "no certificate configured. The sign has TCLV 145 (TLS "
523
+ "mode) set to 1 and cannot talk to us until either a "
524
+ "certificate is configured here or 145 is set back to 0 "
525
+ "over the serial console.",
526
+ peer,
527
+ )
528
+ writer.close()
529
+ with contextlib.suppress(Exception):
530
+ await writer.wait_closed()
531
+ return
532
+ tls = _TlsStream(reader, writer, self.ssl_context, head)
533
+ try:
534
+ await tls.handshake()
535
+ except (ssl.SSLError, OSError) as exc:
536
+ self.stats.tls_failed += 1
537
+ log.warning("TLS handshake with %s failed: %s", peer, exc)
538
+ writer.close()
539
+ with contextlib.suppress(Exception):
540
+ await writer.wait_closed()
541
+ return
542
+ self.stats.tls_accepted += 1
543
+ cipher = tls.get_extra_info("ssl_object")
544
+ log.info(
545
+ "device %s completed a TLS handshake (%s)",
546
+ peer,
547
+ cipher.cipher() if cipher is not None else "?",
548
+ )
549
+ # Everything above here is bytes on the wire; everything below is
550
+ # the protocol, and it does not care which of the two it is on.
551
+ reader = writer = tls # type: ignore[assignment]
552
+ head = b""
553
+
554
+ timer_task = asyncio.create_task(self._run_timers(conn, writer))
555
+ try:
556
+ while not conn.closed:
557
+ if head:
558
+ data, head = head, b""
559
+ else:
560
+ data = await reader.read(READ_CHUNK)
561
+ if not data:
562
+ break
563
+ received_any = True
564
+ self.stats.bytes_in += len(data)
565
+ now = self.clock()
566
+ events = conn.feed_at(data, now)
567
+ if registered is None and conn.device_id is not None:
568
+ registered = conn.device_id
569
+ self.stats.identified += 1
570
+ self._connections[registered] = conn
571
+ self._writers[registered] = writer
572
+ if registered is not None:
573
+ self.stats.last_seen[registered] = now
574
+ await self._flush(conn, writer)
575
+ if events:
576
+ await self._dispatch(conn, events)
577
+ except (ConnectionResetError, asyncio.IncompleteReadError):
578
+ log.info("device %s dropped the connection", peer)
579
+ finally:
580
+ if not received_any:
581
+ # Normal, not an error: the capture shows the real sign opening
582
+ # and closing a connection carrying no protocol bytes at all.
583
+ self.stats.silent_connections += 1
584
+ if conn.closed and received_any:
585
+ self.stats.rejected += 1
586
+ timer_task.cancel()
587
+ with contextlib.suppress(asyncio.CancelledError):
588
+ await timer_task
589
+ if registered is not None and self._connections.get(registered) is conn:
590
+ del self._connections[registered]
591
+ self._writers.pop(registered, None)
592
+ writer.close()
593
+ with contextlib.suppress(Exception):
594
+ await writer.wait_closed()
595
+ log.info("device %s disconnected", peer)
596
+
597
+ async def _run_timers(
598
+ self, conn: DeviceConnection, writer: asyncio.StreamWriter
599
+ ) -> None:
600
+ """Poll ``advance()`` once a second.
601
+
602
+ A second of granularity is plenty: the shortest timer here is the
603
+ read timeout at 300 s and the watchdog at 15 min.
604
+ """
605
+ while not conn.closed:
606
+ await asyncio.sleep(1.0)
607
+ events = conn.advance(self.clock())
608
+ await self._flush(conn, writer)
609
+ if events:
610
+ await self._dispatch(conn, events)
611
+
612
+ async def _flush(
613
+ self, conn: DeviceConnection, writer: asyncio.StreamWriter
614
+ ) -> None:
615
+ data = conn.drain()
616
+ if data:
617
+ self.stats.bytes_out += len(data)
618
+ writer.write(data)
619
+ await writer.drain()
620
+
621
+ def add_listener(self, handler: EventHandler) -> Callable[[], None]:
622
+ """Also deliver every event to *handler*. Returns an unsubscribe.
623
+
624
+ ``on_events`` is the one consumer a server is constructed with, which
625
+ is right for an application but wrong for a transfer that needs to see
626
+ replies for the few minutes it runs. Listeners let such a transfer
627
+ attach and detach without the application having to route for it.
628
+
629
+ A listener that raises is unsubscribed and the exception is logged,
630
+ rather than taking down the read loop for everyone else.
631
+ """
632
+ self._listeners.append(handler)
633
+
634
+ def _remove() -> None:
635
+ try:
636
+ self._listeners.remove(handler)
637
+ except ValueError:
638
+ pass
639
+
640
+ return _remove
641
+
642
+ async def _dispatch(self, conn: DeviceConnection, events: list[Event]) -> None:
643
+ for listener in list(self._listeners):
644
+ try:
645
+ result = listener(conn, events)
646
+ if asyncio.iscoroutine(result):
647
+ await result
648
+ except Exception: # noqa: BLE001 - one listener must not break the rest
649
+ log.exception("event listener failed; unsubscribing it")
650
+ try:
651
+ self._listeners.remove(listener)
652
+ except ValueError:
653
+ pass
654
+ result = self.on_events(conn, events)
655
+ if asyncio.iscoroutine(result):
656
+ await result
657
+
658
+ async def flush(self, device_id: bytes) -> None:
659
+ """Push whatever a caller queued on a device's connection.
660
+
661
+ Call this after queueing from *outside* the read loop, e.g.::
662
+
663
+ conn = server.connection_for(uuid)
664
+ conn.send_image(frame)
665
+ await server.flush(uuid)
666
+
667
+ Queueing from inside an ``on_events`` callback needs no explicit flush;
668
+ the server drains after every callback.
669
+
670
+ Raises:
671
+ KeyError: if that UUID has no live connection.
672
+ """
673
+ conn = self._connections.get(device_id)
674
+ writer = self._writers.get(device_id)
675
+ if conn is None or writer is None:
676
+ raise KeyError(f"no live connection for {device_id.hex()}")
677
+ await self._flush(conn, writer)
678
+
679
+ # ------------------------------------------------------- file transfers
680
+
681
+ async def read_device_file(
682
+ self,
683
+ device_id: bytes,
684
+ filename: str,
685
+ length: int,
686
+ *,
687
+ chunk: int = DEVICE_FILE_READ_CHUNK,
688
+ timeout: float = DEFAULT_FILE_TIMEOUT,
689
+ attempts: int = 3,
690
+ stop_on_short: bool = False,
691
+ progress: Callable[[int, int], None] | None = None,
692
+ ) -> bytes:
693
+ """Pull *filename* off the device and return its bytes.
694
+
695
+ **This is slow.** The device answers at about 2.3 KiB/s in 1 KiB
696
+ replies, so one of the 32" sign's stored frames takes between one and
697
+ nine minutes. There is no seek opcode either, so a reply that never
698
+ arrives costs the whole transfer and the only recovery is to start
699
+ again -- which is what *attempts* buys.
700
+
701
+ Args:
702
+ device_id: the 16 UUID bytes. The device must be connected now.
703
+ filename: as the directory listing spells it, slash included.
704
+ length: bytes to read, from the listing's size column.
705
+ chunk: bytes per request; clamped to
706
+ :data:`~pyvisionect.packets.file.DEVICE_FILE_READ_CHUNK`.
707
+ timeout: seconds to wait for any one reply.
708
+ attempts: how many times to restart from offset 0 after a lost
709
+ reply.
710
+ stop_on_short: end the read at the first reply shorter than the
711
+ request. For a directory listing, not for a file.
712
+ progress: called with ``(bytes_so_far, total)`` after every reply.
713
+
714
+ Raises:
715
+ KeyError: if that UUID has no live connection.
716
+ FileReadError: if the device refused the open, or every attempt
717
+ lost a reply.
718
+ """
719
+ conn = self._connections.get(device_id)
720
+ if conn is None or device_id not in self._writers:
721
+ raise KeyError(f"no live connection for {device_id.hex()}")
722
+
723
+ seq = FileRead(filename, length, chunk=chunk, stop_on_short=stop_on_short)
724
+ woke: asyncio.Queue[int] = asyncio.Queue()
725
+
726
+ def _listen(source: DeviceConnection, events: list[Event]) -> None:
727
+ if source.device_id != device_id:
728
+ return
729
+ for event in events:
730
+ if seq.on_event(event, source):
731
+ woke.put_nowait(seq.bytes_read)
732
+
733
+ unsubscribe = self.add_listener(_listen)
734
+ try:
735
+ for attempt in range(1, max(1, attempts) + 1):
736
+ if attempt == 1:
737
+ seq.start(conn)
738
+ else:
739
+ log.info(
740
+ "restarting the read of %s from offset 0 (attempt %d/%d)",
741
+ filename,
742
+ attempt,
743
+ attempts,
744
+ )
745
+ seq.restart(conn)
746
+ await self.flush(device_id)
747
+ lost = False
748
+ while seq.awaiting_reply:
749
+ try:
750
+ seen = await asyncio.wait_for(woke.get(), timeout)
751
+ except asyncio.TimeoutError:
752
+ lost = True
753
+ break
754
+ if progress is not None:
755
+ progress(seen, length)
756
+ await self.flush(device_id)
757
+ if seq.failed:
758
+ raise FileReadError(seq.error or f"reading {filename} failed")
759
+ if seq.done:
760
+ return seq.data
761
+ if lost:
762
+ # Close the handle so the next attempt opens cleanly; the
763
+ # device may or may not answer, and either is fine.
764
+ conn.file_close()
765
+ with contextlib.suppress(Exception):
766
+ await self.flush(device_id)
767
+ raise FileReadError(
768
+ f"gave up reading {filename} after {attempts} attempts; got "
769
+ f"{seq.bytes_read} of {length} bytes. There is no seek opcode, "
770
+ "so a lost reply means restarting from the beginning."
771
+ )
772
+ finally:
773
+ unsubscribe()
774
+
775
+ async def list_device_files(
776
+ self,
777
+ device_id: bytes,
778
+ *,
779
+ timeout: float = DEFAULT_FILE_TIMEOUT,
780
+ ) -> dict[str, FileListEntry]:
781
+ """The device's directory listing, parsed.
782
+
783
+ Cheap -- one open, one read, one close, well under a second -- so this
784
+ is the right thing to call before deciding whether a file is worth
785
+ pulling.
786
+ """
787
+ raw = await self.read_device_file(
788
+ device_id,
789
+ FILE_LIST_PATH,
790
+ FILE_LIST_LENGTH,
791
+ timeout=timeout,
792
+ attempts=1,
793
+ stop_on_short=True,
794
+ )
795
+ return parse_file_listing(raw)