flashforge-python-api 1.6.0__py3-none-any.whl → 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. flashforge/__init__.py +337 -256
  2. flashforge/_removed.py +65 -0
  3. flashforge/api/__init__.py +12 -18
  4. flashforge/api/constants/__init__.py +11 -11
  5. flashforge/api/constants/commands.py +18 -15
  6. flashforge/api/constants/endpoints.py +11 -11
  7. flashforge/api/misc/__init__.py +8 -8
  8. flashforge/api/network/__init__.py +11 -11
  9. flashforge/api/network/utils.py +71 -71
  10. flashforge/backends/__init__.py +80 -0
  11. flashforge/backends/connect.py +275 -0
  12. flashforge/backends/creator5_backend.py +191 -0
  13. flashforge/backends/dual_api_backend.py +170 -0
  14. flashforge/backends/dual_api_models.py +145 -0
  15. flashforge/backends/http_core.py +431 -0
  16. flashforge/backends/http_printer_backend.py +254 -0
  17. flashforge/backends/legacy_backend.py +436 -0
  18. flashforge/backends/printer_backend.py +217 -0
  19. flashforge/backends/types.py +125 -0
  20. flashforge/capabilities/__init__.py +98 -0
  21. flashforge/capabilities/models.py +67 -0
  22. flashforge/capabilities/palettes/__init__.py +28 -0
  23. flashforge/capabilities/palettes/ad5x_palette.py +70 -0
  24. flashforge/capabilities/palettes/creator5_palette.py +78 -0
  25. flashforge/capabilities/palettes/palette.py +54 -0
  26. flashforge/{api/controls/creator5_palette.py → capabilities/palettes/palette_snap.py} +226 -258
  27. flashforge/capabilities/printer_capabilities.py +145 -0
  28. flashforge/capabilities/registry.py +125 -0
  29. flashforge/capabilities/resolve_model.py +61 -0
  30. flashforge/discovery/__init__.py +39 -39
  31. flashforge/discovery/discovery.py +730 -763
  32. flashforge/exceptions.py +90 -51
  33. flashforge/models/__init__.py +52 -55
  34. flashforge/models/machine_info.py +540 -543
  35. flashforge/{api/controls/info.py → models/machine_info_parser.py} +35 -242
  36. flashforge/models/responses.py +119 -254
  37. flashforge/status/__init__.py +43 -0
  38. flashforge/status/printer_snapshot.py +396 -0
  39. flashforge/tcp/__init__.py +55 -54
  40. flashforge/tcp/a3_client.py +427 -427
  41. flashforge/tcp/a4_client.py +304 -304
  42. flashforge/tcp/ff_client.py +609 -590
  43. flashforge/tcp/gcode/__init__.py +15 -13
  44. flashforge/tcp/gcode/a3_gcode_controller.py +109 -109
  45. flashforge/tcp/gcode/gcode_controller.py +292 -308
  46. flashforge/tcp/gcode/gcodes.py +81 -99
  47. flashforge/tcp/gcode/legacy_gcode_controller.py +56 -0
  48. flashforge/tcp/parsers/__init__.py +27 -27
  49. flashforge/tcp/parsers/endstop_status.py +248 -248
  50. flashforge/tcp/parsers/location_info.py +83 -83
  51. flashforge/tcp/parsers/print_status.py +180 -180
  52. flashforge/tcp/parsers/printer_info.py +146 -146
  53. flashforge/tcp/parsers/temp_info.py +218 -218
  54. flashforge/tcp/parsers/thumbnail_info.py +274 -274
  55. flashforge/tcp/tcp_client.py +52 -12
  56. flashforge/threemf/__init__.py +40 -40
  57. flashforge/threemf/parser.py +560 -560
  58. flashforge/threemf/warnings.py +58 -58
  59. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.0.0.dist-info}/METADATA +46 -47
  60. flashforge_python_api-3.0.0.dist-info/RECORD +69 -0
  61. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.0.0.dist-info}/WHEEL +1 -1
  62. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.0.0.dist-info}/licenses/LICENSE +21 -21
  63. flashforge/api/controls/__init__.py +0 -17
  64. flashforge/api/controls/control.py +0 -413
  65. flashforge/api/controls/files.py +0 -210
  66. flashforge/api/controls/job_control.py +0 -896
  67. flashforge/api/controls/temp_control.py +0 -309
  68. flashforge/client.py +0 -609
  69. flashforge_python_api-1.6.0.dist-info/RECORD +0 -52
  70. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.0.0.dist-info}/entry_points.txt +0 -0
