flashforge-python-api 1.6.0__py3-none-any.whl → 3.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 (70) hide show
  1. flashforge/__init__.py +137 -56
  2. flashforge/_removed.py +65 -0
  3. flashforge/api/__init__.py +12 -18
  4. flashforge/api/constants/__init__.py +11 -11
  5. flashforge/api/constants/commands.py +18 -15
  6. flashforge/api/constants/endpoints.py +11 -11
  7. flashforge/api/misc/__init__.py +8 -8
  8. flashforge/api/network/__init__.py +11 -11
  9. flashforge/api/network/utils.py +71 -71
  10. flashforge/backends/__init__.py +80 -0
  11. flashforge/backends/connect.py +275 -0
  12. flashforge/backends/creator5_backend.py +191 -0
  13. flashforge/backends/dual_api_backend.py +170 -0
  14. flashforge/backends/dual_api_models.py +145 -0
  15. flashforge/backends/http_core.py +431 -0
  16. flashforge/backends/http_printer_backend.py +254 -0
  17. flashforge/backends/legacy_backend.py +436 -0
  18. flashforge/backends/printer_backend.py +217 -0
  19. flashforge/backends/types.py +125 -0
  20. flashforge/capabilities/__init__.py +98 -0
  21. flashforge/capabilities/models.py +67 -0
  22. flashforge/capabilities/palettes/__init__.py +28 -0
  23. flashforge/capabilities/palettes/ad5x_palette.py +70 -0
  24. flashforge/capabilities/palettes/creator5_palette.py +78 -0
  25. flashforge/capabilities/palettes/palette.py +54 -0
  26. flashforge/{api/controls/creator5_palette.py → capabilities/palettes/palette_snap.py} +226 -258
  27. flashforge/capabilities/printer_capabilities.py +145 -0
  28. flashforge/capabilities/registry.py +125 -0
  29. flashforge/capabilities/resolve_model.py +61 -0
  30. flashforge/discovery/__init__.py +39 -39
  31. flashforge/discovery/discovery.py +150 -77
  32. flashforge/exceptions.py +90 -51
  33. flashforge/models/__init__.py +52 -55
  34. flashforge/models/machine_info.py +540 -543
  35. flashforge/{api/controls/info.py → models/machine_info_parser.py} +35 -242
  36. flashforge/models/responses.py +119 -254
  37. flashforge/status/__init__.py +43 -0
  38. flashforge/status/printer_snapshot.py +396 -0
  39. flashforge/tcp/__init__.py +55 -54
  40. flashforge/tcp/a3_client.py +427 -427
  41. flashforge/tcp/a4_client.py +304 -304
  42. flashforge/tcp/ff_client.py +609 -590
  43. flashforge/tcp/gcode/__init__.py +15 -13
  44. flashforge/tcp/gcode/a3_gcode_controller.py +109 -109
  45. flashforge/tcp/gcode/gcode_controller.py +292 -308
  46. flashforge/tcp/gcode/gcodes.py +81 -99
  47. flashforge/tcp/gcode/legacy_gcode_controller.py +56 -0
  48. flashforge/tcp/parsers/__init__.py +27 -27
  49. flashforge/tcp/parsers/endstop_status.py +248 -248
  50. flashforge/tcp/parsers/location_info.py +83 -83
  51. flashforge/tcp/parsers/print_status.py +180 -180
  52. flashforge/tcp/parsers/printer_info.py +146 -146
  53. flashforge/tcp/parsers/temp_info.py +218 -218
  54. flashforge/tcp/parsers/thumbnail_info.py +274 -274
  55. flashforge/tcp/tcp_client.py +52 -12
  56. flashforge/threemf/__init__.py +40 -40
  57. flashforge/threemf/parser.py +560 -560
  58. flashforge/threemf/warnings.py +58 -58
  59. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/METADATA +46 -47
  60. flashforge_python_api-3.1.0.dist-info/RECORD +69 -0
  61. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/WHEEL +1 -1
  62. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/licenses/LICENSE +21 -21
  63. flashforge/api/controls/__init__.py +0 -17
  64. flashforge/api/controls/control.py +0 -413
  65. flashforge/api/controls/files.py +0 -210
  66. flashforge/api/controls/job_control.py +0 -896
  67. flashforge/api/controls/temp_control.py +0 -309
  68. flashforge/client.py +0 -609
  69. flashforge_python_api-1.6.0.dist-info/RECORD +0 -52
  70. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,125 @@
