flashforge-python-api 1.5.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 (71) hide show
  1. flashforge/__init__.py +337 -233
  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 -0
  57. flashforge/threemf/parser.py +560 -0
  58. flashforge/threemf/warnings.py +58 -0
  59. flashforge_python_api-3.0.0.dist-info/METADATA +184 -0
  60. flashforge_python_api-3.0.0.dist-info/RECORD +69 -0
  61. {flashforge_python_api-1.5.0.dist-info → flashforge_python_api-3.0.0.dist-info}/WHEEL +1 -1
  62. {flashforge_python_api-1.5.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 -880
  67. flashforge/api/controls/temp_control.py +0 -309
  68. flashforge/client.py +0 -609
  69. flashforge_python_api-1.5.0.dist-info/METADATA +0 -152
  70. flashforge_python_api-1.5.0.dist-info/RECORD +0 -49
  71. {flashforge_python_api-1.5.0.dist-info → flashforge_python_api-3.0.0.dist-info}/entry_points.txt +0 -0
@@ -1,543 +1,540 @@
1
- """
2
- FlashForge Python API - Data Models
3
- """
4
-
5
- from __future__ import annotations
6
-
7
- import re
8
- from datetime import datetime
9
- from enum import Enum
10
- from typing import Any
11
-
12
- from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
13
-
14
- # ---------------------------------------------------------------------------
15
- # Validation policy for inbound firmware payloads
16
- # ---------------------------------------------------------------------------
17
- #
18
- # Models parsed FROM the printer carry types but NOT value ranges, and no
19
- # required fields beyond what we genuinely cannot work without. The reason is
20
- # blast radius: pydantic fails a model as a unit, and `Info.get_detail_response`
21
- # turns any failure into "no data", which Home Assistant shows as an offline
22
- # printer. So a `ge=0` on a field nobody reads could take the whole integration
23
- # down. That is exactly what happened in ff-5mp-hass#18, where a Creator 5 reporting
24
- # `chamberTemp: -108` made every entity unavailable and the config flow report
25
- # `cannot_connect`.
26
- #
27
- # Range constraints belong on OUTBOUND command models (see responses.py), where
28
- # the values are ours and a bad one is our bug. Inbound, we take what we need
29
- # and tolerate the rest. This mirrors the TypeScript client (ff-5mp-api-ts),
30
- # which has never hit this class of failure.
31
- #
32
- # Firmware signals "this sensor does not exist" with an out-of-band negative
33
- # sentinel rather than by omitting the field: -108 on a chamber-less Creator 5,
34
- # and -100 is our own "heater off" value (TempControl.TEMP_OFF). Anything at or
35
- # below this floor is a marker, not a reading.
36
- TEMP_SENTINEL_FLOOR = -50.0
37
-
38
- _HEX_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
39
-
40
-
41
- def sanitize_temperature(value: Any) -> Any:
42
- """
43
- Map firmware temperature sentinels to None, passing everything else through.
44
-
45
- Non-numeric input is returned untouched so normal type validation still
46
- reports it. Used as a `mode="before"` validator on every inbound
47
- temperature field.
48
- """
49
- if isinstance(value, bool) or not isinstance(value, (int, float)):
50
- return value
51
- return None if value <= TEMP_SENTINEL_FLOOR else value
52
-
53
-
54
- def _normalize_hex_color(value: Any) -> Any:
55
- """
56
- Coerce a material color into `#RRGGBB`, or an empty string when it is not
57
- recognizable.
58
-
59
- Never raises. An unparseable color costs a swatch its color; it must not
60
- cost the caller the entire /detail response.
61
- """
62
- if not isinstance(value, str):
63
- return "" if value is None else value
64
-
65
- candidate = value.strip()
66
- if candidate == "" or _HEX_COLOR_RE.match(candidate):
67
- return candidate
68
-
69
- # Accept the shorthand `#RGB` form by expanding it, and a bare `RRGGBB`
70
- # without the leading hash - both are plausible firmware variations.
71
- if re.match(r"^#[0-9A-Fa-f]{3}$", candidate):
72
- return "#" + "".join(char * 2 for char in candidate[1:])
73
- if re.match(r"^[0-9A-Fa-f]{6}$", candidate):
74
- return f"#{candidate}"
75
- return ""
76
-
77
-
78
- class MachineState(Enum):
79
- """Enumerates the possible operational states of the FlashForge 3D printer."""
80
-
81
- READY = "ready"
82
- BUSY = "busy"
83
- CALIBRATING = "calibrating"
84
- ERROR = "error"
85
- HEATING = "heating"
86
- PRINTING = "printing"
87
- PAUSING = "pausing"
88
- PAUSED = "paused"
89
- CANCELLED = "cancelled"
90
- COMPLETED = "completed"
91
- UNKNOWN = "unknown"
92
-
93
-
94
- class Temperature(BaseModel):
95
- """Represents a pair of current and target temperatures for a component like an extruder or print bed."""
96
-
97
- # `extra="forbid"` deliberately: this model is never parsed from a printer
98
- # payload, only constructed by MachineInfoParser.from_detail. Forbidding
99
- # extras there catches a typo'd keyword argument in our own parser, which
100
- # `extra="allow"` would silently absorb.
101
- model_config = ConfigDict(extra="forbid")
102
-
103
- # No range constraints: MachineInfoParser feeds these straight from firmware
104
- # values, so a range here fails `from_detail` for the same reason a range on
105
- # FFPrinterDetail fails the response - one odd reading, no data at all.
106
- current: float = Field(default=0.0, description="The current temperature in Celsius")
107
- set: float = Field(default=0.0, description="The target (set) temperature in Celsius")
108
-
109
-
110
- class SlotInfo(BaseModel):
111
- """Information about a single slot in the material station."""
112
-
113
- # `extra="allow"`: inbound, nested under FFPrinterDetail.matl_station_info.
114
- # FFPrinterDetail allowing extras is not enough on its own - a new field on
115
- # a *child* fails validation for the whole /detail response, and
116
- # `Info.get_detail_response` swallows that and returns None, which the HA
117
- # integration reports as "could not retrieve printer information".
118
- model_config = ConfigDict(extra="allow", populate_by_name=True)
119
-
120
- # Every field defaulted: a slot missing one attribute must cost that
121
- # attribute, not the whole /detail response. `slot_id` carries no 1-4 range
122
- # for the same reason - a station reporting a fifth slot should show up as a
123
- # slot we ignore, not as an offline printer.
124
- has_filament: bool = Field(
125
- default=False,
126
- alias="hasFilament",
127
- description="Indicates if filament is present in this slot",
128
- )
129
- material_color: str = Field(
130
- default="",
131
- alias="materialColor",
132
- description="Color of the material in this slot (e.g., '#FFFFFF')",
133
- )
134
- material_name: str = Field(
135
- default="",
136
- alias="materialName",
137
- description="Name of the material in this slot (e.g., 'PLA')",
138
- )
139
- slot_id: int = Field(default=0, alias="slotId", description="Identifier for this slot (1-4)")
140
-
141
- @field_validator("material_color", mode="before")
142
- @classmethod
143
- def normalize_material_color(cls, v: Any) -> Any:
144
- """Normalize the material color, falling back to '' rather than raising."""
145
- return _normalize_hex_color(v)
146
-
147
-
148
- class MatlStationInfo(BaseModel):
149
- """Detailed information about the material station."""
150
-
151
- # `extra="allow"`: inbound, see SlotInfo.
152
- model_config = ConfigDict(extra="allow", populate_by_name=True)
153
-
154
- # Defaulted and unconstrained throughout, per the inbound policy at the top
155
- # of this module. `slot_infos` in particular had `min_length=1`, which made
156
- # an explicitly empty `slotInfos: []` - a station with nothing loaded - fail
157
- # the entire /detail response.
158
- current_load_slot: int = Field(
159
- default=0, alias="currentLoadSlot", description="Currently loading slot ID (0 if none)"
160
- )
161
- current_slot: int = Field(
162
- default=0, alias="currentSlot", description="Currently active/printing slot ID (0 if none)"
163
- )
164
- slot_cnt: int = Field(
165
- default=0, alias="slotCnt", description="Total number of slots in the station"
166
- )
167
- slot_infos: list[SlotInfo] = Field(
168
- default_factory=list,
169
- alias="slotInfos",
170
- description="Array of information for each slot",
171
- )
172
- state_action: int = Field(
173
- default=0, alias="stateAction", description="Current action state of the material station"
174
- )
175
- state_step: int = Field(
176
- default=0, alias="stateStep", description="Current step within the state action"
177
- )
178
-
179
-
180
- class IndepMatlInfo(BaseModel):
181
- """Information related to independent material loading, often used when a single extruder printer has a material station."""
182
-
183
- # `extra="allow"`: inbound, see SlotInfo.
184
- model_config = ConfigDict(extra="allow", populate_by_name=True)
185
-
186
- material_color: str = Field(
187
- default="", alias="materialColor", description="Color of the material"
188
- )
189
- material_name: str = Field(
190
- default="",
191
- alias="materialName",
192
- description="Name of the material (can be '?' if unknown)",
193
- )
194
- state_action: int = Field(default=0, alias="stateAction", description="Current action state")
195
- state_step: int = Field(
196
- default=0, alias="stateStep", description="Current step within the state action"
197
- )
198
-
199
- @field_validator("material_color", mode="before")
200
- @classmethod
201
- def normalize_material_color(cls, v: Any) -> Any:
202
- """Normalize the material color, falling back to '' rather than raising."""
203
- return _normalize_hex_color(v)
204
-
205
-
206
- class FFGcodeToolData(BaseModel):
207
- """Represents data for a single tool/material used in a G-code file, typically part of a multi-material print."""
208
-
209
- # `extra="allow"`: inbound, nested under FFGcodeFileEntry - which already
210
- # allows extras, but a child that forbids them reintroduces the same
211
- # names-only fallback it was flipped to avoid.
212
- model_config = ConfigDict(extra="allow", populate_by_name=True)
213
-
214
- filament_weight: float = Field(
215
- default=0.0,
216
- alias="filamentWeight",
217
- description="Calculated filament weight for this tool/material in the print",
218
- )
219
- material_color: str = Field(
220
- default="", alias="materialColor", description="Material color hex string (e.g., '#FFFF00')"
221
- )
222
- material_name: str = Field(
223
- default="", alias="materialName", description="Name of the material (e.g., 'PLA')"
224
- )
225
- slot_id: int = Field(
226
- default=0,
227
- alias="slotId",
228
- description="Slot ID from the material station, if applicable (0 if not or direct)",
229
- )
230
- tool_id: int = Field(default=0, alias="toolId", description="Tool ID or extruder number (0-3)")
231
-
232
- @field_validator("material_color", mode="before")
233
- @classmethod
234
- def normalize_material_color(cls, v: Any) -> Any:
235
- """Normalize the material color, falling back to '' rather than raising."""
236
- return _normalize_hex_color(v)
237
-
238
-
239
- class FFGcodeFileEntry(BaseModel):
240
- """Represents a single G-code file entry as returned by the /gcodeList endpoint, especially for printers like AD5X that provide detailed material info."""
241
-
242
- # `extra="allow"`, matching FFPrinterDetail: a firmware update that adds one
243
- # field must not fail validation, because Files.get_recent_file_list falls
244
- # back to a names-only list when it does - silently dropping print time,
245
- # filament weight, and the per-tool material data for EVERY file.
246
- model_config = ConfigDict(extra="allow", populate_by_name=True)
247
-
248
- # `gcode_file_name` stays required - it is the one field without which the
249
- # entry means nothing, so failing here is honest. Everything else is
250
- # metadata and gets a default.
251
- gcode_file_name: str = Field(
252
- alias="gcodeFileName", description="The name of the G-code file (e.g., 'FISH_PLA.3mf')"
253
- )
254
- gcode_tool_cnt: int | None = Field(
255
- default=None,
256
- alias="gcodeToolCnt",
257
- description="Number of tools/materials used in this G-code file",
258
- )
259
- gcode_tool_datas: list[FFGcodeToolData] | None = Field(
260
- default=None,
261
- alias="gcodeToolDatas",
262
- description="Array of detailed information for each tool/material",
263
- )
264
- printing_time: int = Field(
265
- default=0, alias="printingTime", description="Estimated printing time in seconds"
266
- )
267
- total_filament_weight: float | None = Field(
268
- default=None,
269
- alias="totalFilamentWeight",
270
- description="Total estimated filament weight for the print",
271
- )
272
- use_matl_station: bool | None = Field(
273
- default=None,
274
- alias="useMatlStation",
275
- description="Indicates if the G-code file is intended for use with a material station",
276
- )
277
-
278
-
279
- class FFPrinterDetail(BaseModel):
280
- """
281
- Represents the raw detailed information about a FlashForge 3D printer as obtained from its API.
282
- Properties are often in the printer's native naming format and may include string representations
283
- of boolean states (e.g., "open", "close").
284
- """
285
-
286
- model_config = ConfigDict(extra="allow")
287
-
288
- auto_shutdown: str | None = Field(default=None, alias="autoShutdown")
289
- auto_shutdown_time: int | None = Field(default=None, alias="autoShutdownTime")
290
- camera: int | None = Field(default=None, alias="camera")
291
- camera_stream_url: str | None = Field(default=None, alias="cameraStreamUrl")
292
- chamber_fan_speed: int | None = Field(default=None, alias="chamberFanSpeed")
293
- chamber_target_temp: float | None = Field(default=None, alias="chamberTargetTemp")
294
- chamber_temp: float | None = Field(default=None, alias="chamberTemp")
295
- clear_fan_status: str | None = Field(default=None, alias="clearFanStatus")
296
- cooling_fan_speed: int | None = Field(default=None, alias="coolingFanSpeed")
297
- cooling_fan_left_speed: int | None = Field(default=None, alias="coolingFanLeftSpeed")
298
- coordinate: list[float] | None = Field(default=None, alias="coordinate")
299
- cumulative_filament: float | None = Field(default=None, alias="cumulativeFilament")
300
- cumulative_print_time: int | None = Field(default=None, alias="cumulativePrintTime")
301
- current_print_speed: int | None = Field(default=None, alias="currentPrintSpeed")
302
- door_status: str | None = Field(default=None, alias="doorStatus")
303
- error_code: str | None = Field(default=None, alias="errorCode")
304
- estimated_left_len: float | None = Field(default=None, alias="estimatedLeftLen")
305
- estimated_left_weight: float | None = Field(default=None, alias="estimatedLeftWeight")
306
- estimated_right_len: float | None = Field(default=None, alias="estimatedRightLen")
307
- estimated_right_weight: float | None = Field(default=None, alias="estimatedRightWeight")
308
- estimated_time: float | None = Field(default=None, alias="estimatedTime")
309
- extrude_ctrl: int | None = Field(default=None, alias="extrudeCtrl")
310
- external_fan_status: str | None = Field(default=None, alias="externalFanStatus")
311
- fill_amount: float | None = Field(default=None, alias="fillAmount")
312
- firmware_version: str | None = Field(default=None, alias="firmwareVersion")
313
- flash_register_code: str | None = Field(default=None, alias="flashRegisterCode")
314
- # AD5X-only, and firmware omits what does not apply: the Creator 5 series
315
- # leaves this out of /detail even with four loaded slots, so None means "not
316
- # reported", NOT "no station". Never gate a feature on it - read the derived
317
- # FFMachineInfo.has_matl_station, or check matl_station_info yourself.
318
- has_matl_station: bool | None = Field(default=None, alias="hasMatlStation")
319
- matl_station_info: MatlStationInfo | None = Field(default=None, alias="matlStationInfo")
320
- indep_matl_info: IndepMatlInfo | None = Field(default=None, alias="indepMatlInfo")
321
- has_left_filament: bool | None = Field(default=None, alias="hasLeftFilament")
322
- has_right_filament: bool | None = Field(default=None, alias="hasRightFilament")
323
- internal_fan_status: str | None = Field(default=None, alias="internalFanStatus")
324
- ip_addr: str | None = Field(default=None, alias="ipAddr")
325
- left_filament_type: str | None = Field(default=None, alias="leftFilamentType")
326
- left_target_temp: float | None = Field(default=None, alias="leftTargetTemp")
327
- left_temp: float | None = Field(default=None, alias="leftTemp")
328
- light_status: str | None = Field(default=None, alias="lightStatus")
329
- location: str | None = Field(default=None, alias="location")
330
- mac_addr: str | None = Field(default=None, alias="macAddr")
331
- measure: str | None = Field(default=None, alias="measure")
332
- move_ctrl: int | None = Field(default=None, alias="moveCtrl")
333
- name: str | None = Field(default=None, alias="name")
334
- nozzle_cnt: int | None = Field(default=None, alias="nozzleCnt")
335
- nozzle_model: str | None = Field(default=None, alias="nozzleModel")
336
- nozzle_style: int | None = Field(default=None, alias="nozzleStyle")
337
- # --- Creator 5 series raw fields ---
338
- # Immutable factory model name (e.g. "Creator 5 Pro"); unlike `name` this is
339
- # not user-editable. May be absent on older firmware.
340
- model: str | None = Field(default=None, alias="model")
341
- # Per-tool current nozzle temperatures (one entry per nozzle). Multi-nozzle
342
- # Creator 5 series report these; single-nozzle models use rightTemp/leftTemp.
343
- # Entries are nullable because a sentinel reading is normalized to None by
344
- # `drop_nozzle_temperature_sentinels` below.
345
- nozzle_temps: list[float | None] | None = Field(default=None, alias="nozzleTemps")
346
- # Per-tool target nozzle temperatures (one entry per nozzle).
347
- nozzle_target_temps: list[float | None] | None = Field(
348
- default=None, alias="nozzleTargetTemps"
349
- )
350
- # Lidar / first-layer scanner presence flag (1 = present, 0 = absent).
351
- lidar: int | None = Field(default=None, alias="lidar")
352
- pid: int | None = Field(default=None, alias="pid")
353
- plat_target_temp: float | None = Field(default=None, alias="platTargetTemp")
354
- plat_temp: float | None = Field(default=None, alias="platTemp")
355
- polar_register_code: str | None = Field(default=None, alias="polarRegisterCode")
356
- print_duration: int | None = Field(default=None, alias="printDuration")
357
- print_file_name: str | None = Field(default=None, alias="printFileName")
358
- print_file_thumb_url: str | None = Field(default=None, alias="printFileThumbUrl")
359
- print_layer: int | None = Field(default=None, alias="printLayer")
360
- print_progress: float | None = Field(default=None, alias="printProgress")
361
- print_speed_adjust: int | None = Field(default=None, alias="printSpeedAdjust")
362
- remaining_disk_space: float | None = Field(default=None, alias="remainingDiskSpace")
363
- right_filament_type: str | None = Field(default=None, alias="rightFilamentType")
364
- right_target_temp: float | None = Field(default=None, alias="rightTargetTemp")
365
- right_temp: float | None = Field(default=None, alias="rightTemp")
366
- status: str | None = Field(default=None, alias="status")
367
- target_print_layer: int | None = Field(default=None, alias="targetPrintLayer")
368
- tvoc: float | None = Field(default=None, alias="tvoc")
369
- z_axis_compensation: float | None = Field(default=None, alias="zAxisCompensation")
370
-
371
- # Firmware reports absent temperature hardware with a negative sentinel
372
- # (-108 on a chamber-less Creator 5, ff-5mp-hass#18) rather than by omitting the
373
- # field. Map those to None here so "no sensor" reads as "not reported"
374
- # everywhere downstream, instead of as a -108 C reading or a hard failure.
375
- @field_validator(
376
- "chamber_temp",
377
- "chamber_target_temp",
378
- "left_temp",
379
- "left_target_temp",
380
- "plat_temp",
381
- "plat_target_temp",
382
- "right_temp",
383
- "right_target_temp",
384
- mode="before",
385
- )
386
- @classmethod
387
- def drop_temperature_sentinels(cls, v: Any) -> Any:
388
- """Replace out-of-band 'no sensor' temperature markers with None."""
389
- return sanitize_temperature(v)
390
-
391
- @field_validator("nozzle_temps", "nozzle_target_temps", mode="before")
392
- @classmethod
393
- def drop_nozzle_temperature_sentinels(cls, v: Any) -> Any:
394
- """Apply the same sentinel handling to the per-tool temperature arrays."""
395
- if not isinstance(v, list):
396
- return v
397
- return [sanitize_temperature(entry) for entry in v]
398
-
399
-
400
- class FFMachineInfo(BaseModel):
401
- """
402
- Represents a structured and user-friendly model of the printer's information and state.
403
- This interface is populated by transforming data from FFPrinterDetail.
404
- """
405
-
406
- # `extra="forbid"` deliberately: see Temperature. Built only at
407
- # `MachineInfoParser.from_detail`, from ~50 keyword arguments, never from
408
- # raw printer JSON - so forbidding extras is a typo check on our own code,
409
- # not a firmware-compatibility risk.
410
- model_config = ConfigDict(extra="forbid")
411
-
412
- # Auto-shutdown settings
413
- auto_shutdown: bool = False
414
- auto_shutdown_time: int = 0
415
-
416
- # Camera
417
- camera_stream_url: str = ""
418
-
419
- # Fan speeds
420
- chamber_fan_speed: int = 0
421
- cooling_fan_speed: int = 0
422
- cooling_fan_left_speed: int | None = None
423
-
424
- # Cumulative stats
425
- cumulative_filament: float = 0.0
426
- cumulative_print_time: int = 0
427
-
428
- # Current print speed
429
- current_print_speed: int = 0
430
-
431
- # Disk space
432
- free_disk_space: str = "0.00"
433
-
434
- # Door and error status
435
- door_open: bool = False
436
- error_code: str = ""
437
-
438
- # Current print estimates
439
- est_length: float = 0.0
440
- est_weight: float = 0.0
441
- estimated_time: float = 0.0
442
-
443
- # Fans & LED status
444
- external_fan_on: bool = False
445
- internal_fan_on: bool = False
446
- lights_on: bool = False
447
-
448
- # Network
449
- ip_address: str = ""
450
- mac_address: str = ""
451
-
452
- # Print settings
453
- fill_amount: float = 0.0
454
- firmware_version: str = ""
455
- name: str = ""
456
- pid: int | None = None
457
- is_pro: bool = False
458
- is_ad5x: bool = False
459
- # Creator 5 / Creator 5 Pro (4-head tool-changer) detection. Drives the
460
- # http_only transport decision and Pro-only capabilities (door sensor).
461
- is_creator5: bool = False
462
- is_creator5_pro: bool = False
463
- # Immutable factory model name (e.g. "Creator 5 Pro"). Falls back to a
464
- # PID-derived name, then the user-set `name`, when the printer doesn't
465
- # report the `model` field.
466
- model: str | None = None
467
- nozzle_size: str = ""
468
- # Number of tools/nozzles the printer reports. Creator 5 series = 4
469
- # (tool-changer); single-nozzle models = 1. Mirrors len(tool_temps).
470
- nozzle_count: int | None = None
471
-
472
- # Temperatures
473
- print_bed: Temperature = Field(default_factory=Temperature)
474
- extruder: Temperature = Field(default_factory=Temperature)
475
- # Heated chamber. Only the Creator 5 series has one; other models report 0/0.
476
- chamber: Temperature | None = None
477
- # Current/target temperatures for every tool/nozzle. Single-nozzle models
478
- # report a 1-element array mirroring `extruder`; Creator 5 series report
479
- # one entry per nozzle.
480
- tool_temps: list[Temperature] = Field(default_factory=list)
481
-
482
- # Capability flags (presence-derived, never assumed from model family)
483
- has_camera: bool = False
484
- has_lidar: bool = False
485
- # Only true on models with confirmed hardware (Creator 5 Pro). When false,
486
- # `door_open` is cosmetic and should not be surfaced.
487
- has_door_sensor: bool = False
488
- # True only when the printer actually reported a chamber temperature. The
489
- # heated chamber is a Creator 5 series *option*, not a family trait: units
490
- # without it report the -108 sentinel, which FFPrinterDetail normalizes to
491
- # None. Gate chamber entities on this, never on `is_creator5`.
492
- has_chamber_sensor: bool = False
493
-
494
- # Current print stats
495
- print_duration: int = 0
496
- print_file_name: str = ""
497
- print_file_thumb_url: str = ""
498
- current_print_layer: int = 0
499
- print_progress: float = 0.0
500
- print_progress_int: int = 0
501
- print_speed_adjust: int = 0
502
- filament_type: str = ""
503
-
504
- # Machine state
505
- machine_state: MachineState = MachineState.UNKNOWN
506
- status: str = ""
507
- total_print_layers: int = 0
508
- tvoc: float = 0.0
509
- z_axis_compensation: float = 0.0
510
-
511
- # Cloud codes
512
- flash_cloud_register_code: str = ""
513
- polar_cloud_register_code: str = ""
514
-
515
- # Extras
516
- print_eta: str = "00:00"
517
- # None whenever the print is not advancing (paused, heating, ready, error,
518
- # ...). The firmware freezes `estimatedTime` outside the PRINTING state, so
519
- # an absolute timestamp derived from it would recede in real time rather
520
- # than hold. Use `print_eta` / `estimated_time` for the remaining duration,
521
- # which stays valid in every state.
522
- completion_time: datetime | None = None
523
- formatted_run_time: str = "00:00"
524
- formatted_total_run_time: str = "0h:0m"
525
-
526
- # Material Station (AD5X / Creator 5 series)
527
- #
528
- # A capability, not a passthrough: MachineInfoParser DERIVES this from the
529
- # station data rather than copying the raw `hasMatlStation` field, which the
530
- # Creator 5 series never reports even with a station attached. It is a plain
531
- # bool on purpose - there is no "unknown" state to represent, and offering
532
- # one is what let an unreported flag read as absent hardware. For the
533
- # untouched firmware value, read FFPrinterDetail.has_matl_station.
534
- has_matl_station: bool = False
535
- matl_station_info: MatlStationInfo | None = None
536
- indep_matl_info: IndepMatlInfo | None = None
537
-
538
- @model_validator(mode="after")
539
- def validate_print_progress(self) -> FFMachineInfo:
540
- """Ensure print progress integer matches float value."""
541
- if self.print_progress is not None:
542
- self.print_progress_int = max(0, min(100, int(self.print_progress * 100)))
543
- return self
1
+ """
2
+ FlashForge Python API - Data Models
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from datetime import datetime
9
+ from enum import Enum
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
13
+
14
+ from ..capabilities.models import PrinterModelId
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Validation policy for inbound firmware payloads
18
+ # ---------------------------------------------------------------------------
19
+ #
20
+ # Models parsed FROM the printer carry types but NOT value ranges, and no
21
+ # required fields beyond what we genuinely cannot work without. The reason is
22
+ # blast radius: pydantic fails a model as a unit, and `Info.get_detail_response`
23
+ # turns any failure into "no data", which Home Assistant shows as an offline
24
+ # printer. So a `ge=0` on a field nobody reads could take the whole integration
25
+ # down. That is exactly what happened in ff-5mp-hass#18, where a Creator 5 reporting
26
+ # `chamberTemp: -108` made every entity unavailable and the config flow report
27
+ # `cannot_connect`.
28
+ #
29
+ # Range constraints belong on OUTBOUND command models (see responses.py), where
30
+ # the values are ours and a bad one is our bug. Inbound, we take what we need
31
+ # and tolerate the rest. This mirrors the TypeScript client (ff-5mp-api-ts),
32
+ # which has never hit this class of failure.
33
+ #
34
+ # Firmware signals "this sensor does not exist" with an out-of-band negative
35
+ # sentinel rather than by omitting the field: -108 on a chamber-less Creator 5,
36
+ # and -100 is our own "heater off" value (TempControl.TEMP_OFF). Anything at or
37
+ # below this floor is a marker, not a reading.
38
+ TEMP_SENTINEL_FLOOR = -50.0
39
+
40
+ _HEX_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
41
+
42
+
43
+ def sanitize_temperature(value: Any) -> Any:
44
+ """
45
+ Map firmware temperature sentinels to None, passing everything else through.
46
+
47
+ Non-numeric input is returned untouched so normal type validation still
48
+ reports it. Used as a `mode="before"` validator on every inbound
49
+ temperature field.
50
+ """
51
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
52
+ return value
53
+ return None if value <= TEMP_SENTINEL_FLOOR else value
54
+
55
+
56
+ def _normalize_hex_color(value: Any) -> Any:
57
+ """
58
+ Coerce a material color into `#RRGGBB`, or an empty string when it is not
59
+ recognizable.
60
+
61
+ Never raises. An unparseable color costs a swatch its color; it must not
62
+ cost the caller the entire /detail response.
63
+ """
64
+ if not isinstance(value, str):
65
+ return "" if value is None else value
66
+
67
+ candidate = value.strip()
68
+ if candidate == "" or _HEX_COLOR_RE.match(candidate):
69
+ return candidate
70
+
71
+ # Accept the shorthand `#RGB` form by expanding it, and a bare `RRGGBB`
72
+ # without the leading hash - both are plausible firmware variations.
73
+ if re.match(r"^#[0-9A-Fa-f]{3}$", candidate):
74
+ return "#" + "".join(char * 2 for char in candidate[1:])
75
+ if re.match(r"^[0-9A-Fa-f]{6}$", candidate):
76
+ return f"#{candidate}"
77
+ return ""
78
+
79
+
80
+ class MachineState(Enum):
81
+ """Enumerates the possible operational states of the FlashForge 3D printer."""
82
+
83
+ READY = "ready"
84
+ BUSY = "busy"
85
+ CALIBRATING = "calibrating"
86
+ ERROR = "error"
87
+ HEATING = "heating"
88
+ PRINTING = "printing"
89
+ PAUSING = "pausing"
90
+ PAUSED = "paused"
91
+ CANCELLED = "cancelled"
92
+ COMPLETED = "completed"
93
+ UNKNOWN = "unknown"
94
+
95
+
96
+ class Temperature(BaseModel):
97
+ """Represents a pair of current and target temperatures for a component like an extruder or print bed."""
98
+
99
+ # `extra="forbid"` deliberately: this model is never parsed from a printer
100
+ # payload, only constructed by MachineInfoParser.from_detail. Forbidding
101
+ # extras there catches a typo'd keyword argument in our own parser, which
102
+ # `extra="allow"` would silently absorb.
103
+ model_config = ConfigDict(extra="forbid")
104
+
105
+ # No range constraints: MachineInfoParser feeds these straight from firmware
106
+ # values, so a range here fails `from_detail` for the same reason a range on
107
+ # FFPrinterDetail fails the response - one odd reading, no data at all.
108
+ current: float = Field(default=0.0, description="The current temperature in Celsius")
109
+ set: float = Field(default=0.0, description="The target (set) temperature in Celsius")
110
+
111
+
112
+ class SlotInfo(BaseModel):
113
+ """Information about a single slot in the material station."""
114
+
115
+ # `extra="allow"`: inbound, nested under FFPrinterDetail.matl_station_info.
116
+ # FFPrinterDetail allowing extras is not enough on its own - a new field on
117
+ # a *child* fails validation for the whole /detail response, and
118
+ # `Info.get_detail_response` swallows that and returns None, which the HA
119
+ # integration reports as "could not retrieve printer information".
120
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
121
+
122
+ # Every field defaulted: a slot missing one attribute must cost that
123
+ # attribute, not the whole /detail response. `slot_id` carries no 1-4 range
124
+ # for the same reason - a station reporting a fifth slot should show up as a
125
+ # slot we ignore, not as an offline printer.
126
+ has_filament: bool = Field(
127
+ default=False,
128
+ alias="hasFilament",
129
+ description="Indicates if filament is present in this slot",
130
+ )
131
+ material_color: str = Field(
132
+ default="",
133
+ alias="materialColor",
134
+ description="Color of the material in this slot (e.g., '#FFFFFF')",
135
+ )
136
+ material_name: str = Field(
137
+ default="",
138
+ alias="materialName",
139
+ description="Name of the material in this slot (e.g., 'PLA')",
140
+ )
141
+ slot_id: int = Field(default=0, alias="slotId", description="Identifier for this slot (1-4)")
142
+
143
+ @field_validator("material_color", mode="before")
144
+ @classmethod
145
+ def normalize_material_color(cls, v: Any) -> Any:
146
+ """Normalize the material color, falling back to '' rather than raising."""
147
+ return _normalize_hex_color(v)
148
+
149
+
150
+ class MatlStationInfo(BaseModel):
151
+ """Detailed information about the material station."""
152
+
153
+ # `extra="allow"`: inbound, see SlotInfo.
154
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
155
+
156
+ # Defaulted and unconstrained throughout, per the inbound policy at the top
157
+ # of this module. `slot_infos` in particular had `min_length=1`, which made
158
+ # an explicitly empty `slotInfos: []` - a station with nothing loaded - fail
159
+ # the entire /detail response.
160
+ current_load_slot: int = Field(
161
+ default=0, alias="currentLoadSlot", description="Currently loading slot ID (0 if none)"
162
+ )
163
+ current_slot: int = Field(
164
+ default=0, alias="currentSlot", description="Currently active/printing slot ID (0 if none)"
165
+ )
166
+ slot_cnt: int = Field(
167
+ default=0, alias="slotCnt", description="Total number of slots in the station"
168
+ )
169
+ slot_infos: list[SlotInfo] = Field(
170
+ default_factory=list,
171
+ alias="slotInfos",
172
+ description="Array of information for each slot",
173
+ )
174
+ state_action: int = Field(
175
+ default=0, alias="stateAction", description="Current action state of the material station"
176
+ )
177
+ state_step: int = Field(
178
+ default=0, alias="stateStep", description="Current step within the state action"
179
+ )
180
+
181
+
182
+ class IndepMatlInfo(BaseModel):
183
+ """Information related to independent material loading, often used when a single extruder printer has a material station."""
184
+
185
+ # `extra="allow"`: inbound, see SlotInfo.
186
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
187
+
188
+ material_color: str = Field(
189
+ default="", alias="materialColor", description="Color of the material"
190
+ )
191
+ material_name: str = Field(
192
+ default="",
193
+ alias="materialName",
194
+ description="Name of the material (can be '?' if unknown)",
195
+ )
196
+ state_action: int = Field(default=0, alias="stateAction", description="Current action state")
197
+ state_step: int = Field(
198
+ default=0, alias="stateStep", description="Current step within the state action"
199
+ )
200
+
201
+ @field_validator("material_color", mode="before")
202
+ @classmethod
203
+ def normalize_material_color(cls, v: Any) -> Any:
204
+ """Normalize the material color, falling back to '' rather than raising."""
205
+ return _normalize_hex_color(v)
206
+
207
+
208
+ class FFGcodeToolData(BaseModel):
209
+ """Represents data for a single tool/material used in a G-code file, typically part of a multi-material print."""
210
+
211
+ # `extra="allow"`: inbound, nested under FFGcodeFileEntry - which already
212
+ # allows extras, but a child that forbids them reintroduces the same
213
+ # names-only fallback it was flipped to avoid.
214
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
215
+
216
+ filament_weight: float = Field(
217
+ default=0.0,
218
+ alias="filamentWeight",
219
+ description="Calculated filament weight for this tool/material in the print",
220
+ )
221
+ material_color: str = Field(
222
+ default="", alias="materialColor", description="Material color hex string (e.g., '#FFFF00')"
223
+ )
224
+ material_name: str = Field(
225
+ default="", alias="materialName", description="Name of the material (e.g., 'PLA')"
226
+ )
227
+ slot_id: int = Field(
228
+ default=0,
229
+ alias="slotId",
230
+ description="Slot ID from the material station, if applicable (0 if not or direct)",
231
+ )
232
+ tool_id: int = Field(default=0, alias="toolId", description="Tool ID or extruder number (0-3)")
233
+
234
+ @field_validator("material_color", mode="before")
235
+ @classmethod
236
+ def normalize_material_color(cls, v: Any) -> Any:
237
+ """Normalize the material color, falling back to '' rather than raising."""
238
+ return _normalize_hex_color(v)
239
+
240
+
241
+ class FFGcodeFileEntry(BaseModel):
242
+ """Represents a single G-code file entry as returned by the /gcodeList endpoint, especially for printers like AD5X that provide detailed material info."""
243
+
244
+ # `extra="allow"`, matching FFPrinterDetail: a firmware update that adds one
245
+ # field must not fail validation, because Files.get_recent_file_list falls
246
+ # back to a names-only list when it does - silently dropping print time,
247
+ # filament weight, and the per-tool material data for EVERY file.
248
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
249
+
250
+ # `gcode_file_name` stays required - it is the one field without which the
251
+ # entry means nothing, so failing here is honest. Everything else is
252
+ # metadata and gets a default.
253
+ gcode_file_name: str = Field(
254
+ alias="gcodeFileName", description="The name of the G-code file (e.g., 'FISH_PLA.3mf')"
255
+ )
256
+ gcode_tool_cnt: int | None = Field(
257
+ default=None,
258
+ alias="gcodeToolCnt",
259
+ description="Number of tools/materials used in this G-code file",
260
+ )
261
+ gcode_tool_datas: list[FFGcodeToolData] | None = Field(
262
+ default=None,
263
+ alias="gcodeToolDatas",
264
+ description="Array of detailed information for each tool/material",
265
+ )
266
+ printing_time: int = Field(
267
+ default=0, alias="printingTime", description="Estimated printing time in seconds"
268
+ )
269
+ total_filament_weight: float | None = Field(
270
+ default=None,
271
+ alias="totalFilamentWeight",
272
+ description="Total estimated filament weight for the print",
273
+ )
274
+ use_matl_station: bool | None = Field(
275
+ default=None,
276
+ alias="useMatlStation",
277
+ description="Indicates if the G-code file is intended for use with a material station",
278
+ )
279
+
280
+
281
+ class FFPrinterDetail(BaseModel):
282
+ """
283
+ Represents the raw detailed information about a FlashForge 3D printer as obtained from its API.
284
+ Properties are often in the printer's native naming format and may include string representations
285
+ of boolean states (e.g., "open", "close").
286
+ """
287
+
288
+ model_config = ConfigDict(extra="allow")
289
+
290
+ auto_shutdown: str | None = Field(default=None, alias="autoShutdown")
291
+ auto_shutdown_time: int | None = Field(default=None, alias="autoShutdownTime")
292
+ camera: int | None = Field(default=None, alias="camera")
293
+ camera_stream_url: str | None = Field(default=None, alias="cameraStreamUrl")
294
+ chamber_fan_speed: int | None = Field(default=None, alias="chamberFanSpeed")
295
+ chamber_target_temp: float | None = Field(default=None, alias="chamberTargetTemp")
296
+ chamber_temp: float | None = Field(default=None, alias="chamberTemp")
297
+ clear_fan_status: str | None = Field(default=None, alias="clearFanStatus")
298
+ cooling_fan_speed: int | None = Field(default=None, alias="coolingFanSpeed")
299
+ cooling_fan_left_speed: int | None = Field(default=None, alias="coolingFanLeftSpeed")
300
+ coordinate: list[float] | None = Field(default=None, alias="coordinate")
301
+ cumulative_filament: float | None = Field(default=None, alias="cumulativeFilament")
302
+ cumulative_print_time: int | None = Field(default=None, alias="cumulativePrintTime")
303
+ current_print_speed: int | None = Field(default=None, alias="currentPrintSpeed")
304
+ door_status: str | None = Field(default=None, alias="doorStatus")
305
+ error_code: str | None = Field(default=None, alias="errorCode")
306
+ estimated_left_len: float | None = Field(default=None, alias="estimatedLeftLen")
307
+ estimated_left_weight: float | None = Field(default=None, alias="estimatedLeftWeight")
308
+ estimated_right_len: float | None = Field(default=None, alias="estimatedRightLen")
309
+ estimated_right_weight: float | None = Field(default=None, alias="estimatedRightWeight")
310
+ estimated_time: float | None = Field(default=None, alias="estimatedTime")
311
+ extrude_ctrl: int | None = Field(default=None, alias="extrudeCtrl")
312
+ external_fan_status: str | None = Field(default=None, alias="externalFanStatus")
313
+ fill_amount: float | None = Field(default=None, alias="fillAmount")
314
+ firmware_version: str | None = Field(default=None, alias="firmwareVersion")
315
+ flash_register_code: str | None = Field(default=None, alias="flashRegisterCode")
316
+ # AD5X-only, and firmware omits what does not apply: the Creator 5 series
317
+ # leaves this out of /detail even with four loaded slots, so None means "not
318
+ # reported", NOT "no station". Never gate a feature on it - read the derived
319
+ # FFMachineInfo.has_matl_station, or check matl_station_info yourself.
320
+ has_matl_station: bool | None = Field(default=None, alias="hasMatlStation")
321
+ matl_station_info: MatlStationInfo | None = Field(default=None, alias="matlStationInfo")
322
+ indep_matl_info: IndepMatlInfo | None = Field(default=None, alias="indepMatlInfo")
323
+ has_left_filament: bool | None = Field(default=None, alias="hasLeftFilament")
324
+ has_right_filament: bool | None = Field(default=None, alias="hasRightFilament")
325
+ internal_fan_status: str | None = Field(default=None, alias="internalFanStatus")
326
+ ip_addr: str | None = Field(default=None, alias="ipAddr")
327
+ left_filament_type: str | None = Field(default=None, alias="leftFilamentType")
328
+ left_target_temp: float | None = Field(default=None, alias="leftTargetTemp")
329
+ left_temp: float | None = Field(default=None, alias="leftTemp")
330
+ light_status: str | None = Field(default=None, alias="lightStatus")
331
+ location: str | None = Field(default=None, alias="location")
332
+ mac_addr: str | None = Field(default=None, alias="macAddr")
333
+ measure: str | None = Field(default=None, alias="measure")
334
+ move_ctrl: int | None = Field(default=None, alias="moveCtrl")
335
+ name: str | None = Field(default=None, alias="name")
336
+ nozzle_cnt: int | None = Field(default=None, alias="nozzleCnt")
337
+ nozzle_model: str | None = Field(default=None, alias="nozzleModel")
338
+ nozzle_style: int | None = Field(default=None, alias="nozzleStyle")
339
+ # --- Creator 5 series raw fields ---
340
+ # Immutable factory model name (e.g. "Creator 5 Pro"); unlike `name` this is
341
+ # not user-editable. May be absent on older firmware.
342
+ model: str | None = Field(default=None, alias="model")
343
+ # Per-tool current nozzle temperatures (one entry per nozzle). Multi-nozzle
344
+ # Creator 5 series report these; single-nozzle models use rightTemp/leftTemp.
345
+ # Entries are nullable because a sentinel reading is normalized to None by
346
+ # `drop_nozzle_temperature_sentinels` below.
347
+ nozzle_temps: list[float | None] | None = Field(default=None, alias="nozzleTemps")
348
+ # Per-tool target nozzle temperatures (one entry per nozzle).
349
+ nozzle_target_temps: list[float | None] | None = Field(default=None, alias="nozzleTargetTemps")
350
+ # Lidar / first-layer scanner presence flag (1 = present, 0 = absent).
351
+ lidar: int | None = Field(default=None, alias="lidar")
352
+ pid: int | None = Field(default=None, alias="pid")
353
+ plat_target_temp: float | None = Field(default=None, alias="platTargetTemp")
354
+ plat_temp: float | None = Field(default=None, alias="platTemp")
355
+ polar_register_code: str | None = Field(default=None, alias="polarRegisterCode")
356
+ print_duration: int | None = Field(default=None, alias="printDuration")
357
+ print_file_name: str | None = Field(default=None, alias="printFileName")
358
+ print_file_thumb_url: str | None = Field(default=None, alias="printFileThumbUrl")
359
+ print_layer: int | None = Field(default=None, alias="printLayer")
360
+ print_progress: float | None = Field(default=None, alias="printProgress")
361
+ print_speed_adjust: int | None = Field(default=None, alias="printSpeedAdjust")
362
+ remaining_disk_space: float | None = Field(default=None, alias="remainingDiskSpace")
363
+ right_filament_type: str | None = Field(default=None, alias="rightFilamentType")
364
+ right_target_temp: float | None = Field(default=None, alias="rightTargetTemp")
365
+ right_temp: float | None = Field(default=None, alias="rightTemp")
366
+ status: str | None = Field(default=None, alias="status")
367
+ target_print_layer: int | None = Field(default=None, alias="targetPrintLayer")
368
+ tvoc: float | None = Field(default=None, alias="tvoc")
369
+ z_axis_compensation: float | None = Field(default=None, alias="zAxisCompensation")
370
+
371
+ # Firmware reports absent temperature hardware with a negative sentinel
372
+ # (-108 on a chamber-less Creator 5, ff-5mp-hass#18) rather than by omitting the
373
+ # field. Map those to None here so "no sensor" reads as "not reported"
374
+ # everywhere downstream, instead of as a -108 C reading or a hard failure.
375
+ @field_validator(
376
+ "chamber_temp",
377
+ "chamber_target_temp",
378
+ "left_temp",
379
+ "left_target_temp",
380
+ "plat_temp",
381
+ "plat_target_temp",
382
+ "right_temp",
383
+ "right_target_temp",
384
+ mode="before",
385
+ )
386
+ @classmethod
387
+ def drop_temperature_sentinels(cls, v: Any) -> Any:
388
+ """Replace out-of-band 'no sensor' temperature markers with None."""
389
+ return sanitize_temperature(v)
390
+
391
+ @field_validator("nozzle_temps", "nozzle_target_temps", mode="before")
392
+ @classmethod
393
+ def drop_nozzle_temperature_sentinels(cls, v: Any) -> Any:
394
+ """Apply the same sentinel handling to the per-tool temperature arrays."""
395
+ if not isinstance(v, list):
396
+ return v
397
+ return [sanitize_temperature(entry) for entry in v]
398
+
399
+
400
+ class FFMachineInfo(BaseModel):
401
+ """
402
+ Represents a structured and user-friendly model of the printer's information and state.
403
+ This interface is populated by transforming data from FFPrinterDetail.
404
+ """
405
+
406
+ # `extra="forbid"` deliberately: see Temperature. Built only at
407
+ # `MachineInfoParser.from_detail`, from ~50 keyword arguments, never from
408
+ # raw printer JSON - so forbidding extras is a typo check on our own code,
409
+ # not a firmware-compatibility risk.
410
+ model_config = ConfigDict(extra="forbid")
411
+
412
+ # Auto-shutdown settings
413
+ auto_shutdown: bool = False
414
+ auto_shutdown_time: int = 0
415
+
416
+ # Camera
417
+ camera_stream_url: str = ""
418
+
419
+ # Fan speeds
420
+ chamber_fan_speed: int = 0
421
+ cooling_fan_speed: int = 0
422
+ cooling_fan_left_speed: int | None = None
423
+
424
+ # Cumulative stats
425
+ cumulative_filament: float = 0.0
426
+ cumulative_print_time: int = 0
427
+
428
+ # Current print speed
429
+ current_print_speed: int = 0
430
+
431
+ # Disk space
432
+ free_disk_space: str = "0.00"
433
+
434
+ # Door and error status
435
+ door_open: bool = False
436
+ error_code: str = ""
437
+
438
+ # Current print estimates
439
+ est_length: float = 0.0
440
+ est_weight: float = 0.0
441
+ estimated_time: float = 0.0
442
+
443
+ # Fans & LED status
444
+ external_fan_on: bool = False
445
+ internal_fan_on: bool = False
446
+ lights_on: bool = False
447
+
448
+ # Network
449
+ ip_address: str = ""
450
+ mac_address: str = ""
451
+
452
+ # Print settings
453
+ fill_amount: float = 0.0
454
+ firmware_version: str = ""
455
+ name: str = ""
456
+ pid: int | None = None
457
+ # Resolved model (PID first, then the factory model name). Gate features on the
458
+ # connected backend's `capabilities`, never on `name`.
459
+ model_id: PrinterModelId = PrinterModelId.UNKNOWN
460
+ # Immutable factory model name (e.g. "Creator 5 Pro"). Falls back to a
461
+ # PID-derived name, then the user-set `name`, when the printer doesn't
462
+ # report the `model` field.
463
+ model: str | None = None
464
+ nozzle_size: str = ""
465
+ # Number of tools/nozzles the printer reports. Creator 5 series = 4
466
+ # (tool-changer); single-nozzle models = 1. Mirrors len(tool_temps).
467
+ nozzle_count: int | None = None
468
+
469
+ # Temperatures
470
+ print_bed: Temperature = Field(default_factory=Temperature)
471
+ extruder: Temperature = Field(default_factory=Temperature)
472
+ # Heated chamber. Only the Creator 5 series has one; other models report 0/0.
473
+ chamber: Temperature | None = None
474
+ # Current/target temperatures for every tool/nozzle. Single-nozzle models
475
+ # report a 1-element array mirroring `extruder`; Creator 5 series report
476
+ # one entry per nozzle.
477
+ tool_temps: list[Temperature] = Field(default_factory=list)
478
+
479
+ # Capability flags (presence-derived, never assumed from model family)
480
+ has_camera: bool = False
481
+ has_lidar: bool = False
482
+ # Only true on models with confirmed hardware (Creator 5 Pro). When false,
483
+ # `door_open` is cosmetic and should not be surfaced.
484
+ has_door_sensor: bool = False
485
+ # True only when the printer actually reported a chamber temperature. The
486
+ # heated chamber is a Creator 5 series *option*, not a family trait: units
487
+ # without it report the -108 sentinel, which FFPrinterDetail normalizes to
488
+ # None. Gate chamber entities on this, never on `is_creator5`.
489
+ has_chamber_sensor: bool = False
490
+
491
+ # Current print stats
492
+ print_duration: int = 0
493
+ print_file_name: str = ""
494
+ print_file_thumb_url: str = ""
495
+ current_print_layer: int = 0
496
+ print_progress: float = 0.0
497
+ print_progress_int: int = 0
498
+ print_speed_adjust: int = 0
499
+ filament_type: str = ""
500
+
501
+ # Machine state
502
+ machine_state: MachineState = MachineState.UNKNOWN
503
+ status: str = ""
504
+ total_print_layers: int = 0
505
+ tvoc: float = 0.0
506
+ z_axis_compensation: float = 0.0
507
+
508
+ # Cloud codes
509
+ flash_cloud_register_code: str = ""
510
+ polar_cloud_register_code: str = ""
511
+
512
+ # Extras
513
+ print_eta: str = "00:00"
514
+ # None whenever the print is not advancing (paused, heating, ready, error,
515
+ # ...). The firmware freezes `estimatedTime` outside the PRINTING state, so
516
+ # an absolute timestamp derived from it would recede in real time rather
517
+ # than hold. Use `print_eta` / `estimated_time` for the remaining duration,
518
+ # which stays valid in every state.
519
+ completion_time: datetime | None = None
520
+ formatted_run_time: str = "00:00"
521
+ formatted_total_run_time: str = "0h:0m"
522
+
523
+ # Material Station (AD5X / Creator 5 series)
524
+ #
525
+ # A capability, not a passthrough: MachineInfoParser DERIVES this from the
526
+ # station data rather than copying the raw `hasMatlStation` field, which the
527
+ # Creator 5 series never reports even with a station attached. It is a plain
528
+ # bool on purpose - there is no "unknown" state to represent, and offering
529
+ # one is what let an unreported flag read as absent hardware. For the
530
+ # untouched firmware value, read FFPrinterDetail.has_matl_station.
531
+ has_matl_station: bool = False
532
+ matl_station_info: MatlStationInfo | None = None
533
+ indep_matl_info: IndepMatlInfo | None = None
534
+
535
+ @model_validator(mode="after")
536
+ def validate_print_progress(self) -> FFMachineInfo:
537
+ """Ensure print progress integer matches float value."""
538
+ if self.print_progress is not None:
539
+ self.print_progress_int = max(0, min(100, int(self.print_progress * 100)))
540
+ return self