@@ -1,258 +1,226 @@
1
- """
2
- FlashForge Python API - Creator 5 / Creator 5 Pro material-station slot color
3
- palette and perceptual nearest-color snapping.
4
-
5
- The Creator 5 ``msConfig_cmd`` only renders a color icon when the ``rgb`` field is
6
- an EXACT, case-sensitive, byte-for-byte match against one of the firmware's 24
7
- built-in palette strings (verified in firmware 1.9.2). A non-match leaves the
8
- slot's color index at 0 (White). These values
9
- DIFFER from the AD5X palette (e.g. Blue is ``#4CAAF8`` here vs ``#45A8F9`` on the
10
- AD5X), so callers must snap against THIS list specifically.
11
-
12
- By contrast the AD5X accepts freeform hex (with the ``#`` stripped), so the two
13
- wire formats are mutually exclusive — see :func:`flashforge.api.controls.control.Control.configure_slot`
14
- for the model-gating that splits them.
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- import logging
20
- import math
21
- import re
22
- from dataclasses import dataclass
23
-
24
- # The color-space math in this module mirrors the published CIEDE2000 / CIE L*a*b*
25
- # notation (L, a, b, C', h', etc.) verbatim so it can be checked against the
26
- # reference. PEP 8 lowercase locals are therefore relaxed here on purpose.
27
- # ruff: noqa: N806
28
-
29
- logger = logging.getLogger(__name__)
30
-
31
-
32
- @dataclass(frozen=True)
33
- class Creator5PaletteColor:
34
- """A single entry in the Creator 5 firmware color palette."""
35
-
36
- index: int
37
- """Firmware palette index (0 = White = the no-match fallback)."""
38
-
39
- name: str
40
- """Color name as shown on the printer UI."""
41
-
42
- hex: str # noqa: N815 - field mirrors the TS `hex` property name
43
- """Wire value sent to the printer, always uppercase ``#RRGGBB``."""
44
-
45
-
46
- #: The firmware's 24-entry UI palette (verified in firmware 1.9.2).
47
- #: Index 0 (White) is also what the firmware falls back to on a no-match.
48
- CREATOR5_PALETTE: tuple[Creator5PaletteColor, ...] = (
49
- Creator5PaletteColor(0, "White", "#FFFFFF"),
50
- Creator5PaletteColor(1, "Yellow", "#FFF245"),
51
- Creator5PaletteColor(2, "Light Green", "#DEF578"),
52
- Creator5PaletteColor(3, "Green", "#21CC3D"),
53
- Creator5PaletteColor(4, "Dark Green", "#167A4B"),
54
- Creator5PaletteColor(5, "Teal", "#156682"),
55
- Creator5PaletteColor(6, "Cyan", "#24E4A0"),
56
- Creator5PaletteColor(7, "Light Blue", "#7BD9F0"),
57
- Creator5PaletteColor(8, "Blue", "#4CAAF8"),
58
- Creator5PaletteColor(9, "Dark Blue", "#2E54DD"),
59
- Creator5PaletteColor(10, "Purple", "#48358C"),
60
- Creator5PaletteColor(11, "Violet", "#A341F7"),
61
- Creator5PaletteColor(12, "Magenta", "#F435F6"),
62
- Creator5PaletteColor(13, "Pink", "#D5B4DE"),
63
- Creator5PaletteColor(14, "Coral", "#FA6173"),
64
- Creator5PaletteColor(15, "Red", "#F82D29"),
65
- Creator5PaletteColor(16, "Brown", "#805003"),
66
- Creator5PaletteColor(17, "Orange", "#F9903B"),
67
- Creator5PaletteColor(18, "Cream", "#FCEBD7"),
68
- Creator5PaletteColor(19, "Tan", "#D5C5A1"),
69
- Creator5PaletteColor(20, "Dark Brown", "#B17C38"),
70
- Creator5PaletteColor(21, "Gray", "#8C8C89"),
71
- Creator5PaletteColor(22, "Light Gray", "#BEBEBE"),
72
- Creator5PaletteColor(23, "Black", "#1B1B1B"),
73
- )
74
-
75
- # 25^7, the CIEDE2000 chroma weighting constant.
76
- _25_POW_7 = 25.0**7
77
-
78
- # D65 reference white point used by the sRGB -> XYZ transform.
79
- _D65_XN = 0.95047
80
- _D65_YN = 1.0
81
- _D65_ZN = 1.08883
82
-
83
-
84
- def _srgb_to_linear(channel: float) -> float:
85
- """sRGB component (0-255) channel transfer function -> linear value (0-1)."""
86
- c = channel / 255.0
87
- return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
88
-
89
-
90
- def _rgb_to_lab(r: float, g: float, b: float) -> tuple[float, float, float]:
91
- """
92
- Converts an sRGB color (0-255 channels) to CIE L*a*b* under a D65 illuminant.
93
- Used as the perceptual basis for the CIEDE2000 nearest-color match.
94
- """
95
- R = _srgb_to_linear(r)
96
- G = _srgb_to_linear(g)
97
- B = _srgb_to_linear(b)
98
-
99
- x = R * 0.4124564 + G * 0.3575761 + B * 0.1804375
100
- y = R * 0.2126729 + G * 0.7151522 + B * 0.072175
101
- z = R * 0.0193339 + G * 0.119192 + B * 0.9503041
102
-
103
- x /= _D65_XN
104
- y /= _D65_YN
105
- z /= _D65_ZN
106
-
107
- def f(t: float) -> float:
108
- return math.cbrt(t) if t > 0.008856 else 7.787 * t + 16.0 / 116.0
109
-
110
- fx = f(x)
111
- fy = f(y)
112
- fz = f(z)
113
-
114
- return (116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz))
115
-
116
-
117
- def _atan2_deg(ordinate: float, abscissa: float) -> float:
118
- """atan2 -> hue in degrees, normalized to [0, 360)."""
119
- h = math.degrees(math.atan2(ordinate, abscissa))
120
- if h < 0:
121
- h += 360.0
122
- return h
123
-
124
-
125
- def _delta_e_2000(c1: tuple[float, float, float], c2: tuple[float, float, float]) -> float:
126
- """
127
- CIEDE2000 color difference between two L*a*b* colors (kL=kC=kH=1). This is the
128
- most accurate standard delta-E metric and is preferred here because the
129
- firmware renders only an exact palette match — snapping to the wrong
130
- perceptual neighbor would display the wrong color on the printer.
131
- """
132
- L1, a1, b1 = c1
133
- L2, a2, b2 = c2
134
-
135
- C1 = math.sqrt(a1 * a1 + b1 * b1)
136
- C2 = math.sqrt(a2 * a2 + b2 * b2)
137
- Cbar = (C1 + C2) / 2.0
138
- Cbar7 = Cbar**7
139
- G = 0.5 * (1 - math.sqrt(Cbar7 / (Cbar7 + _25_POW_7)))
140
-
141
- a1p = (1 + G) * a1
142
- a2p = (1 + G) * a2
143
- C1p = math.sqrt(a1p * a1p + b1 * b1)
144
- C2p = math.sqrt(a2p * a2p + b2 * b2)
145
- h1p = _atan2_deg(b1, a1p)
146
- h2p = _atan2_deg(b2, a2p)
147
-
148
- dLp = L2 - L1
149
- dCp = C2p - C1p
150
- if C1p * C2p == 0:
151
- dhp = 0.0
152
- else:
153
- diff = h2p - h1p
154
- if abs(diff) <= 180:
155
- dhp = diff
156
- elif diff > 180:
157
- dhp = diff - 360
158
- else:
159
- dhp = diff + 360
160
- dHp = 2 * math.sqrt(C1p * C2p) * math.sin(math.radians(dhp) / 2.0)
161
-
162
- Lbarp = (L1 + L2) / 2.0
163
- Cbarp = (C1p + C2p) / 2.0
164
- if C1p * C2p == 0:
165
- hbarp = h1p + h2p
166
- else:
167
- diff = abs(h1p - h2p)
168
- if diff <= 180:
169
- hbarp = (h1p + h2p) / 2.0
170
- elif h1p + h2p < 360:
171
- hbarp = (h1p + h2p + 360) / 2.0
172
- else:
173
- hbarp = (h1p + h2p - 360) / 2.0
174
-
175
- T = (
176
- 1
177
- - 0.17 * math.cos(math.radians(hbarp - 30))
178
- + 0.24 * math.cos(math.radians(2 * hbarp))
179
- + 0.32 * math.cos(math.radians(3 * hbarp + 6))
180
- - 0.20 * math.cos(math.radians(4 * hbarp - 63))
181
- )
182
-
183
- dTheta = 30 * math.exp(-(((hbarp - 275) / 25.0) ** 2))
184
- Cbarp7 = Cbarp**7
185
- RC = 2 * math.sqrt(Cbarp7 / (Cbarp7 + _25_POW_7))
186
- SL = 1 + (0.015 * (Lbarp - 50) ** 2) / math.sqrt(20 + (Lbarp - 50) ** 2)
187
- SC = 1 + 0.045 * Cbarp
188
- SH = 1 + 0.015 * Cbarp * T
189
- RT = -math.sin(math.radians(2 * dTheta)) * RC
190
-
191
- termL = dLp / SL
192
- termC = dCp / SC
193
- termH = dHp / SH
194
-
195
- return math.sqrt(termL * termL + termC * termC + termH * termH + RT * termC * termH)
196
-
197
-
198
- _HEX_RE = re.compile(r"^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$")
199
-
200
-
201
- def _hex_to_rgb(hex_str: str) -> tuple[int, int, int] | None:
202
- """
203
- Parses a hex color string (``#RRGGBB``, ``RRGGBB``, 3-digit shorthand, any
204
- case) into its RGB channels. Returns None for unparseable input.
205
- """
206
- clean = hex_str.strip()
207
- # Remove a single leading "#" (matches the TS replace(/^#/, '')).
208
- if clean.startswith("#"):
209
- clean = clean[1:]
210
- if not _HEX_RE.match(clean):
211
- return None
212
- if len(clean) == 3:
213
- clean = "".join(ch + ch for ch in clean)
214
- return (int(clean[0:2], 16), int(clean[2:4], 16), int(clean[4:6], 16))
215
-
216
-
217
- # Palette entries with their L*a*b* values precomputed once at module load.
218
- _PALETTE_LAB: list[tuple[Creator5PaletteColor, tuple[float, float, float]]] = []
219
- for _color in CREATOR5_PALETTE:
220
- _rgb = _hex_to_rgb(_color.hex)
221
- if _rgb is None:
222
- _rgb = (0, 0, 0)
223
- _PALETTE_LAB.append((_color, _rgb_to_lab(_rgb[0], _rgb[1], _rgb[2])))
224
-
225
-
226
- def snap_to_creator5_palette(hex_str: str) -> Creator5PaletteColor:
227
- """
228
- Snaps an arbitrary hex color to the nearest entry in the Creator 5 firmware
229
- palette using the CIEDE2000 perceptual distance in CIE L*a*b* space.
230
-
231
- The returned :attr:`Creator5PaletteColor.hex` is always uppercase ``#RRGGBB``
232
- and is guaranteed to be a byte-for-byte firmware match. Unparseable input
233
- falls back to White (index 0, the firmware's own no-match fallback) with a
234
- warning.
235
-
236
- Args:
237
- hex_str: The caller's color as a hex string (leading ``#`` optional, any case).
238
-
239
- Returns:
240
- The nearest Creator 5 palette entry.
241
- """
242
- rgb = _hex_to_rgb(hex_str)
243
- if rgb is None:
244
- logger.warning(
245
- 'snap_to_creator5_palette: could not parse "%s" as hex; falling back to White.',
246
- hex_str,
247
- )
248
- return CREATOR5_PALETTE[0]
249
-
250
- target = _rgb_to_lab(rgb[0], rgb[1], rgb[2])
251
- best = _PALETTE_LAB[0]
252
- best_delta = float("inf")
253
- for entry in _PALETTE_LAB:
254
- delta = _delta_e_2000(target, entry[1])
255
- if delta < best_delta:
256
- best_delta = delta
257
- best = entry
258
- return best[0]
1
+ """
2
+ Shared palette types and CIEDE2000 nearest-color snapping.
3
+
4
+ A material-station printer draws a slot color icon only when the color is an exact,
5
+ case-sensitive match with one entry of its own 24-entry firmware palette, sent as
6
+ uppercase ``#RRGGBB``. The AD5X and the Creator 5 series have different palettes
7
+ (see :mod:`.ad5x_palette` and :mod:`.creator5_palette`); this module holds the math
8
+ they share.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import math
15
+ import re
16
+ from collections.abc import Sequence
17
+ from dataclasses import dataclass
18
+
19
+ # The color-space math in this module mirrors the published CIEDE2000 / CIE L*a*b*
20
+ # notation (L, a, b, C', h', etc.) verbatim so it can be checked against the
21
+ # reference. PEP 8 lowercase locals are therefore relaxed here on purpose.
22
+ # ruff: noqa: N806
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class PaletteColor:
29
+ """A single entry in a printer's firmware color palette."""
30
+
31
+ index: int
32
+ """Firmware palette index (0 = White = the no-match fallback)."""
33
+
34
+ name: str
35
+ """Color name as shown on the printer UI."""
36
+
37
+ hex: str
38
+ """Wire value sent to the printer, always uppercase ``#RRGGBB``."""
39
+
40
+
41
+ Lab = tuple[float, float, float]
42
+ PaletteLab = list[tuple[PaletteColor, Lab]]
43
+
44
+
45
+ # 25^7, the CIEDE2000 chroma weighting constant.
46
+ _25_POW_7 = 25.0**7
47
+
48
+ # D65 reference white point used by the sRGB -> XYZ transform.
49
+ _D65_XN = 0.95047
50
+ _D65_YN = 1.0
51
+ _D65_ZN = 1.08883
52
+
53
+
54
+ def _srgb_to_linear(channel: float) -> float:
55
+ """sRGB component (0-255) channel transfer function -> linear value (0-1)."""
56
+ c = channel / 255.0
57
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
58
+
59
+
60
+ def _rgb_to_lab(r: float, g: float, b: float) -> tuple[float, float, float]:
61
+ """
62
+ Converts an sRGB color (0-255 channels) to CIE L*a*b* under a D65 illuminant.
63
+ Used as the perceptual basis for the CIEDE2000 nearest-color match.
64
+ """
65
+ R = _srgb_to_linear(r)
66
+ G = _srgb_to_linear(g)
67
+ B = _srgb_to_linear(b)
68
+
69
+ x = R * 0.4124564 + G * 0.3575761 + B * 0.1804375
70
+ y = R * 0.2126729 + G * 0.7151522 + B * 0.072175
71
+ z = R * 0.0193339 + G * 0.119192 + B * 0.9503041
72
+
73
+ x /= _D65_XN
74
+ y /= _D65_YN
75
+ z /= _D65_ZN
76
+
77
+ def f(t: float) -> float:
78
+ return math.cbrt(t) if t > 0.008856 else 7.787 * t + 16.0 / 116.0
79
+
80
+ fx = f(x)
81
+ fy = f(y)
82
+ fz = f(z)
83
+
84
+ return (116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz))
85
+
86
+
87
+ def _atan2_deg(ordinate: float, abscissa: float) -> float:
88
+ """atan2 -> hue in degrees, normalized to [0, 360)."""
89
+ h = math.degrees(math.atan2(ordinate, abscissa))
90
+ if h < 0:
91
+ h += 360.0
92
+ return h
93
+
94
+
95
+ def _delta_e_2000(c1: tuple[float, float, float], c2: tuple[float, float, float]) -> float:
96
+ """
97
+ CIEDE2000 color difference between two L*a*b* colors (kL=kC=kH=1). This is the
98
+ most accurate standard delta-E metric and is preferred here because the
99
+ firmware renders only an exact palette match — snapping to the wrong
100
+ perceptual neighbor would display the wrong color on the printer.
101
+ """
102
+ L1, a1, b1 = c1
103
+ L2, a2, b2 = c2
104
+
105
+ C1 = math.sqrt(a1 * a1 + b1 * b1)
106
+ C2 = math.sqrt(a2 * a2 + b2 * b2)
107
+ Cbar = (C1 + C2) / 2.0
108
+ Cbar7 = Cbar**7
109
+ G = 0.5 * (1 - math.sqrt(Cbar7 / (Cbar7 + _25_POW_7)))
110
+
111
+ a1p = (1 + G) * a1
112
+ a2p = (1 + G) * a2
113
+ C1p = math.sqrt(a1p * a1p + b1 * b1)
114
+ C2p = math.sqrt(a2p * a2p + b2 * b2)
115
+ h1p = _atan2_deg(b1, a1p)
116
+ h2p = _atan2_deg(b2, a2p)
117
+
118
+ dLp = L2 - L1
119
+ dCp = C2p - C1p
120
+ if C1p * C2p == 0:
121
+ dhp = 0.0
122
+ else:
123
+ diff = h2p - h1p
124
+ if abs(diff) <= 180:
125
+ dhp = diff
126
+ elif diff > 180:
127
+ dhp = diff - 360
128
+ else:
129
+ dhp = diff + 360
130
+ dHp = 2 * math.sqrt(C1p * C2p) * math.sin(math.radians(dhp) / 2.0)
131
+
132
+ Lbarp = (L1 + L2) / 2.0
133
+ Cbarp = (C1p + C2p) / 2.0
134
+ if C1p * C2p == 0:
135
+ hbarp = h1p + h2p
136
+ else:
137
+ diff = abs(h1p - h2p)
138
+ if diff <= 180:
139
+ hbarp = (h1p + h2p) / 2.0
140
+ elif h1p + h2p < 360:
141
+ hbarp = (h1p + h2p + 360) / 2.0
142
+ else:
143
+ hbarp = (h1p + h2p - 360) / 2.0
144
+
145
+ T = (
146
+ 1
147
+ - 0.17 * math.cos(math.radians(hbarp - 30))
148
+ + 0.24 * math.cos(math.radians(2 * hbarp))
149
+ + 0.32 * math.cos(math.radians(3 * hbarp + 6))
150
+ - 0.20 * math.cos(math.radians(4 * hbarp - 63))
151
+ )
152
+
153
+ dTheta = 30 * math.exp(-(((hbarp - 275) / 25.0) ** 2))
154
+ Cbarp7 = Cbarp**7
155
+ RC = 2 * math.sqrt(Cbarp7 / (Cbarp7 + _25_POW_7))
156
+ SL = 1 + (0.015 * (Lbarp - 50) ** 2) / math.sqrt(20 + (Lbarp - 50) ** 2)
157
+ SC = 1 + 0.045 * Cbarp
158
+ SH = 1 + 0.015 * Cbarp * T
159
+ RT = -math.sin(math.radians(2 * dTheta)) * RC
160
+
161
+ termL = dLp / SL
162
+ termC = dCp / SC
163
+ termH = dHp / SH
164
+
165
+ return math.sqrt(termL * termL + termC * termC + termH * termH + RT * termC * termH)
166
+
167
+
168
+ _HEX_RE = re.compile(r"^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$")
169
+
170
+
171
+ def _hex_to_rgb(hex_str: str) -> tuple[int, int, int] | None:
172
+ """
173
+ Parses a hex color string (``#RRGGBB``, ``RRGGBB``, ``#RRGGBBAA`` with the alpha
174
+ ignored, 3-digit shorthand, any case) into its RGB channels. Returns None for
175
+ unparseable input.
176
+ """
177
+ clean = hex_str.strip()
178
+ # Remove a single leading "#" (matches the TS replace(/^#/, '')).
179
+ if clean.startswith("#"):
180
+ clean = clean[1:]
181
+ if len(clean) == 8 and re.fullmatch(r"[0-9a-fA-F]{8}", clean):
182
+ clean = clean[:6]
183
+ if not _HEX_RE.match(clean):
184
+ return None
185
+ if len(clean) == 3:
186
+ clean = "".join(ch + ch for ch in clean)
187
+ return (int(clean[0:2], 16), int(clean[2:4], 16), int(clean[4:6], 16))
188
+
189
+
190
+ def hex_to_rgb(hex_str: str) -> tuple[int, int, int] | None:
191
+ """Public alias of the hex parser (``#RRGGBB``, ``RRGGBB``, ``#RRGGBBAA`` or 3-digit)."""
192
+ return _hex_to_rgb(hex_str)
193
+
194
+
195
+ def build_palette_lab(palette: Sequence[PaletteColor]) -> PaletteLab:
196
+ """Precomputes a palette's L*a*b* values once, at module load."""
197
+ entries: PaletteLab = []
198
+ for color in palette:
199
+ rgb = _hex_to_rgb(color.hex) or (0, 0, 0)
200
+ entries.append((color, _rgb_to_lab(rgb[0], rgb[1], rgb[2])))
201
+ return entries
202
+
203
+
204
+ def snap_to_palette(hex_str: str, palette_lab: PaletteLab, palette_name: str) -> PaletteColor:
205
+ """
206
+ Snaps an arbitrary hex color to the nearest palette entry by CIEDE2000 distance.
207
+
208
+ Unparseable input falls back to the first entry, which on both firmware palettes
209
+ is White: the same value the firmware itself falls back to on a no-match.
210
+ """
211
+ rgb = _hex_to_rgb(hex_str)
212
+ if rgb is None:
213
+ logger.warning(
214
+ '%s: could not parse "%s" as hex; falling back to White.', palette_name, hex_str
215
+ )
216
+ return palette_lab[0][0]
217
+
218
+ target = _rgb_to_lab(rgb[0], rgb[1], rgb[2])
219
+ best = palette_lab[0]
220
+ best_delta = float("inf")
221
+ for entry in palette_lab:
222
+ delta = _delta_e_2000(target, entry[1])
223
+ if delta < best_delta:
224
+ best_delta = delta
225
+ best = entry
226
+ return best[0]
@@ -0,0 +1,145 @@
1
+ """
2
+ The capabilities object that a connected printer exposes to its callers.
3
+
4
+ Each feature has the same shape: ``available`` (the hardware is there) and
5
+ ``controllable`` (the API can drive it), with a ``reason`` when either is False. A UI
6
+ reads these and never looks at the model name. No field is ever undefined.
7
+
8
+ This object holds hardware facts only. Per-printer user settings (force-legacy mode)
9
+ are connect options and do not appear here.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Literal
16
+
17
+ from .models import BackendFamily, PrinterModelId
18
+ from .registry import ModelSpec, get_model_spec
19
+
20
+ LedTransport = Literal["http", "tcp", "none"]
21
+
22
+ NO_TCP = "This printer has no TCP command channel."
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class FeatureSupport:
27
+ """One feature of a printer."""
28
+
29
+ available: bool
30
+ controllable: bool
31
+ #: Plain-language reason when ``available`` or ``controllable`` is False.
32
+ reason: str | None = None
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class LedSupport(FeatureSupport):
37
+ """The light control feature and how it is driven."""
38
+
39
+ #: ``http`` = factory LED (``lightControl_cmd``), ``tcp`` = custom LED (G-code), ``none``.
40
+ transport: LedTransport = "none"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class MaterialStationSupport(FeatureSupport):
45
+ """The material station feature."""
46
+
47
+ slot_count: int = 0
48
+ #: The API can load and unload filament. AD5X only.
49
+ load_unload: bool = False
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class PrinterCapabilities:
54
+ """Everything a caller needs to know about what a connected printer can do."""
55
+
56
+ model: PrinterModelId
57
+ display_name: str
58
+ family: BackendFamily
59
+ tool_count: int
60
+ #: The printer runs a TCP command server. False for the Creator 5 series.
61
+ tcp_command_channel: bool
62
+ #: Raw G-code passthrough and axis homing. Needs the TCP command channel.
63
+ gcode: FeatureSupport
64
+ led: LedSupport
65
+ camera: FeatureSupport
66
+ filtration: FeatureSupport
67
+ chamber: FeatureSupport
68
+ material_station: MaterialStationSupport
69
+ #: A real door sensor.
70
+ door_sensor: bool
71
+ #: An air-quality (TVOC) reading in the status (``PrinterSnapshot.filtration.tvoc_level``).
72
+ #: Adventurer 5M Pro only: the other models report a fixed 0.
73
+ air_quality_sensor: bool
74
+ #: Values for this model are confirmed on real hardware. False for the Creator 5 series.
75
+ hardware_verified: bool
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class PrinterReport:
80
+ """What the connected printer reports about itself. None = not reported."""
81
+
82
+ #: ``/detail`` shows a camera.
83
+ camera_available: bool | None = None
84
+
85
+
86
+ def _feature(available: bool, controllable: bool, reason: str) -> FeatureSupport:
87
+ if available and controllable:
88
+ return FeatureSupport(available, controllable)
89
+ return FeatureSupport(available, controllable, reason)
90
+
91
+
92
+ def _build_led(spec: ModelSpec) -> LedSupport:
93
+ """
94
+ The light comes from the model. Every modern printer (5M, 5M Pro, AD5X, Creator 5 series)
95
+ drives a light with ``lightControl_cmd``, also a light the user fitted, even when
96
+ ``/product`` reports ``lightCtrlState: 0`` (the base 5M and the AD5X always report 0). So
97
+ ``/product`` is not read for the light. Legacy printers drive it over TCP (M146).
98
+ """
99
+ if spec.family == BackendFamily.LEGACY:
100
+ return LedSupport(True, True, transport="tcp")
101
+ if spec.family == BackendFamily.UNKNOWN:
102
+ return LedSupport(False, False, "The printer model is not known.", transport="none")
103
+ return LedSupport(True, True, transport="http")
104
+
105
+
106
+ def resolve_capabilities(
107
+ model: PrinterModelId,
108
+ report: PrinterReport | None = None,
109
+ ) -> PrinterCapabilities:
110
+ """
111
+ Builds the capabilities for a model, merged with what the printer reports.
112
+ Fields with trust ``model`` ignore the report (see ``FIELD_TRUST``).
113
+ """
114
+ spec = get_model_spec(model)
115
+ has_tcp = spec.tcp_command_channel
116
+ station = spec.material_station_slots > 0
117
+ camera = bool(report and report.camera_available is True)
118
+ return PrinterCapabilities(
119
+ model=spec.id,
120
+ display_name=spec.display_name,
121
+ family=spec.family,
122
+ tool_count=spec.tool_count,
123
+ tcp_command_channel=has_tcp,
124
+ gcode=_feature(has_tcp, has_tcp, NO_TCP),
125
+ led=_build_led(spec),
126
+ camera=_feature(camera, camera, "The printer does not report a camera."),
127
+ filtration=_feature(
128
+ spec.filtration,
129
+ spec.filtration,
130
+ "Only the Adventurer 5M Pro has air filtration that the API can control.",
131
+ ),
132
+ chamber=_feature(
133
+ spec.chamber_heater, spec.chamber_heater, "Only the Creator 5 Pro has a heated chamber."
134
+ ),
135
+ material_station=MaterialStationSupport(
136
+ station,
137
+ station,
138
+ None if station else "This printer has no material station.",
139
+ slot_count=spec.material_station_slots,
140
+ load_unload=spec.material_station_load_unload,
141
+ ),
142
+ door_sensor=spec.door_sensor,
143
+ air_quality_sensor=spec.air_quality_sensor,
144
+ hardware_verified=spec.hardware_verified,
145
+ )