1
+ """
2
+ Static per-model facts and the rules that decide how far each fact can be trusted.
3
+
4
+ Trust rules (each field has exactly one source):
5
+
6
+ - ``model``: the model table is the truth. The printer's ``/product`` flags are ignored.
7
+ - ``printer``: the printer reports it. The model table does not say.
8
+
9
+ Live tests on 2026-11-14 showed that the Creator 5 series sends fixed ``/product``
10
+ values. Its chamber flag is set on the plain Creator 5, which has no chamber heater.
11
+ Both models ignore the filtration command. So chamber and filtration come from the
12
+ model table only.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Literal
19
+
20
+ from .models import BackendFamily, PrinterModelId
21
+
22
+ TrustSource = Literal["model", "printer"]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ModelSpec:
27
+ """Static facts about one printer model."""
28
+
29
+ id: PrinterModelId
30
+ display_name: str
31
+ family: BackendFamily
32
+ #: The printer runs a TCP command server on port 8899.
33
+ tcp_command_channel: bool
34
+ #: Status comes from the HTTP ``/detail`` endpoint. When False, status comes over TCP.
35
+ http_status: bool
36
+ #: The field values were confirmed on real hardware. False for the Creator 5 series.
37
+ hardware_verified: bool
38
+ #: Number of tool heads.
39
+ tool_count: int = 1
40
+ #: Number of material-station slots. 0 when there is no station.
41
+ material_station_slots: int = 0
42
+ #: The station can load and unload filament (``ms_cmd``). AD5X only.
43
+ material_station_load_unload: bool = False
44
+ #: Heated chamber with API control. Creator 5 Pro only.
45
+ chamber_heater: bool = False
46
+ #: Air filtration with API control. Adventurer 5M Pro only.
47
+ filtration: bool = False
48
+ #: A real door sensor. Creator 5 Pro only. On other models the door flag is cosmetic.
49
+ door_sensor: bool = False
50
+ #: An air-quality (TVOC) sensor that the API reads (``/detail`` ``tvoc``). Adventurer 5M Pro
51
+ #: only. The base 5M and the Creator 5 series always report 0.
52
+ air_quality_sensor: bool = False
53
+
54
+
55
+ #: Trust rule per capability field. A field listed as ``model`` never reads the printer flag.
56
+ FIELD_TRUST: dict[str, TrustSource] = {
57
+ "chamber_heater": "model",
58
+ "filtration": "model",
59
+ "door_sensor": "model",
60
+ "air_quality_sensor": "model",
61
+ "material_station": "model",
62
+ "led": "model",
63
+ "camera": "printer",
64
+ }
65
+
66
+ _M = PrinterModelId
67
+ _F = BackendFamily
68
+
69
+ #: The registry. One entry per model.
70
+ MODEL_REGISTRY: dict[PrinterModelId, ModelSpec] = {
71
+ _M.ADVENTURER_5M: ModelSpec(_M.ADVENTURER_5M, "Adventurer 5M", _F.DUAL_API, True, True, True),
72
+ _M.ADVENTURER_5M_PRO: ModelSpec(
73
+ _M.ADVENTURER_5M_PRO,
74
+ "Adventurer 5M Pro",
75
+ _F.DUAL_API,
76
+ True,
77
+ True,
78
+ True,
79
+ filtration=True,
80
+ air_quality_sensor=True,
81
+ ),
82
+ _M.AD5X: ModelSpec(
83
+ _M.AD5X,
84
+ "AD5X",
85
+ _F.DUAL_API,
86
+ True,
87
+ True,
88
+ True,
89
+ material_station_slots=4,
90
+ material_station_load_unload=True,
91
+ ),
92
+ _M.CREATOR_5: ModelSpec(
93
+ _M.CREATOR_5,
94
+ "Creator 5",
95
+ _F.HTTP_ONLY,
96
+ False,
97
+ True,
98
+ False,
99
+ tool_count=4,
100
+ material_station_slots=4,
101
+ ),
102
+ _M.CREATOR_5_PRO: ModelSpec(
103
+ _M.CREATOR_5_PRO,
104
+ "Creator 5 Pro",
105
+ _F.HTTP_ONLY,
106
+ False,
107
+ True,
108
+ False,
109
+ tool_count=4,
110
+ material_station_slots=4,
111
+ chamber_heater=True,
112
+ door_sensor=True,
113
+ ),
114
+ _M.ADVENTURER_4: ModelSpec(_M.ADVENTURER_4, "Adventurer 4", _F.LEGACY, True, False, False),
115
+ _M.ADVENTURER_3: ModelSpec(_M.ADVENTURER_3, "Adventurer 3", _F.LEGACY, True, False, False),
116
+ _M.GENERIC_LEGACY: ModelSpec(
117
+ _M.GENERIC_LEGACY, "FlashForge printer (legacy)", _F.LEGACY, True, False, False
118
+ ),
119
+ _M.UNKNOWN: ModelSpec(_M.UNKNOWN, "Unknown printer", _F.UNKNOWN, False, False, False),
120
+ }
121
+
122
+
123
+ def get_model_spec(model: PrinterModelId) -> ModelSpec:
124
+ """Returns the spec for a model."""
125
+ return MODEL_REGISTRY[PrinterModelId(model)]
@@ -0,0 +1,61 @@
1
+ """
2
+ Resolves a printer model from the evidence the library has.
3
+
4
+ One function serves discovery, a first connection and a reconnect. Evidence is used in
5
+ this order:
6
+
7
+ 1. PID (discovery USB product ID, or ``/detail`` ``pid``). Firmware-set; users cannot change it.
8
+ 2. TCP ``M115`` machine type string (firmware-set).
9
+ 3. The factory model name (``/detail`` ``model``), then the printer name as a last resort.
10
+ Users can rename a printer.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from .models import PrinterModelId, model_from_pid
16
+
17
+
18
+ def resolve_model(
19
+ *,
20
+ pid: int | None = None,
21
+ machine_type: str | None = None,
22
+ name: str | None = None,
23
+ model_name: str | None = None,
24
+ has_material_station: bool = False,
25
+ ) -> PrinterModelId:
26
+ """Resolves the model. Returns ``UNKNOWN`` when nothing matches."""
27
+ by_pid = model_from_pid(pid)
28
+ if by_pid is not None:
29
+ return by_pid
30
+ if machine_type:
31
+ return model_from_machine_type(machine_type)
32
+ return _model_from_name(model_name or name or "", has_material_station)
33
+
34
+
35
+ def model_from_machine_type(machine_type: str) -> PrinterModelId:
36
+ """Resolves a legacy model from a TCP ``M115`` machine type. Unknown types are generic."""
37
+ upper = machine_type.upper()
38
+ if "ADVENTURER 3" in upper or "ADVENTURER III" in upper:
39
+ return PrinterModelId.ADVENTURER_3
40
+ if "ADVENTURER 4" in upper:
41
+ return PrinterModelId.ADVENTURER_4
42
+ return PrinterModelId.GENERIC_LEGACY
43
+
44
+
45
+ def _model_from_name(name: str, has_material_station: bool) -> PrinterModelId:
46
+ upper = name.upper()
47
+ if "CREATOR 5 PRO" in upper:
48
+ return PrinterModelId.CREATOR_5_PRO
49
+ if "CREATOR 5" in upper:
50
+ return PrinterModelId.CREATOR_5
51
+ if has_material_station or upper == "AD5X" or "5X" in upper:
52
+ return PrinterModelId.AD5X
53
+ if "ADVENTURER 4" in upper or "ADVENTURER4" in upper or "AD4" in upper:
54
+ return PrinterModelId.ADVENTURER_4
55
+ if "ADVENTURER 3" in upper or "ADVENTURER3" in upper or "AD3" in upper:
56
+ return PrinterModelId.ADVENTURER_3
57
+ if "PRO" in upper:
58
+ return PrinterModelId.ADVENTURER_5M_PRO
59
+ if "5M" in upper:
60
+ return PrinterModelId.ADVENTURER_5M
61
+ return PrinterModelId.UNKNOWN
@@ -1,39 +1,39 @@
1
- """
2
- FlashForge Python API - Discovery Package
3
-
4
- UDP-based printer discovery for finding FlashForge printers on the local network.
5
- """
6
-
7
- from .discovery import (
8
- DiscoveredPrinter,
9
- DiscoveryError,
10
- DiscoveryMonitor,
11
- DiscoveryOptions,
12
- DiscoveryProtocol,
13
- DiscoveryTimeoutError,
14
- FlashForgePrinter,
15
- FlashForgePrinterDiscovery,
16
- InvalidResponseError,
17
- PrinterDiscovery,
18
- PrinterModel,
19
- PrinterStatus,
20
- SocketCreationError,
21
- main,
22
- )
23
-
24
- __all__ = [
25
- "PrinterDiscovery",
26
- "DiscoveredPrinter",
27
- "DiscoveryOptions",
28
- "PrinterModel",
29
- "DiscoveryProtocol",
30
- "PrinterStatus",
31
- "DiscoveryMonitor",
32
- "DiscoveryError",
33
- "InvalidResponseError",
34
- "SocketCreationError",
35
- "DiscoveryTimeoutError",
36
- "FlashForgePrinter",
37
- "FlashForgePrinterDiscovery",
38
- "main",
39
- ]
1
+ """
2
+ FlashForge Python API - Discovery Package
3
+
4
+ UDP-based printer discovery for finding FlashForge printers on the local network.
5
+ """
6
+
7
+ from .discovery import (
8
+ DiscoveredPrinter,
9
+ DiscoveryError,
10
+ DiscoveryMonitor,
11
+ DiscoveryOptions,
12
+ DiscoveryProtocol,
13
+ DiscoveryTimeoutError,
14
+ FlashForgePrinter,
15
+ FlashForgePrinterDiscovery,
16
+ InvalidResponseError,
17
+ PrinterDiscovery,
18
+ PrinterModelId,
19
+ PrinterStatus,
20
+ SocketCreationError,
21
+ main,
22
+ )
23
+
24
+ __all__ = [
25
+ "PrinterDiscovery",
26
+ "DiscoveredPrinter",
27
+ "DiscoveryOptions",
28
+ "PrinterModelId",
29
+ "DiscoveryProtocol",
30
+ "PrinterStatus",
31
+ "DiscoveryMonitor",
32
+ "DiscoveryError",
33
+ "InvalidResponseError",
34
+ "SocketCreationError",
35
+ "DiscoveryTimeoutError",
36
+ "FlashForgePrinter",
37
+ "FlashForgePrinterDiscovery",
38
+ "main",
39
+ ]
@@ -14,18 +14,18 @@ from typing import Any
14
14
 
