flashforge-python-api 3.0.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.
@@ -1,730 +1,836 @@
1
- """
2
- Universal FlashForge printer discovery using UDP broadcast and multicast.
3
- """
4
-
5
- from __future__ import annotations
6
-
7
- import asyncio
8
- import logging
9
- import socket
10
- from collections.abc import Callable
11
- from dataclasses import dataclass, field
12
- from enum import IntEnum, StrEnum
13
- from typing import Any
14
-
15
- import ifaddr
16
-
17
- from ..capabilities.models import BackendFamily, PrinterModelId, model_from_pid
18
- from ..capabilities.registry import get_model_spec
19
-
20
- logger = logging.getLogger(__name__)
21
-
22
- MULTICAST_ADDRESS = "225.0.0.9"
23
- MODERN_PROTOCOL_SIZE = 276
24
- LEGACY_PROTOCOL_SIZE = 140
25
-
26
-
27
- class DiscoveryError(Exception):
28
- """Base error for discovery-related failures."""
29
-
30
- def __init__(self, message: str, code: str) -> None:
31
- super().__init__(message)
32
- self.code = code
33
-
34
-
35
- class InvalidResponseError(DiscoveryError):
36
- """Raised when a discovery response has an unexpected size."""
37
-
38
- def __init__(self, size: int, address: str) -> None:
39
- super().__init__(f"Invalid response size: {size} bytes from {address}", "INVALID_RESPONSE")
40
- self.response_size = size
41
- self.address = address
42
-
43
-
44
- class SocketCreationError(DiscoveryError):
45
- """Raised when a UDP discovery socket cannot be created."""
46
-
47
- def __init__(self, message: str) -> None:
48
- super().__init__(message, "SOCKET_CREATION_FAILED")
49
-
50
-
51
- class DiscoveryTimeoutError(DiscoveryError):
52
- """Raised when discovery times out without any responses."""
53
-
54
- def __init__(self, timeout_ms: int) -> None:
55
- super().__init__(f"Discovery timeout after {timeout_ms}ms", "DISCOVERY_TIMEOUT")
56
- self.timeout_ms = timeout_ms
57
-
58
-
59
- class DiscoveryProtocol(StrEnum):
60
- """Discovery response wire formats."""
61
-
62
- MODERN = "modern"
63
- LEGACY = "legacy"
64
-
65
-
66
- class PrinterStatus(IntEnum):
67
- """Printer status reported via UDP discovery."""
68
-
69
- READY = 0
70
- BUSY = 1
71
- ERROR = 2
72
- UNKNOWN = 3
73
-
74
-
75
- @dataclass(slots=True)
76
- class DiscoveredPrinter:
77
- """Typed printer metadata returned by universal discovery."""
78
-
79
- #: Resolved model (USB product ID first, then name). UNKNOWN when not recognised.
80
- model: PrinterModelId
81
- protocol_format: DiscoveryProtocol
82
- name: str
83
- ip_address: str
84
- command_port: int
85
- serial_number: str | None = None
86
- event_port: int | None = None
87
- vendor_id: int | None = None
88
- product_id: int | None = None
89
- product_type: int | None = None
90
- status_code: int | None = None
91
- status: PrinterStatus | None = None
92
-
93
-
94
- @dataclass(slots=True)
95
- class DiscoveryOptions:
96
- """Configuration options for printer discovery."""
97
-
98
- timeout: int = 10000
99
- idle_timeout: int = 1500
100
- max_retries: int = 3
101
- use_multicast: bool = True
102
- use_broadcast: bool = True
103
- ports: list[int] = field(default_factory=lambda: [8899, 19000, 48899])
104
-
105
-
106
- @dataclass(slots=True)
107
- class FlashForgePrinter:
108
- """
109
- Backward-compatible legacy discovery result.
110
-
111
- This keeps the historical Python surface used by ff-5mp-hass while the richer
112
- DiscoveredPrinter metadata is exposed via PrinterDiscovery.
113
- """
114
-
115
- name: str = ""
116
- serial_number: str = ""
117
- ip_address: str = ""
118
-
119
- @classmethod
120
- def from_discovered_printer(cls, printer: DiscoveredPrinter) -> FlashForgePrinter:
121
- return cls(
122
- name=printer.name,
123
- serial_number=printer.serial_number or "",
124
- ip_address=printer.ip_address,
125
- )
126
-
127
- def __str__(self) -> str:
128
- return f"Name: {self.name}, Serial: {self.serial_number}, IP: {self.ip_address}"
129
-
130
- def __repr__(self) -> str:
131
- return (
132
- "FlashForgePrinter("
133
- f"name='{self.name}', serial_number='{self.serial_number}', ip_address='{self.ip_address}')"
134
- )
135
-
136
-
137
- class _DiscoveryDatagramProtocol(asyncio.DatagramProtocol):
138
- """Asyncio protocol used to push UDP datagrams into an async queue."""
139
-
140
- def __init__(
141
- self,
142
- message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
143
- error_queue: asyncio.Queue[Exception],
144
- ) -> None:
145
- self.message_queue = message_queue
146
- self.error_queue = error_queue
147
-
148
- def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
149
- self.message_queue.put_nowait((data, addr))
150
-
151
- def error_received(self, exc: Exception) -> None:
152
- self.error_queue.put_nowait(exc)
153
-
154
-
155
- class DiscoveryMonitor:
156
- """Event-based continuous discovery monitor."""
157
-
158
- def __init__(self, discovery: PrinterDiscovery, options: DiscoveryOptions) -> None:
159
- self._discovery = discovery
160
- self._options = options
161
- self._listeners: dict[str, list[Callable[..., Any]]] = {
162
- "discovered": [],
163
- "end": [],
164
- "error": [],
165
- }
166
- self._transport: asyncio.DatagramTransport | None = None
167
- self._task = asyncio.create_task(self._run())
168
- self._stopped = False
169
- self._end_emitted = False
170
-
171
- def on(self, event: str, callback: Callable[..., Any]) -> DiscoveryMonitor:
172
- """Register an event callback."""
173
- self._listeners.setdefault(event, []).append(callback)
174
- return self
175
-
176
- def stop(self) -> None:
177
- """Stop monitoring and clean up resources."""
178
- if self._stopped:
179
- return
180
- self._stopped = True
181
- if self._transport:
182
- self._transport.close()
183
- self._transport = None
184
- if not self._task.done():
185
- self._task.cancel()
186
- self._emit_end_if_needed()
187
-
188
- async def _run(self) -> None:
189
- discovered_keys: set[str] = set()
190
- message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]] = asyncio.Queue()
191
- error_queue: asyncio.Queue[Exception] = asyncio.Queue()
192
- last_response_at: float | None = None
193
- send_interval_seconds = self._options.timeout / 1000.0
194
- total_timeout_seconds = (self._options.timeout * self._options.max_retries) / 1000.0
195
-
196
- try:
197
- self._transport, _ = await self._discovery._create_endpoint(message_queue, error_queue)
198
- self._discovery._send_discovery_packets(self._transport, self._options)
199
-
200
- loop = asyncio.get_running_loop()
201
- started_at = loop.time()
202
- next_send_at = started_at + send_interval_seconds
203
-
204
- while not self._stopped:
205
- now = loop.time()
206
- if now - started_at >= total_timeout_seconds:
207
- break
208
-
209
- if (
210
- last_response_at is not None
211
- and now - last_response_at >= self._options.idle_timeout / 1000.0
212
- ):
213
- break
214
-
215
- if now >= next_send_at:
216
- self._discovery._send_discovery_packets(self._transport, self._options)
217
- next_send_at = now + send_interval_seconds
218
-
219
- wait_timeout = min(0.1, max(total_timeout_seconds - (now - started_at), 0.0))
220
- try:
221
- data, addr = await asyncio.wait_for(message_queue.get(), timeout=wait_timeout)
222
- except TimeoutError:
223
- if not error_queue.empty():
224
- error = error_queue.get_nowait()
225
- self._emit("error", error)
226
- continue
227
-
228
- printer = self._discovery.parse_discovery_response(data, addr[0])
229
- if printer is None:
230
- continue
231
-
232
- last_response_at = loop.time()
233
- key = f"{printer.ip_address}:{printer.command_port}"
234
- if key not in discovered_keys:
235
- discovered_keys.add(key)
236
- self._emit("discovered", printer)
237
- except asyncio.CancelledError:
238
- raise
239
- except Exception as error:
240
- self._emit("error", error)
241
- finally:
242
- if self._transport:
243
- self._transport.close()
244
- self._transport = None
245
- self._emit_end_if_needed()
246
-
247
- def _emit(self, event: str, *args: Any) -> None:
248
- listeners = list(self._listeners.get(event, []))
249
- if event == "error" and not listeners:
250
- logger.error("Discovery monitor error: %s", args[0] if args else "unknown error")
251
- return
252
- for callback in listeners:
253
- callback(*args)
254
-
255
- def _emit_end_if_needed(self) -> None:
256
- if self._end_emitted:
257
- return
258
- self._end_emitted = True
259
- for callback in list(self._listeners.get("end", [])):
260
- callback()
261
-
262
-
263
- class PrinterDiscovery:
264
- """Universal FlashForge printer discovery using UDP broadcast and multicast."""
265
-
266
- async def discover(self, options: DiscoveryOptions | None = None) -> list[DiscoveredPrinter]:
267
- config = options or DiscoveryOptions()
268
- printers: dict[str, DiscoveredPrinter] = {}
269
-
270
- for attempt in range(config.max_retries):
271
- message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]] = asyncio.Queue()
272
- error_queue: asyncio.Queue[Exception] = asyncio.Queue()
273
- transport: asyncio.DatagramTransport | None = None
274
- try:
275
- transport, _ = await self._create_endpoint(message_queue, error_queue)
276
- self._send_discovery_packets(transport, config)
277
- discovered_printers = await self._receive_responses(
278
- message_queue, error_queue, config
279
- )
280
-
281
- for printer in discovered_printers:
282
- key = f"{printer.ip_address}:{printer.command_port}"
283
- existing = printers.get(key)
284
- if existing is None or printer.protocol_format == DiscoveryProtocol.MODERN:
285
- printers[key] = printer
286
-
287
- if printers:
288
- break
289
- finally:
290
- if transport is not None:
291
- transport.close()
292
-
293
- if attempt < config.max_retries - 1:
294
- await asyncio.sleep(1.0)
295
-
296
- return list(printers.values())
297
-
298
- def monitor(self, options: DiscoveryOptions | None = None) -> DiscoveryMonitor:
299
- """Create an event-based continuous discovery monitor."""
300
- return DiscoveryMonitor(self, options or DiscoveryOptions())
301
-
302
- async def _create_endpoint(
303
- self,
304
- message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
305
- error_queue: asyncio.Queue[Exception],
306
- ) -> tuple[asyncio.DatagramTransport, _DiscoveryDatagramProtocol]:
307
- loop = asyncio.get_running_loop()
308
- try:
309
- transport, protocol = await loop.create_datagram_endpoint(
310
- lambda: _DiscoveryDatagramProtocol(message_queue, error_queue),
311
- local_addr=("0.0.0.0", 0),
312
- allow_broadcast=True,
313
- )
314
- except Exception as error:
315
- raise SocketCreationError(str(error)) from error
316
- return transport, protocol
317
-
318
- async def _receive_responses(
319
- self,
320
- message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
321
- error_queue: asyncio.Queue[Exception],
322
- options: DiscoveryOptions,
323
- ) -> list[DiscoveredPrinter]:
324
- printers: list[DiscoveredPrinter] = []
325
- loop = asyncio.get_running_loop()
326
- started_at = loop.time()
327
- last_response_at = started_at
328
- total_timeout_seconds = options.timeout / 1000.0
329
- idle_timeout_seconds = options.idle_timeout / 1000.0
330
-
331
- while True:
332
- now = loop.time()
333
- if now - started_at >= total_timeout_seconds:
334
- break
335
- if now - last_response_at >= idle_timeout_seconds:
336
- break
337
-
338
- try:
339
- data, addr = await asyncio.wait_for(message_queue.get(), timeout=0.1)
340
- except TimeoutError:
341
- if not error_queue.empty():
342
- logger.error("Socket error during discovery: %s", error_queue.get_nowait())
343
- continue
344
-
345
- last_response_at = loop.time()
346
- printer = self.parse_discovery_response(data, addr[0])
347
- if printer is not None:
348
- printers.append(printer)
349
-
350
- return printers
351
-
352
- def _send_discovery_packets(
353
- self,
354
- transport: asyncio.DatagramTransport,
355
- options: DiscoveryOptions,
356
- ) -> None:
357
- packet = b""
358
-
359
- if options.use_multicast:
360
- self._join_multicast_group(transport)
361
- for port in options.ports:
362
- if port in {8899, 19000}:
363
- try:
364
- transport.sendto(packet, (MULTICAST_ADDRESS, port))
365
- except Exception as error:
366
- logger.warning(
367
- "Discovery: Failed to send multicast to %s:%s - %s",
368
- MULTICAST_ADDRESS,
369
- port,
370
- error,
371
- )
372
-
373
- if options.use_broadcast:
374
- for address in self.get_broadcast_addresses():
375
- for port in options.ports:
376
- if port == 48899:
377
- try:
378
- transport.sendto(packet, (address, port))
379
- except Exception as error:
380
- logger.warning(
381
- "Discovery: Failed to send broadcast to %s:%s - %s",
382
- address,
383
- port,
384
- error,
385
- )
386
-
387
- for port in options.ports:
388
- try:
389
- transport.sendto(packet, ("255.255.255.255", port))
390
- except Exception as error:
391
- logger.warning(
392
- "Discovery: Failed to send to broadcast 255.255.255.255:%s - %s",
393
- port,
394
- error,
395
- )
396
-
397
- def parse_discovery_response(
398
- self,
399
- buffer: bytes,
400
- ip_address: str,
401
- ) -> DiscoveredPrinter | None:
402
- """Parse a UDP discovery response and return typed printer metadata."""
403
- if not buffer:
404
- return None
405
-
406
- try:
407
- if len(buffer) >= MODERN_PROTOCOL_SIZE:
408
- return self.parse_modern_protocol(buffer, ip_address)
409
- if len(buffer) >= LEGACY_PROTOCOL_SIZE:
410
- return self.parse_legacy_protocol(buffer, ip_address)
411
-
412
- logger.warning("Invalid discovery response: %s bytes from %s", len(buffer), ip_address)
413
- return None
414
- except Exception as error:
415
- logger.error("Error parsing discovery response: %s", error)
416
- return None
417
-
418
- def parse_modern_protocol(self, buffer: bytes, ip_address: str) -> DiscoveredPrinter:
419
- """Parse a modern 276-byte (0x114) discovery response."""
420
- if len(buffer) < MODERN_PROTOCOL_SIZE:
421
- raise InvalidResponseError(len(buffer), ip_address)
422
-
423
- name = buffer[0:0x84].decode("utf-8", errors="ignore").split("\x00", 1)[0]
424
- command_port = int.from_bytes(buffer[0x84:0x86], byteorder="big")
425
- vendor_id = int.from_bytes(buffer[0x86:0x88], byteorder="big")
426
- product_id = int.from_bytes(buffer[0x88:0x8A], byteorder="big")
427
- status_code = int.from_bytes(buffer[0x8A:0x8C], byteorder="big")
428
- product_type = int.from_bytes(buffer[0x8C:0x8E], byteorder="big")
429
- event_port = int.from_bytes(buffer[0x8E:0x90], byteorder="big")
430
- serial_number = (
431
- buffer[0x92 : 0x92 + 128].decode("utf-8", errors="ignore").split("\x00", 1)[0]
432
- )
433
- model = self.detect_modern_model(name, product_type, product_id)
434
-
435
- return DiscoveredPrinter(
436
- model=model,
437
- protocol_format=DiscoveryProtocol.MODERN,
438
- name=name,
439
- ip_address=ip_address,
440
- command_port=command_port,
441
- serial_number=serial_number,
442
- event_port=event_port,
443
- vendor_id=vendor_id,
444
- product_id=product_id,
445
- product_type=product_type,
446
- status_code=status_code,
447
- status=self.map_status_code(status_code),
448
- )
449
-
450
- def parse_legacy_protocol(self, buffer: bytes, ip_address: str) -> DiscoveredPrinter:
451
- """Parse a legacy 140-byte discovery response."""
452
- if len(buffer) < LEGACY_PROTOCOL_SIZE:
453
- raise InvalidResponseError(len(buffer), ip_address)
454
-
455
- name = buffer[0:0x80].decode("utf-8", errors="ignore").split("\x00", 1)[0]
456
- command_port = int.from_bytes(buffer[0x84:0x86], byteorder="big")
457
- vendor_id = int.from_bytes(buffer[0x86:0x88], byteorder="big")
458
- product_id = int.from_bytes(buffer[0x88:0x8A], byteorder="big")
459
- status_code = int.from_bytes(buffer[0x8A:0x8C], byteorder="big")
460
- model = self.detect_legacy_model(name, product_id)
461
-
462
- return DiscoveredPrinter(
463
- model=model,
464
- protocol_format=DiscoveryProtocol.LEGACY,
465
- name=name,
466
- ip_address=ip_address,
467
- command_port=command_port,
468
- vendor_id=vendor_id,
469
- product_id=product_id,
470
- status_code=status_code,
471
- status=self.map_status_code(status_code),
472
- )
473
-
474
- def detect_modern_model(
475
- self,
476
- name: str,
477
- product_type: int,
478
- product_id: int | None = None,
479
- ) -> PrinterModelId:
480
- """Detect a modern printer model from discovery metadata.
481
-
482
- Resolution order:
483
- 1. USB product ID (offset 0x88) -- authoritative, user-immutable, and
484
- the only signal that distinguishes 5M / 5M Pro / AD5X / Creator 5.
485
- 2. product_type 0x5A02 (5M *family*) + name -- fallback for firmware
486
- reporting an unknown/zero product ID.
487
- 3. Name heuristics -- last resort.
488
- """
489
- # Product ID is authoritative (firmware-set, not user-mutable).
490
- by_pid = model_from_pid(product_id)
491
- if by_pid is not None and get_model_spec(by_pid).family != BackendFamily.LEGACY:
492
- return by_pid
493
-
494
- upper_name = name.upper()
495
-
496
- # 0x5A02 identifies the 5M family but not the specific model, so we still
497
- # need the name to separate base from Pro.
498
- if product_type == 0x5A02:
499
- if upper_name == "AD5X":
500
- return PrinterModelId.AD5X
501
- if "PRO" in upper_name:
502
- return PrinterModelId.ADVENTURER_5M_PRO
503
- return PrinterModelId.ADVENTURER_5M
504
-
505
- if upper_name == "AD5X":
506
- return PrinterModelId.AD5X
507
-
508
- if "ADVENTURER 5M" in upper_name or "AD5M" in upper_name:
509
- if "PRO" in upper_name:
510
- return PrinterModelId.ADVENTURER_5M_PRO
511
- return PrinterModelId.ADVENTURER_5M
512
-
513
- return PrinterModelId.UNKNOWN
514
-
515
- def detect_legacy_model(self, name: str, product_id: int | None = None) -> PrinterModelId:
516
- """Detect a legacy printer model from discovery metadata."""
517
- upper_name = name.upper()
518
-
519
- if "ADVENTURER 4" in upper_name or "ADVENTURER4" in upper_name or "AD4" in upper_name:
520
- return PrinterModelId.ADVENTURER_4
521
-
522
- if "ADVENTURER 3" in upper_name or "ADVENTURER3" in upper_name or "AD3" in upper_name:
523
- return PrinterModelId.ADVENTURER_3
524
-
525
- by_pid = model_from_pid(product_id)
526
- if by_pid is not None and get_model_spec(by_pid).family == BackendFamily.LEGACY:
527
- return by_pid
528
-
529
- return PrinterModelId.UNKNOWN
530
-
531
- def map_status_code(self, status_code: int) -> PrinterStatus:
532
- """Map discovery status codes to the typed printer status enum."""
533
- if status_code == 0:
534
- return PrinterStatus.READY
535
- if status_code == 1:
536
- return PrinterStatus.BUSY
537
- if status_code == 2:
538
- return PrinterStatus.ERROR
539
- return PrinterStatus.UNKNOWN
540
-
541
- def get_broadcast_addresses(self) -> list[str]:
542
- """Retrieve broadcast addresses for all active IPv4 interfaces."""
543
- broadcast_addresses: list[str] = []
544
-
545
- try:
546
- for adapter in ifaddr.get_adapters():
547
- for ip in adapter.ips:
548
- if not ip.is_IPv4:
549
- continue
550
-
551
- ip_addr = ip.ip
552
- if not isinstance(ip_addr, str) or ip_addr.startswith("127."):
553
- continue
554
-
555
- prefix = ip.network_prefix
556
- if not isinstance(prefix, int) or not 0 < prefix <= 32:
557
- continue
558
-
559
- mask_int = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
560
- netmask = ".".join(str((mask_int >> (8 * (3 - i))) & 0xFF) for i in range(4))
561
-
562
- broadcast = self.calculate_broadcast_address(ip_addr, netmask)
563
- if broadcast and broadcast not in broadcast_addresses:
564
- broadcast_addresses.append(broadcast)
565
- except Exception as error:
566
- logger.error("Error getting network interfaces: %s", error)
567
- broadcast_addresses = ["255.255.255.255", "192.168.1.255", "192.168.0.255"]
568
-
569
- if "255.255.255.255" not in broadcast_addresses:
570
- broadcast_addresses.append("255.255.255.255")
571
-
572
- return broadcast_addresses
573
-
574
- def calculate_broadcast_address(self, ip_address: str, subnet_mask: str) -> str | None:
575
- """Calculate an IPv4 broadcast address from IP and subnet mask."""
576
- try:
577
- ip_parts = [int(part) for part in ip_address.split(".")]
578
- mask_parts = [int(part) for part in subnet_mask.split(".")]
579
- if len(ip_parts) != 4 or len(mask_parts) != 4:
580
- return None
581
- broadcast_parts = [ip_parts[index] | (~mask_parts[index] & 255) for index in range(4)]
582
- return ".".join(str(part) for part in broadcast_parts)
583
- except Exception:
584
- return None
585
-
586
- def _join_multicast_group(self, transport: asyncio.DatagramTransport) -> None:
587
- """Join the discovery multicast group if the OS/network stack allows it."""
588
- get_extra_info = getattr(transport, "get_extra_info", None)
589
- if get_extra_info is None:
590
- return
591
-
592
- raw_socket = get_extra_info("socket")
593
- if raw_socket is None:
594
- return
595
-
596
- try:
597
- membership = socket.inet_aton(MULTICAST_ADDRESS) + socket.inet_aton("0.0.0.0")
598
- raw_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
599
- except Exception as error:
600
- logger.warning(
601
- "Discovery: Failed to join multicast group %s - %s",
602
- MULTICAST_ADDRESS,
603
- error,
604
- )
605
-
606
-
607
- class FlashForgePrinterDiscovery:
608
- """Backward-compatible wrapper around the universal PrinterDiscovery API."""
609
-
610
- DISCOVERY_PORT = 48899
611
- LISTEN_PORT = 18007
612
-
613
- def __init__(self) -> None:
614
- self.discovery_port = self.DISCOVERY_PORT
615
- self.listen_port = self.LISTEN_PORT
616
- self.discovery_message = bytes(
617
- [
618
- 0x77,
619
- 0x77,
620
- 0x77,
621
- 0x2E,
622
- 0x75,
623
- 0x73,
624
- 0x72,
625
- 0x22,
626
- 0x65,
627
- 0x36,
628
- 0xC0,
629
- 0x00,
630
- 0x00,
631
- 0x00,
632
- 0x00,
633
- 0x00,
634
- 0x00,
635
- 0x00,
636
- 0x00,
637
- 0x00,
638
- ]
639
- )
640
- self._discovery = PrinterDiscovery()
641
-
642
- async def discover_printers_async(
643
- self,
644
- timeout_ms: int = 10000,
645
- idle_timeout_ms: int = 1500,
646
- max_retries: int = 3,
647
- ) -> list[FlashForgePrinter]:
648
- """Discover printers and return the legacy FlashForgePrinter wrapper objects."""
649
- printers = await self._discovery.discover(
650
- DiscoveryOptions(
651
- timeout=timeout_ms,
652
- idle_timeout=idle_timeout_ms,
653
- max_retries=max_retries,
654
- )
655
- )
656
- return [FlashForgePrinter.from_discovered_printer(printer) for printer in printers]
657
-
658
- def _parse_printer_response(
659
- self,
660
- response: bytes | None,
661
- ip_address: str,
662
- ) -> FlashForgePrinter | None:
663
- if response is None:
664
- return None
665
-
666
- if LEGACY_PROTOCOL_SIZE <= len(response) < MODERN_PROTOCOL_SIZE and len(response) >= 0x92:
667
- legacy_name = (
668
- response[0:32].decode("utf-8", errors="ignore").split("\x00", 1)[0].strip()
669
- )
670
- legacy_serial = (
671
- response[0x92 : 0x92 + 32]
672
- .decode("utf-8", errors="ignore")
673
- .split("\x00", 1)[0]
674
- .strip()
675
- )
676
- if legacy_name or legacy_serial:
677
- return FlashForgePrinter(
678
- name=legacy_name,
679
- serial_number=legacy_serial,
680
- ip_address=ip_address,
681
- )
682
-
683
- printer = self._discovery.parse_discovery_response(response, ip_address)
684
- if printer is None:
685
- return None
686
- if not printer.name and not printer.serial_number:
687
- return None
688
- return FlashForgePrinter.from_discovered_printer(printer)
689
-
690
- def _get_broadcast_addresses(self) -> list[str]:
691
- return self._discovery.get_broadcast_addresses()
692
-
693
- def _calculate_broadcast_address(self, ip_address: str, subnet_mask: str) -> str | None:
694
- return self._discovery.calculate_broadcast_address(ip_address, subnet_mask)
695
-
696
- def print_debug_info(self, response: bytes, ip_address: str) -> None:
697
- print(f"Received response from {ip_address}:")
698
- print(f"Response length: {len(response)} bytes")
699
- print("Hex dump:")
700
- for index in range(0, len(response), 16):
701
- parts = [f"{index:04x} "]
702
- for offset in range(16):
703
- if index + offset < len(response):
704
- parts.append(f"{response[index + offset]:02x} ")
705
- else:
706
- parts.append(" ")
707
- if offset == 7:
708
- parts.append(" ")
709
-
710
- parts.append(" ")
711
- for offset in range(16):
712
- if index + offset < len(response):
713
- byte = response[index + offset]
714
- parts.append(chr(byte) if 32 <= byte <= 126 else ".")
715
- print("".join(parts))
716
-
717
- print("ASCII dump:")
718
- print(repr(response.decode("ascii", errors="replace")))
719
-
720
-
721
- async def _async_main() -> None:
722
- discovery = FlashForgePrinterDiscovery()
723
- printers = await discovery.discover_printers_async()
724
- for printer in printers:
725
- print(printer)
726
-
727
-
728
- def main() -> None:
729
- """CLI entry point for `flashforge-discover`."""
730
- asyncio.run(_async_main())
1
+ """
2
+ Universal FlashForge printer discovery using UDP broadcast and multicast.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import logging
9
+ import socket
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass, field
12
+ from enum import IntEnum, StrEnum
13
+ from typing import Any
14
+
15
+ import ifaddr
16
+
17
+ from ..capabilities.models import BackendFamily, PrinterModelId, model_from_pid
18
+ from ..capabilities.registry import get_model_spec
19
+
20
+ logger = logging.getLogger(__name__)
21
+
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"
26
+ MODERN_PROTOCOL_SIZE = 276
27
+ LEGACY_PROTOCOL_SIZE = 140
28
+
29
+
30
+ class DiscoveryError(Exception):
31
+ """Base error for discovery-related failures."""
32
+
33
+ def __init__(self, message: str, code: str) -> None:
34
+ super().__init__(message)
35
+ self.code = code
36
+
37
+
38
+ class InvalidResponseError(DiscoveryError):
39
+ """Raised when a discovery response has an unexpected size."""
40
+
41
+ def __init__(self, size: int, address: str) -> None:
42
+ super().__init__(f"Invalid response size: {size} bytes from {address}", "INVALID_RESPONSE")
43
+ self.response_size = size
44
+ self.address = address
45
+
46
+
47
+ class SocketCreationError(DiscoveryError):
48
+ """Raised when a UDP discovery socket cannot be created."""
49
+
50
+ def __init__(self, message: str) -> None:
51
+ super().__init__(message, "SOCKET_CREATION_FAILED")
52
+
53
+
54
+ class DiscoveryTimeoutError(DiscoveryError):
55
+ """Raised when discovery times out without any responses."""
56
+
57
+ def __init__(self, timeout_ms: int) -> None:
58
+ super().__init__(f"Discovery timeout after {timeout_ms}ms", "DISCOVERY_TIMEOUT")
59
+ self.timeout_ms = timeout_ms
60
+
61
+
62
+ class DiscoveryProtocol(StrEnum):
63
+ """Discovery response wire formats."""
64
+
65
+ MODERN = "modern"
66
+ LEGACY = "legacy"
67
+
68
+
69
+ class PrinterStatus(IntEnum):
70
+ """Printer status reported via UDP discovery."""
71
+
72
+ READY = 0
73
+ BUSY = 1
74
+ ERROR = 2
75
+ UNKNOWN = 3
76
+
77
+
78
+ @dataclass(slots=True)
79
+ class DiscoveredPrinter:
80
+ """Typed printer metadata returned by universal discovery."""
81
+
82
+ #: Resolved model (USB product ID first, then name). UNKNOWN when not recognised.
83
+ model: PrinterModelId
84
+ protocol_format: DiscoveryProtocol
85
+ name: str
86
+ ip_address: str
87
+ command_port: int
88
+ serial_number: str | None = None
89
+ event_port: int | None = None
90
+ vendor_id: int | None = None
91
+ product_id: int | None = None
92
+ product_type: int | None = None
93
+ status_code: int | None = None
94
+ status: PrinterStatus | None = None
95
+
96
+
97
+ @dataclass(slots=True)
98
+ class DiscoveryOptions:
99
+ """Configuration options for printer discovery."""
100
+
101
+ timeout: int = 10000
102
+ idle_timeout: int = 1500
103
+ max_retries: int = 3
104
+ use_multicast: bool = True
105
+ use_broadcast: bool = True
106
+ ports: list[int] = field(default_factory=lambda: [8899, 19000, 48899])
107
+
108
+
109
+ @dataclass(slots=True)
110
+ class FlashForgePrinter:
111
+ """
112
+ Backward-compatible legacy discovery result.
113
+
114
+ This keeps the historical Python surface used by ff-5mp-hass while the richer
115
+ DiscoveredPrinter metadata is exposed via PrinterDiscovery.
116
+ """
117
+
118
+ name: str = ""
119
+ serial_number: str = ""
120
+ ip_address: str = ""
121
+
122
+ @classmethod
123
+ def from_discovered_printer(cls, printer: DiscoveredPrinter) -> FlashForgePrinter:
124
+ return cls(
125
+ name=printer.name,
126
+ serial_number=printer.serial_number or "",
127
+ ip_address=printer.ip_address,
128
+ )
129
+
130
+ def __str__(self) -> str:
131
+ return f"Name: {self.name}, Serial: {self.serial_number}, IP: {self.ip_address}"
132
+
133
+ def __repr__(self) -> str:
134
+ return (
135
+ "FlashForgePrinter("
136
+ f"name='{self.name}', serial_number='{self.serial_number}', ip_address='{self.ip_address}')"
137
+ )
138
+
139
+
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
+ """
157
+
158
+ def __init__(
159
+ self,
160
+ sock: socket.socket,
161
+ message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
162
+ error_queue: asyncio.Queue[Exception],
163
+ ) -> None:
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])
193
+
194
+ def get_extra_info(self, name: str, default: Any = None) -> Any:
195
+ return self._sock if name == "socket" else default
196
+
197
+ def close(self) -> None:
198
+ if self._closed:
199
+ return
200
+ self._closed = True
201
+ self._reader.cancel()
202
+ self._sock.close()
203
+
204
+
205
+ class DiscoveryMonitor:
206
+ """Event-based continuous discovery monitor."""
207
+
208
+ def __init__(self, discovery: PrinterDiscovery, options: DiscoveryOptions) -> None:
209
+ self._discovery = discovery
210
+ self._options = options
211
+ self._listeners: dict[str, list[Callable[..., Any]]] = {
212
+ "discovered": [],
213
+ "end": [],
214
+ "error": [],
215
+ }
216
+ self._transport: _DiscoverySocket | None = None
217
+ self._task = asyncio.create_task(self._run())
218
+ self._stopped = False
219
+ self._end_emitted = False
220
+
221
+ def on(self, event: str, callback: Callable[..., Any]) -> DiscoveryMonitor:
222
+ """Register an event callback."""
223
+ self._listeners.setdefault(event, []).append(callback)
224
+ return self
225
+
226
+ def stop(self) -> None:
227
+ """Stop monitoring and clean up resources."""
228
+ if self._stopped:
229
+ return
230
+ self._stopped = True
231
+ if self._transport:
232
+ self._transport.close()
233
+ self._transport = None
234
+ if not self._task.done():
235
+ self._task.cancel()
236
+ self._emit_end_if_needed()
237
+
238
+ async def _run(self) -> None:
239
+ discovered_keys: set[str] = set()
240
+ message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]] = asyncio.Queue()
241
+ error_queue: asyncio.Queue[Exception] = asyncio.Queue()
242
+ last_response_at: float | None = None
243
+ send_interval_seconds = self._options.timeout / 1000.0
244
+ total_timeout_seconds = (self._options.timeout * self._options.max_retries) / 1000.0
245
+
246
+ try:
247
+ self._transport, _ = await self._discovery._create_endpoint(message_queue, error_queue)
248
+ self._discovery._send_discovery_packets(self._transport, self._options)
249
+
250
+ loop = asyncio.get_running_loop()
251
+ started_at = loop.time()
252
+ next_send_at = started_at + send_interval_seconds
253
+
254
+ while not self._stopped:
255
+ now = loop.time()
256
+ if now - started_at >= total_timeout_seconds:
257
+ break
258
+
259
+ if (
260
+ last_response_at is not None
261
+ and now - last_response_at >= self._options.idle_timeout / 1000.0
262
+ ):
263
+ break
264
+
265
+ if now >= next_send_at:
266
+ self._discovery._send_discovery_packets(self._transport, self._options)
267
+ next_send_at = now + send_interval_seconds
268
+
269
+ wait_timeout = min(0.1, max(total_timeout_seconds - (now - started_at), 0.0))
270
+ try:
271
+ data, addr = await asyncio.wait_for(message_queue.get(), timeout=wait_timeout)
272
+ except TimeoutError:
273
+ if not error_queue.empty():
274
+ error = error_queue.get_nowait()
275
+ self._emit("error", error)
276
+ continue
277
+
278
+ printer = self._discovery.parse_discovery_response(data, addr[0])
279
+ if printer is None:
280
+ continue
281
+
282
+ last_response_at = loop.time()
283
+ key = f"{printer.ip_address}:{printer.command_port}"
284
+ if key not in discovered_keys:
285
+ discovered_keys.add(key)
286
+ self._emit("discovered", printer)
287
+ except asyncio.CancelledError:
288
+ raise
289
+ except Exception as error:
290
+ self._emit("error", error)
291
+ finally:
292
+ if self._transport:
293
+ self._transport.close()
294
+ self._transport = None
295
+ self._emit_end_if_needed()
296
+
297
+ def _emit(self, event: str, *args: Any) -> None:
298
+ listeners = list(self._listeners.get(event, []))
299
+ if event == "error" and not listeners:
300
+ logger.error("Discovery monitor error: %s", args[0] if args else "unknown error")
301
+ return
302
+ for callback in listeners:
303
+ callback(*args)
304
+
305
+ def _emit_end_if_needed(self) -> None:
306
+ if self._end_emitted:
307
+ return
308
+ self._end_emitted = True
309
+ for callback in list(self._listeners.get("end", [])):
310
+ callback()
311
+
312
+
313
+ class PrinterDiscovery:
314
+ """Universal FlashForge printer discovery using UDP broadcast and multicast."""
315
+
316
+ async def discover(self, options: DiscoveryOptions | None = None) -> list[DiscoveredPrinter]:
317
+ config = options or DiscoveryOptions()
318
+ printers: dict[str, DiscoveredPrinter] = {}
319
+
320
+ for attempt in range(config.max_retries):
321
+ message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]] = asyncio.Queue()
322
+ error_queue: asyncio.Queue[Exception] = asyncio.Queue()
323
+ transport: _DiscoverySocket | None = None
324
+ try:
325
+ transport, _ = await self._create_endpoint(message_queue, error_queue)
326
+ self._send_discovery_packets(transport, config)
327
+ discovered_printers = await self._receive_responses(
328
+ message_queue, error_queue, config
329
+ )
330
+
331
+ for printer in discovered_printers:
332
+ key = f"{printer.ip_address}:{printer.command_port}"
333
+ existing = printers.get(key)
334
+ if existing is None or printer.protocol_format == DiscoveryProtocol.MODERN:
335
+ printers[key] = printer
336
+
337
+ if printers:
338
+ break
339
+ finally:
340
+ if transport is not None:
341
+ transport.close()
342
+
343
+ if attempt < config.max_retries - 1:
344
+ await asyncio.sleep(1.0)
345
+
346
+ return list(printers.values())
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
+
391
+ def monitor(self, options: DiscoveryOptions | None = None) -> DiscoveryMonitor:
392
+ """Create an event-based continuous discovery monitor."""
393
+ return DiscoveryMonitor(self, options or DiscoveryOptions())
394
+
395
+ async def _create_endpoint(
396
+ self,
397
+ message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
398
+ error_queue: asyncio.Queue[Exception],
399
+ ) -> tuple[_DiscoverySocket, None]:
400
+ sock: socket.socket | None = None
401
+ try:
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))
406
+ except Exception as error:
407
+ if sock is not None:
408
+ sock.close()
409
+ raise SocketCreationError(str(error)) from error
410
+ return _DiscoverySocket(sock, message_queue, error_queue), None
411
+
412
+ async def _receive_responses(
413
+ self,
414
+ message_queue: asyncio.Queue[tuple[bytes, tuple[str, int]]],
415
+ error_queue: asyncio.Queue[Exception],
416
+ options: DiscoveryOptions,
417
+ ) -> list[DiscoveredPrinter]:
418
+ printers: list[DiscoveredPrinter] = []
419
+ loop = asyncio.get_running_loop()
420
+ started_at = loop.time()
421
+ last_response_at = started_at
422
+ total_timeout_seconds = options.timeout / 1000.0
423
+ idle_timeout_seconds = options.idle_timeout / 1000.0
424
+
425
+ while True:
426
+ now = loop.time()
427
+ if now - started_at >= total_timeout_seconds:
428
+ break
429
+ if now - last_response_at >= idle_timeout_seconds:
430
+ break
431
+
432
+ try:
433
+ data, addr = await asyncio.wait_for(message_queue.get(), timeout=0.1)
434
+ except TimeoutError:
435
+ if not error_queue.empty():
436
+ logger.error("Socket error during discovery: %s", error_queue.get_nowait())
437
+ continue
438
+
439
+ last_response_at = loop.time()
440
+ printer = self.parse_discovery_response(data, addr[0])
441
+ if printer is not None:
442
+ printers.append(printer)
443
+
444
+ return printers
445
+
446
+ def _send_discovery_packets(
447
+ self,
448
+ transport: _DiscoverySocket,
449
+ options: DiscoveryOptions,
450
+ ) -> None:
451
+ packet = b""
452
+
453
+ if options.use_multicast:
454
+ self._join_multicast_group(transport)
455
+ for port in options.ports:
456
+ if port in {8899, 19000}:
457
+ try:
458
+ transport.sendto(packet, (MULTICAST_ADDRESS, port))
459
+ except Exception as error:
460
+ logger.warning(
461
+ "Discovery: Failed to send multicast to %s:%s - %s",
462
+ MULTICAST_ADDRESS,
463
+ port,
464
+ error,
465
+ )
466
+
467
+ if options.use_broadcast:
468
+ for address in self.get_broadcast_addresses():
469
+ for port in options.ports:
470
+ if port == 48899:
471
+ try:
472
+ transport.sendto(packet, (address, port))
473
+ except Exception as error:
474
+ # A disconnected adapter's broadcast address is unreachable.
475
+ logger.debug(
476
+ "Discovery: Failed to send broadcast to %s:%s - %s",
477
+ address,
478
+ port,
479
+ error,
480
+ )
481
+
482
+ for port in options.ports:
483
+ try:
484
+ transport.sendto(packet, ("255.255.255.255", port))
485
+ except Exception as error:
486
+ logger.warning(
487
+ "Discovery: Failed to send to broadcast 255.255.255.255:%s - %s",
488
+ port,
489
+ error,
490
+ )
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
+
503
+ def parse_discovery_response(
504
+ self,
505
+ buffer: bytes,
506
+ ip_address: str,
507
+ ) -> DiscoveredPrinter | None:
508
+ """Parse a UDP discovery response and return typed printer metadata."""
509
+ if not buffer:
510
+ return None
511
+
512
+ try:
513
+ if len(buffer) >= MODERN_PROTOCOL_SIZE:
514
+ return self.parse_modern_protocol(buffer, ip_address)
515
+ if len(buffer) >= LEGACY_PROTOCOL_SIZE:
516
+ return self.parse_legacy_protocol(buffer, ip_address)
517
+
518
+ logger.warning("Invalid discovery response: %s bytes from %s", len(buffer), ip_address)
519
+ return None
520
+ except Exception as error:
521
+ logger.error("Error parsing discovery response: %s", error)
522
+ return None
523
+
524
+ def parse_modern_protocol(self, buffer: bytes, ip_address: str) -> DiscoveredPrinter:
525
+ """Parse a modern 276-byte (0x114) discovery response."""
526
+ if len(buffer) < MODERN_PROTOCOL_SIZE:
527
+ raise InvalidResponseError(len(buffer), ip_address)
528
+
529
+ name = buffer[0:0x84].decode("utf-8", errors="ignore").split("\x00", 1)[0]
530
+ command_port = int.from_bytes(buffer[0x84:0x86], byteorder="big")
531
+ vendor_id = int.from_bytes(buffer[0x86:0x88], byteorder="big")
532
+ product_id = int.from_bytes(buffer[0x88:0x8A], byteorder="big")
533
+ status_code = int.from_bytes(buffer[0x8A:0x8C], byteorder="big")
534
+ product_type = int.from_bytes(buffer[0x8C:0x8E], byteorder="big")
535
+ event_port = int.from_bytes(buffer[0x8E:0x90], byteorder="big")
536
+ serial_number = (
537
+ buffer[0x92 : 0x92 + 128].decode("utf-8", errors="ignore").split("\x00", 1)[0]
538
+ )
539
+ model = self.detect_modern_model(name, product_type, product_id)
540
+
541
+ return DiscoveredPrinter(
542
+ model=model,
543
+ protocol_format=DiscoveryProtocol.MODERN,
544
+ name=name,
545
+ ip_address=ip_address,
546
+ command_port=command_port,
547
+ serial_number=serial_number,
548
+ event_port=event_port,
549
+ vendor_id=vendor_id,
550
+ product_id=product_id,
551
+ product_type=product_type,
552
+ status_code=status_code,
553
+ status=self.map_status_code(status_code),
554
+ )
555
+
556
+ def parse_legacy_protocol(self, buffer: bytes, ip_address: str) -> DiscoveredPrinter:
557
+ """Parse a legacy 140-byte discovery response."""
558
+ if len(buffer) < LEGACY_PROTOCOL_SIZE:
559
+ raise InvalidResponseError(len(buffer), ip_address)
560
+
561
+ name = buffer[0:0x80].decode("utf-8", errors="ignore").split("\x00", 1)[0]
562
+ command_port = int.from_bytes(buffer[0x84:0x86], byteorder="big")
563
+ vendor_id = int.from_bytes(buffer[0x86:0x88], byteorder="big")
564
+ product_id = int.from_bytes(buffer[0x88:0x8A], byteorder="big")
565
+ status_code = int.from_bytes(buffer[0x8A:0x8C], byteorder="big")
566
+ model = self.detect_legacy_model(name, product_id)
567
+
568
+ return DiscoveredPrinter(
569
+ model=model,
570
+ protocol_format=DiscoveryProtocol.LEGACY,
571
+ name=name,
572
+ ip_address=ip_address,
573
+ command_port=command_port,
574
+ vendor_id=vendor_id,
575
+ product_id=product_id,
576
+ status_code=status_code,
577
+ status=self.map_status_code(status_code),
578
+ )
579
+
580
+ def detect_modern_model(
581
+ self,
582
+ name: str,
583
+ product_type: int,
584
+ product_id: int | None = None,
585
+ ) -> PrinterModelId:
586
+ """Detect a modern printer model from discovery metadata.
587
+
588
+ Resolution order:
589
+ 1. USB product ID (offset 0x88) -- authoritative, user-immutable, and
590
+ the only signal that distinguishes 5M / 5M Pro / AD5X / Creator 5.
591
+ 2. product_type 0x5A02 (5M *family*) + name -- fallback for firmware
592
+ reporting an unknown/zero product ID.
593
+ 3. Name heuristics -- last resort.
594
+ """
595
+ # Product ID is authoritative (firmware-set, not user-mutable).
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
599
+
600
+ upper_name = name.upper()
601
+
602
+ # 0x5A02 identifies the 5M family but not the specific model, so we still
603
+ # need the name to separate base from Pro.
604
+ if product_type == 0x5A02:
605
+ if upper_name == "AD5X":
606
+ return PrinterModelId.AD5X
607
+ if "PRO" in upper_name:
608
+ return PrinterModelId.ADVENTURER_5M_PRO
609
+ return PrinterModelId.ADVENTURER_5M
610
+
611
+ if upper_name == "AD5X":
612
+ return PrinterModelId.AD5X
613
+
614
+ if "ADVENTURER 5M" in upper_name or "AD5M" in upper_name:
615
+ if "PRO" in upper_name:
616
+ return PrinterModelId.ADVENTURER_5M_PRO
617
+ return PrinterModelId.ADVENTURER_5M
618
+
619
+ return PrinterModelId.UNKNOWN
620
+
621
+ def detect_legacy_model(self, name: str, product_id: int | None = None) -> PrinterModelId:
622
+ """Detect a legacy printer model from discovery metadata."""
623
+ upper_name = name.upper()
624
+
625
+ if "ADVENTURER 4" in upper_name or "ADVENTURER4" in upper_name or "AD4" in upper_name:
626
+ return PrinterModelId.ADVENTURER_4
627
+
628
+ if "ADVENTURER 3" in upper_name or "ADVENTURER3" in upper_name or "AD3" in upper_name:
629
+ return PrinterModelId.ADVENTURER_3
630
+
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
634
+
635
+ return PrinterModelId.UNKNOWN
636
+
637
+ def map_status_code(self, status_code: int) -> PrinterStatus:
638
+ """Map discovery status codes to the typed printer status enum."""
639
+ if status_code == 0:
640
+ return PrinterStatus.READY
641
+ if status_code == 1:
642
+ return PrinterStatus.BUSY
643
+ if status_code == 2:
644
+ return PrinterStatus.ERROR
645
+ return PrinterStatus.UNKNOWN
646
+
647
+ def get_broadcast_addresses(self) -> list[str]:
648
+ """Retrieve broadcast addresses for all active IPv4 interfaces."""
649
+ broadcast_addresses: list[str] = []
650
+
651
+ try:
652
+ for adapter in ifaddr.get_adapters():
653
+ for ip in adapter.ips:
654
+ if not ip.is_IPv4:
655
+ continue
656
+
657
+ ip_addr = ip.ip
658
+ if not isinstance(ip_addr, str) or ip_addr.startswith("127."):
659
+ continue
660
+
661
+ prefix = ip.network_prefix
662
+ if not isinstance(prefix, int) or not 0 < prefix <= 32:
663
+ continue
664
+
665
+ mask_int = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
666
+ netmask = ".".join(str((mask_int >> (8 * (3 - i))) & 0xFF) for i in range(4))
667
+
668
+ broadcast = self.calculate_broadcast_address(ip_addr, netmask)
669
+ if broadcast and broadcast not in broadcast_addresses:
670
+ broadcast_addresses.append(broadcast)
671
+ except Exception as error:
672
+ logger.error("Error getting network interfaces: %s", error)
673
+ broadcast_addresses = ["255.255.255.255", "192.168.1.255", "192.168.0.255"]
674
+
675
+ if "255.255.255.255" not in broadcast_addresses:
676
+ broadcast_addresses.append("255.255.255.255")
677
+
678
+ return broadcast_addresses
679
+
680
+ def calculate_broadcast_address(self, ip_address: str, subnet_mask: str) -> str | None:
681
+ """Calculate an IPv4 broadcast address from IP and subnet mask."""
682
+ try:
683
+ ip_parts = [int(part) for part in ip_address.split(".")]
684
+ mask_parts = [int(part) for part in subnet_mask.split(".")]
685
+ if len(ip_parts) != 4 or len(mask_parts) != 4:
686
+ return None
687
+ broadcast_parts = [ip_parts[index] | (~mask_parts[index] & 255) for index in range(4)]
688
+ return ".".join(str(part) for part in broadcast_parts)
689
+ except Exception:
690
+ return None
691
+
692
+ def _join_multicast_group(self, transport: _DiscoverySocket) -> None:
693
+ """Join the discovery multicast group if the OS/network stack allows it."""
694
+ get_extra_info = getattr(transport, "get_extra_info", None)
695
+ if get_extra_info is None:
696
+ return
697
+
698
+ raw_socket = get_extra_info("socket")
699
+ if raw_socket is None:
700
+ return
701
+
702
+ try:
703
+ membership = socket.inet_aton(MULTICAST_ADDRESS) + socket.inet_aton("0.0.0.0")
704
+ raw_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
705
+ except Exception as error:
706
+ logger.warning(
707
+ "Discovery: Failed to join multicast group %s - %s",
708
+ MULTICAST_ADDRESS,
709
+ error,
710
+ )
711
+
712
+
713
+ class FlashForgePrinterDiscovery:
714
+ """Backward-compatible wrapper around the universal PrinterDiscovery API."""
715
+
716
+ DISCOVERY_PORT = 48899
717
+ LISTEN_PORT = 18007
718
+
719
+ def __init__(self) -> None:
720
+ self.discovery_port = self.DISCOVERY_PORT
721
+ self.listen_port = self.LISTEN_PORT
722
+ self.discovery_message = bytes(
723
+ [
724
+ 0x77,
725
+ 0x77,
726
+ 0x77,
727
+ 0x2E,
728
+ 0x75,
729
+ 0x73,
730
+ 0x72,
731
+ 0x22,
732
+ 0x65,
733
+ 0x36,
734
+ 0xC0,
735
+ 0x00,
736
+ 0x00,
737
+ 0x00,
738
+ 0x00,
739
+ 0x00,
740
+ 0x00,
741
+ 0x00,
742
+ 0x00,
743
+ 0x00,
744
+ ]
745
+ )
746
+ self._discovery = PrinterDiscovery()
747
+
748
+ async def discover_printers_async(
749
+ self,
750
+ timeout_ms: int = 10000,
751
+ idle_timeout_ms: int = 1500,
752
+ max_retries: int = 3,
753
+ ) -> list[FlashForgePrinter]:
754
+ """Discover printers and return the legacy FlashForgePrinter wrapper objects."""
755
+ printers = await self._discovery.discover(
756
+ DiscoveryOptions(
757
+ timeout=timeout_ms,
758
+ idle_timeout=idle_timeout_ms,
759
+ max_retries=max_retries,
760
+ )
761
+ )
762
+ return [FlashForgePrinter.from_discovered_printer(printer) for printer in printers]
763
+
764
+ def _parse_printer_response(
765
+ self,
766
+ response: bytes | None,
767
+ ip_address: str,
768
+ ) -> FlashForgePrinter | None:
769
+ if response is None:
770
+ return None
771
+
772
+ if LEGACY_PROTOCOL_SIZE <= len(response) < MODERN_PROTOCOL_SIZE and len(response) >= 0x92:
773
+ legacy_name = (
774
+ response[0:32].decode("utf-8", errors="ignore").split("\x00", 1)[0].strip()
775
+ )
776
+ legacy_serial = (
777
+ response[0x92 : 0x92 + 32]
778
+ .decode("utf-8", errors="ignore")
779
+ .split("\x00", 1)[0]
780
+ .strip()
781
+ )
782
+ if legacy_name or legacy_serial:
783
+ return FlashForgePrinter(
784
+ name=legacy_name,
785
+ serial_number=legacy_serial,
786
+ ip_address=ip_address,
787
+ )
788
+
789
+ printer = self._discovery.parse_discovery_response(response, ip_address)
790
+ if printer is None:
791
+ return None
792
+ if not printer.name and not printer.serial_number:
793
+ return None
794
+ return FlashForgePrinter.from_discovered_printer(printer)
795
+
796
+ def _get_broadcast_addresses(self) -> list[str]:
797
+ return self._discovery.get_broadcast_addresses()
798
+
799
+ def _calculate_broadcast_address(self, ip_address: str, subnet_mask: str) -> str | None:
800
+ return self._discovery.calculate_broadcast_address(ip_address, subnet_mask)
801
+
802
+ def print_debug_info(self, response: bytes, ip_address: str) -> None:
803
+ print(f"Received response from {ip_address}:")
804
+ print(f"Response length: {len(response)} bytes")
805
+ print("Hex dump:")
806
+ for index in range(0, len(response), 16):
807
+ parts = [f"{index:04x} "]
808
+ for offset in range(16):
809
+ if index + offset < len(response):
810
+ parts.append(f"{response[index + offset]:02x} ")
811
+ else:
812
+ parts.append(" ")
813
+ if offset == 7:
814
+ parts.append(" ")
815
+
816
+ parts.append(" ")
817
+ for offset in range(16):
818
+ if index + offset < len(response):
819
+ byte = response[index + offset]
820
+ parts.append(chr(byte) if 32 <= byte <= 126 else ".")
821
+ print("".join(parts))
822
+
823
+ print("ASCII dump:")
824
+ print(repr(response.decode("ascii", errors="replace")))
825
+
826
+
827
+ async def _async_main() -> None:
828
+ discovery = FlashForgePrinterDiscovery()
829
+ printers = await discovery.discover_printers_async()
830
+ for printer in printers:
831
+ print(printer)
832
+
833
+
834
+ def main() -> None:
835
+ """CLI entry point for `flashforge-discover`."""
836
+ asyncio.run(_async_main())