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.
- flashforge/__init__.py +337 -337
- flashforge/discovery/discovery.py +836 -730
- {flashforge_python_api-3.0.0.dist-info → flashforge_python_api-3.1.0.dist-info}/METADATA +1 -1
- {flashforge_python_api-3.0.0.dist-info → flashforge_python_api-3.1.0.dist-info}/RECORD +7 -7
- {flashforge_python_api-3.0.0.dist-info → flashforge_python_api-3.1.0.dist-info}/WHEEL +0 -0
- {flashforge_python_api-3.0.0.dist-info → flashforge_python_api-3.1.0.dist-info}/entry_points.txt +0 -0
- {flashforge_python_api-3.0.0.dist-info → flashforge_python_api-3.1.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
name
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
def
|
|
131
|
-
return
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
)
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
"""
|
|
157
|
-
|
|
158
|
-
def __init__(
|
|
159
|
-
self
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
self.
|
|
167
|
-
self.
|
|
168
|
-
self.
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
self.
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
if
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
if
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
) -> list[
|
|
648
|
-
"""
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
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())
|