15
15
  import ifaddr
16
16
 
17
+ from ..capabilities.models import BackendFamily, PrinterModelId, model_from_pid
18
+ from ..capabilities.registry import get_model_spec
19
+
17
20
  logger = logging.getLogger(__name__)
18
21
 
19
22
  MULTICAST_ADDRESS = "225.0.0.9"
23
+ #: Probed on every pass, like the TypeScript library: an emulator or bridge on this host
24
+ #: does not hear its own machine's broadcast.
25
+ LOOPBACK_ADDRESS = "127.0.0.1"
20
26
  MODERN_PROTOCOL_SIZE = 276
21
27
  LEGACY_PROTOCOL_SIZE = 140
22
28
 
23
- LEGACY_PRODUCT_IDS = {
24
- "Adventurer3": 0x0008,
25
- "Adventurer4Lite": 0x0016,
26
- "Adventurer4Pro": 0x001E,
27
- }
28
-
29
29
 
30
30
  class DiscoveryError(Exception):
31
31
  """Base error for discovery-related failures."""
@@ -59,33 +59,6 @@ class DiscoveryTimeoutError(DiscoveryError):
59
59
  self.timeout_ms = timeout_ms
60
60
 
61
61
 
62
- class PrinterModel(StrEnum):
63
- """Known FlashForge printer models discoverable on LAN."""
64
-
65
- AD5X = "AD5X"
66
- ADVENTURER_5M = "Adventurer5M"
67
- ADVENTURER_5M_PRO = "Adventurer5MPro"
68
- ADVENTURER_4 = "Adventurer4"
69
- ADVENTURER_3 = "Adventurer3"
70
- CREATOR_5 = "Creator5"
71
- CREATOR_5_PRO = "Creator5Pro"
72
- UNKNOWN = "Unknown"
73
-
74
-
75
- # Canonical USB Product IDs (discovery packet offset 0x88) for modern printers.
76
- # Same value space as the firmware /detail `pid` field and the FlashForge
77
- # update-checker keys, so it is the authoritative model discriminator -- unlike
78
- # `product_type` (0x5A02), which only identifies the 5M *family* and cannot tell
79
- # 5M / 5M Pro / AD5X / Creator 5 apart.
80
- MODERN_PRODUCT_IDS = {
81
- 0x0023: PrinterModel.ADVENTURER_5M,
82
- 0x0024: PrinterModel.ADVENTURER_5M_PRO,
83
- 0x0026: PrinterModel.AD5X,
84
- 0x0028: PrinterModel.CREATOR_5,
85
- 0x0029: PrinterModel.CREATOR_5_PRO,
86
- }
87
-
88
-
89
62
  class DiscoveryProtocol(StrEnum):
90
63
  """Discovery response wire formats."""
91
64
 
@@ -106,7 +79,8 @@ class PrinterStatus(IntEnum):
106
79
  class DiscoveredPrinter:
107
80
  """Typed printer metadata returned by universal discovery."""
108
81
 
109
- model: PrinterModel
82
+ #: Resolved model (USB product ID first, then name). UNKNOWN when not recognised.
83
+ model: PrinterModelId
110
84
  protocol_format: DiscoveryProtocol
111
85
  name: str
112
86
  ip_address: str
@@ -163,22 +137,69 @@ class FlashForgePrinter:
163
137
  )
164
138
 
165
139
 
166
- class _DiscoveryDatagramProtocol(asyncio.DatagramProtocol):
167
- """Asyncio protocol used to push UDP datagrams into an async queue."""
140
+ class _DiscoverySocket:
141
+ """
142
+ The discovery UDP socket, driven with ``loop.sock_recvfrom`` instead of an asyncio
143
+ datagram transport. It offers the transport methods discovery uses (``sendto``,
144
+ ``close``, ``get_extra_info``).
145
+
146
+ Why not ``loop.create_datagram_endpoint``:
147
+
148
+ - Discovery packets are empty, and on Python 3.11 and 3.12 a datagram transport's
149
+ ``sendto`` silently drops empty data. Discovery then sends nothing and finds
150
+ nothing. Python 3.13 sends it.
151
+ - On Windows a send to a closed port comes back as an ICMP "port unreachable", which
152
+ the next receive reports as ``ConnectionResetError``. The proactor transport stops
153
+ reading after that error. Here it is skipped and reading goes on.
154
+ - A send to an unreachable address (for example the broadcast address of a
155
+ disconnected adapter) fails for that address only.
156
+ """
168
157
 
169
158
  def __init__(
170
159
  self,
160
+ sock: socket.socket,
171
161
  message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
172
162
  error_queue: asyncio.Queue[Exception],
173
163
  ) -> None:
174
- self.message_queue = message_queue
175
- self.error_queue = error_queue
164
+ self._sock = sock
165
+ self._message_queue = message_queue
166
+ self._error_queue = error_queue
167
+ self._closed = False
168
+ self._reader = asyncio.get_running_loop().create_task(self._read_loop())
169
+
170
+ async def _read_loop(self) -> None:
171
+ loop = asyncio.get_running_loop()
172
+ while not self._closed:
173
+ try:
174
+ data, addr = await loop.sock_recvfrom(self._sock, 4096)
175
+ except ConnectionResetError:
176
+ continue # Windows: ICMP "port unreachable" from an earlier send
177
+ except asyncio.CancelledError:
178
+ raise
179
+ except OSError as error:
180
+ if self._sock.fileno() == -1:
181
+ return # closed
182
+ self._error_queue.put_nowait(error)
183
+ await asyncio.sleep(0.05)
184
+ continue
185
+ self._message_queue.put_nowait((data, addr))
186
+
187
+ def sendto(self, data: bytes, addr: tuple[str, int]) -> None:
188
+ """Send one datagram (empty data too). Raises OSError for that address only."""
189
+ try:
190
+ self._sock.sendto(data, addr)
191
+ except BlockingIOError:
192
+ logger.debug("Discovery: send buffer full, skipped %s:%s", addr[0], addr[1])
176
193
 
177
- def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
178
- self.message_queue.put_nowait((data, addr))
194
+ def get_extra_info(self, name: str, default: Any = None) -> Any:
195
+ return self._sock if name == "socket" else default
179
196
 
180
- def error_received(self, exc: Exception) -> None:
181
- self.error_queue.put_nowait(exc)
197
+ def close(self) -> None:
198
+ if self._closed:
199
+ return
200
+ self._closed = True
201
+ self._reader.cancel()
202
+ self._sock.close()
182
203
 
183
204
 
184
205
  class DiscoveryMonitor:
@@ -192,7 +213,7 @@ class DiscoveryMonitor:
192
213
  "end": [],
193
214
  "error": [],
194
215
  }
195
- self._transport: asyncio.DatagramTransport | None = None
216
+ self._transport: _DiscoverySocket | None = None
196
217
  self._task = asyncio.create_task(self._run())
197
218
  self._stopped = False
198
219
  self._end_emitted = False
@@ -299,7 +320,7 @@ class PrinterDiscovery:
299
320
  for attempt in range(config.max_retries):
300
321
  message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]] = asyncio.Queue()
301
322
  error_queue: asyncio.Queue[Exception] = asyncio.Queue()
302
- transport: asyncio.DatagramTransport | None = None
323
+ transport: _DiscoverySocket | None = None
303
324
  try:
304
325
  transport, _ = await self._create_endpoint(message_queue, error_queue)
305
326
  self._send_discovery_packets(transport, config)
@@ -324,6 +345,49 @@ class PrinterDiscovery:
324
345
 
325
346
  return list(printers.values())
326
347
 
348
+ async def probe(
349
+ self,
350
+ ip_address: str,
351
+ timeout_ms: int = 2500,
352
+ ports: list[int] | None = None,
353
+ ) -> DiscoveredPrinter | None:
354
+ """
355
+ Ask one address directly (unicast) what printer it is.
356
+
357
+ For a printer the broadcast does not reach (another subnet, a VPN, a firewall that
358
+ drops answers to a broadcast) when the user knows its IP address. Sends the same
359
+ empty discovery packet to each port and returns the first valid answer from that
360
+ address, or None.
361
+ """
362
+ message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]] = asyncio.Queue()
363
+ transport, _ = await self._create_endpoint(message_queue, asyncio.Queue())
364
+ try:
365
+ loop = asyncio.get_running_loop()
366
+ deadline = loop.time() + timeout_ms / 1000.0
367
+ resend_at = loop.time()
368
+ while loop.time() < deadline:
369
+ if loop.time() >= resend_at:
370
+ for port in ports or DiscoveryOptions().ports:
371
+ try:
372
+ transport.sendto(b"", (ip_address, port))
373
+ except OSError as error:
374
+ logger.debug(
375
+ "Discovery: probe %s:%s failed - %s", ip_address, port, error
376
+ )
377
+ resend_at = loop.time() + timeout_ms / 2000.0
378
+ try:
379
+ data, addr = await asyncio.wait_for(message_queue.get(), timeout=0.1)
380
+ except TimeoutError:
381
+ continue
382
+ if addr[0] != ip_address:
383
+ continue
384
+ printer = self.parse_discovery_response(data, addr[0])
385
+ if printer is not None:
386
+ return printer
387
+ return None
388
+ finally:
389
+ transport.close()
390
+
327
391
  def monitor(self, options: DiscoveryOptions | None = None) -> DiscoveryMonitor:
328
392
  """Create an event-based continuous discovery monitor."""
329
393
  return DiscoveryMonitor(self, options or DiscoveryOptions())
@@ -332,17 +396,18 @@ class PrinterDiscovery:
332
396
  self,
333
397
  message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
334
398
  error_queue: asyncio.Queue[Exception],
335
- ) -> tuple[asyncio.DatagramTransport, _DiscoveryDatagramProtocol]:
336
- loop = asyncio.get_running_loop()
399
+ ) -> tuple[_DiscoverySocket, None]:
400
+ sock: socket.socket | None = None
337
401
  try:
338
- transport, protocol = await loop.create_datagram_endpoint(
339
- lambda: _DiscoveryDatagramProtocol(message_queue, error_queue),
340
- local_addr=("0.0.0.0", 0),
341
- allow_broadcast=True,
342
- )
402
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
403
+ sock.setblocking(False)
404
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
405
+ sock.bind(("0.0.0.0", 0))
343
406
  except Exception as error:
407
+ if sock is not None:
408
+ sock.close()
344
409
  raise SocketCreationError(str(error)) from error
345
- return transport, protocol
410
+ return _DiscoverySocket(sock, message_queue, error_queue), None
346
411
 
347
412
  async def _receive_responses(
348
413
  self,
@@ -380,7 +445,7 @@ class PrinterDiscovery:
380
445
 
381
446
  def _send_discovery_packets(
382
447
  self,
383
- transport: asyncio.DatagramTransport,
448
+ transport: _DiscoverySocket,
384
449
  options: DiscoveryOptions,
385
450
  ) -> None:
386
451
  packet = b""
@@ -406,7 +471,8 @@ class PrinterDiscovery:
406
471
  try:
407
472
  transport.sendto(packet, (address, port))
408
473
  except Exception as error:
409
- logger.warning(
474
+ # A disconnected adapter's broadcast address is unreachable.
475
+ logger.debug(
410
476
  "Discovery: Failed to send broadcast to %s:%s - %s",
411
477
  address,
412
478
  port,
@@ -423,6 +489,17 @@ class PrinterDiscovery:
423
489
  error,
424
490
  )
425
491
 
492
+ for port in options.ports:
493
+ try:
494
+ transport.sendto(packet, (LOOPBACK_ADDRESS, port))
495
+ except Exception as error:
496
+ logger.debug(
497
+ "Discovery: Failed to send to loopback %s:%s - %s",
498
+ LOOPBACK_ADDRESS,
499
+ port,
500
+ error,
501
+ )
502
+
426
503
  def parse_discovery_response(
427
504
  self,
428
505
  buffer: bytes,
@@ -505,7 +582,7 @@ class PrinterDiscovery:
505
582
  name: str,
506
583
  product_type: int,
507
584
  product_id: int | None = None,
508
- ) -> PrinterModel:
585
+ ) -> PrinterModelId:
509
586
  """Detect a modern printer model from discovery metadata.
510
587
 
511
588
  Resolution order:
@@ -516,8 +593,9 @@ class PrinterDiscovery:
516
593
  3. Name heuristics -- last resort.
517
594
  """
518
595
  # Product ID is authoritative (firmware-set, not user-mutable).
519
- if product_id is not None and product_id in MODERN_PRODUCT_IDS:
520
- return MODERN_PRODUCT_IDS[product_id]
596
+ by_pid = model_from_pid(product_id)
597
+ if by_pid is not None and get_model_spec(by_pid).family != BackendFamily.LEGACY:
598
+ return by_pid
521
599
 
522
600
  upper_name = name.upper()
523
601
 
@@ -525,41 +603,36 @@ class PrinterDiscovery:
525
603
  # need the name to separate base from Pro.
526
604
  if product_type == 0x5A02:
527
605
  if upper_name == "AD5X":
528
- return PrinterModel.AD5X
606
+ return PrinterModelId.AD5X
529
607
  if "PRO" in upper_name:
530
- return PrinterModel.ADVENTURER_5M_PRO
531
- return PrinterModel.ADVENTURER_5M
608
+ return PrinterModelId.ADVENTURER_5M_PRO
609
+ return PrinterModelId.ADVENTURER_5M
532
610
 
533
611
  if upper_name == "AD5X":
534
- return PrinterModel.AD5X
612
+ return PrinterModelId.AD5X
535
613
 
536
614
  if "ADVENTURER 5M" in upper_name or "AD5M" in upper_name:
537
615
  if "PRO" in upper_name:
538
- return PrinterModel.ADVENTURER_5M_PRO
539
- return PrinterModel.ADVENTURER_5M
616
+ return PrinterModelId.ADVENTURER_5M_PRO
617
+ return PrinterModelId.ADVENTURER_5M
540
618
 
541
- return PrinterModel.UNKNOWN
619
+ return PrinterModelId.UNKNOWN
542
620
 
543
- def detect_legacy_model(self, name: str, product_id: int | None = None) -> PrinterModel:
621
+ def detect_legacy_model(self, name: str, product_id: int | None = None) -> PrinterModelId:
544
622
  """Detect a legacy printer model from discovery metadata."""
545
623
  upper_name = name.upper()
546
624
 
547
625
  if "ADVENTURER 4" in upper_name or "ADVENTURER4" in upper_name or "AD4" in upper_name:
548
- return PrinterModel.ADVENTURER_4
626
+ return PrinterModelId.ADVENTURER_4
549
627
 
550
628
  if "ADVENTURER 3" in upper_name or "ADVENTURER3" in upper_name or "AD3" in upper_name:
551
- return PrinterModel.ADVENTURER_3
552
-
553
- if product_id in {
554
- LEGACY_PRODUCT_IDS["Adventurer4Lite"],
555
- LEGACY_PRODUCT_IDS["Adventurer4Pro"],
556
- }:
557
- return PrinterModel.ADVENTURER_4
629
+ return PrinterModelId.ADVENTURER_3
558
630
 
559
- if product_id == LEGACY_PRODUCT_IDS["Adventurer3"]:
560
- return PrinterModel.ADVENTURER_3
631
+ by_pid = model_from_pid(product_id)
632
+ if by_pid is not None and get_model_spec(by_pid).family == BackendFamily.LEGACY:
633
+ return by_pid
561
634
 
562
- return PrinterModel.UNKNOWN
635
+ return PrinterModelId.UNKNOWN
563
636
 
564
637
  def map_status_code(self, status_code: int) -> PrinterStatus:
565
638
  """Map discovery status codes to the typed printer status enum."""
@@ -616,7 +689,7 @@ class PrinterDiscovery:
616
689
  except Exception:
617
690
  return None
618
691
 
619
- def _join_multicast_group(self, transport: asyncio.DatagramTransport) -> None:
692
+ def _join_multicast_group(self, transport: _DiscoverySocket) -> None:
620
693
  """Join the discovery multicast group if the OS/network stack allows it."""
621
694
  get_extra_info = getattr(transport, "get_extra_info", None)
622
695
  if get_extra_info is None: