printer.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. from datetime import datetime
  2. from pydantic import BaseModel, Field, field_validator, model_validator
  3. from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
  4. from backend.app.schemas.printer_location import normalize_location_name
  5. from backend.app.utils.printer_models import supports_nozzle_flow_type
  6. def _mask_url_login(url: str | None) -> str | None:
  7. """A stored camera URL with its login secret masked.
  8. One URL, not a log line: the login runs to the last ``@`` before the
  9. first ``/`` after the scheme, whitespace, ``?`` and ``#`` included (when
  10. in doubt it is masked). The user part up to the first ``:`` survives;
  11. without a ``:`` the login may be a token and goes whole.
  12. """
  13. if not url or "://" not in url:
  14. return url
  15. start = url.index("://") + 3
  16. slash = url.find("/", start)
  17. end = len(url) if slash == -1 else slash
  18. if "@" not in url[start:end]:
  19. return url
  20. login, host = url[start:end].rsplit("@", 1)
  21. shown = f"{login.split(':', 1)[0]}:[REDACTED]" if ":" in login else "[REDACTED]"
  22. return f"{url[:start]}{shown}@{host}{url[end:]}"
  23. class PrinterBase(BaseModel):
  24. name: str = Field(..., min_length=1, max_length=100)
  25. serial_number: str = Field(..., min_length=1, max_length=50)
  26. @field_validator("serial_number")
  27. @classmethod
  28. def _normalize_serial_number(cls, v: str) -> str:
  29. """Uppercase and trim the serial number.
  30. Bambu serial numbers are uppercase alphanumeric, and the MQTT report
  31. topic ``device/<serial>/report`` is case-sensitive. A serial entered
  32. in the wrong case (or with stray whitespace) connects and subscribes
  33. without error but never receives a message — the printer publishes to
  34. the correctly-cased topic, so every status field stays unknown (#1465).
  35. Normalising on input makes the subscribed topic always match.
  36. """
  37. normalized = v.strip().upper()
  38. if not normalized:
  39. raise ValueError("serial_number must not be blank")
  40. return normalized
  41. ip_address: str = Field(
  42. ...,
  43. max_length=253,
  44. pattern=r"^(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)$",
  45. )
  46. model: str | None = None
  47. location: str | None = None # Group/location name
  48. auto_archive: bool = True
  49. external_camera_url: str | None = None
  50. external_camera_type: str | None = None # "mjpeg", "rtsp", "snapshot", "usb"
  51. external_camera_enabled: bool = False
  52. external_camera_snapshot_url: str | None = None # Optional single-frame override; #1177
  53. camera_rotation: int = 0 # 0, 90, 180, 270 degrees
  54. camera_light_auto: bool = False # #1655, used when camera_light_mode is "selected"
  55. class PrinterCreate(PrinterBase):
  56. # access_code lives on the input shapes only — never on the default
  57. # PrinterResponse. Direct exposure on PRINTERS_READ would let a Viewer
  58. # connect to the printer's MQTT and bypass Bambuddy's RBAC.
  59. access_code: str = Field(..., min_length=1, max_length=20)
  60. # Input only, not on PrinterBase: SQLite never enforced the column width,
  61. # so a stored location may be longer, and the response must still read it.
  62. _location = field_validator("location")(normalize_location_name)
  63. class PlateDetectionROI(BaseModel):
  64. """Region of interest for plate detection (percentages 0.0-1.0)."""
  65. x: float = Field(..., ge=0.0, le=1.0) # X start %
  66. y: float = Field(..., ge=0.0, le=1.0) # Y start %
  67. w: float = Field(..., ge=0.0, le=1.0) # Width %
  68. h: float = Field(..., ge=0.0, le=1.0) # Height %
  69. class PrinterUpdate(IgnoresNullForRequiredColumns):
  70. __orm_table__ = "printers"
  71. name: str | None = None
  72. ip_address: str | None = Field(
  73. default=None,
  74. max_length=253,
  75. pattern=r"^(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)$",
  76. )
  77. access_code: str | None = None
  78. model: str | None = None
  79. location: str | None = None
  80. _location = field_validator("location")(normalize_location_name)
  81. is_active: bool | None = None
  82. auto_archive: bool | None = None
  83. print_hours_offset: float | None = None
  84. # Wear cost per printing hour (#694); null or 0 turns it off.
  85. wear_cost_per_hour: float | None = Field(default=None, ge=0, le=100000)
  86. external_camera_url: str | None = None
  87. external_camera_type: str | None = None
  88. external_camera_enabled: bool | None = None
  89. external_camera_snapshot_url: str | None = None # #1177
  90. camera_rotation: int | None = None # 0, 90, 180, 270 degrees
  91. camera_light_auto: bool | None = None # #1655
  92. plate_detection_enabled: bool | None = None
  93. plate_detection_roi: PlateDetectionROI | None = None
  94. class PrinterResponse(PrinterBase):
  95. id: int
  96. is_active: bool
  97. nozzle_count: int = 1 # 1 or 2, auto-detected from MQTT
  98. # Whether the model is sold with both Standard and High Flow nozzles, so a
  99. # K-profile's flow type is a real choice rather than a meaningless field.
  100. # Derived from the model, not from nozzle_count — see
  101. # printer_models.supports_nozzle_flow_type.
  102. supports_nozzle_flow_type: bool = True
  103. print_hours_offset: float = 0.0
  104. wear_cost_per_hour: float | None = None # #694
  105. external_camera_url: str | None = None
  106. external_camera_type: str | None = None
  107. external_camera_enabled: bool = False
  108. external_camera_snapshot_url: str | None = None # #1177
  109. camera_rotation: int = 0 # 0, 90, 180, 270 degrees
  110. camera_light_auto: bool = False # #1655
  111. plate_detection_enabled: bool = False
  112. plate_detection_roi: PlateDetectionROI | None = None
  113. created_at: datetime
  114. updated_at: datetime
  115. class Config:
  116. from_attributes = True
  117. @classmethod
  118. def from_orm_with_roi(cls, printer) -> "PrinterResponse":
  119. """Create response from ORM model, converting ROI fields to nested object."""
  120. data = {
  121. "id": printer.id,
  122. "name": printer.name,
  123. "serial_number": printer.serial_number,
  124. "ip_address": printer.ip_address,
  125. "model": printer.model,
  126. "location": printer.location,
  127. "auto_archive": printer.auto_archive,
  128. "external_camera_url": printer.external_camera_url,
  129. "external_camera_type": printer.external_camera_type,
  130. "external_camera_enabled": printer.external_camera_enabled,
  131. "external_camera_snapshot_url": printer.external_camera_snapshot_url,
  132. "camera_rotation": printer.camera_rotation,
  133. "camera_light_auto": bool(printer.camera_light_auto),
  134. "is_active": printer.is_active,
  135. "nozzle_count": printer.nozzle_count,
  136. "supports_nozzle_flow_type": supports_nozzle_flow_type(printer.model),
  137. "print_hours_offset": printer.print_hours_offset,
  138. "wear_cost_per_hour": printer.wear_cost_per_hour,
  139. "plate_detection_enabled": printer.plate_detection_enabled,
  140. "created_at": printer.created_at,
  141. "updated_at": printer.updated_at,
  142. }
  143. # Build ROI object if any ROI field is set
  144. if any(
  145. [
  146. printer.plate_detection_roi_x is not None,
  147. printer.plate_detection_roi_y is not None,
  148. printer.plate_detection_roi_w is not None,
  149. printer.plate_detection_roi_h is not None,
  150. ]
  151. ):
  152. data["plate_detection_roi"] = PlateDetectionROI(
  153. x=printer.plate_detection_roi_x or 0.15,
  154. y=printer.plate_detection_roi_y or 0.35,
  155. w=printer.plate_detection_roi_w or 0.70,
  156. h=printer.plate_detection_roi_h or 0.55,
  157. )
  158. return cls(**data)
  159. @field_validator("external_camera_url", "external_camera_snapshot_url", mode="after")
  160. @classmethod
  161. def _camera_credentials(cls, value: str | None) -> str | None:
  162. """Readers see the camera URLs without the password in them."""
  163. return _mask_url_login(value)
  164. class PrinterResponseWithSecret(PrinterResponse):
  165. """PrinterResponse + access_code and the full camera URLs. Returned ONLY to callers with
  166. PRINTERS_UPDATE (Admin / Operator JWTs, or single-trust auth-disabled mode).
  167. Viewers and API keys never receive this shape — they get the bare
  168. PrinterResponse without access_code, since holding the access_code lets
  169. the caller talk to the printer's MQTT directly and bypass Bambuddy's RBAC.
  170. """
  171. access_code: str
  172. @field_validator("external_camera_url", "external_camera_snapshot_url", mode="after")
  173. @classmethod
  174. def _camera_credentials(cls, value: str | None) -> str | None:
  175. """Editors keep the full camera URLs, to edit them."""
  176. return value
  177. class HMSErrorResponse(BaseModel):
  178. code: str
  179. attr: int = 0 # Attribute value for constructing wiki URL
  180. module: int
  181. severity: int # Bambu alert level: 1 error (stopped), 2 warning (paused), 3 notification, 0 invalid
  182. actions: list[str] = [] # List of user-facing action keys (e.g. "CHECK_FILAMENT")
  183. job_id: str | None = None # Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  184. # Canonical hex identifier the firmware uses to match HMS-related commands.
  185. # 16 chars for `hms[]`-array faults (full 64-bit attr+code), 8 chars for
  186. # `print_error` faults. The frontend echoes this back as
  187. # HmsActionBody.print_error so we send the firmware-recognised key, not the
  188. # truncated short_code that historically caused silent command rejection
  189. # (#1830, H2D wrong-plate verification).
  190. full_code: str = ""
  191. # The bundled catalogue's sentence for this fault, so a client does not have
  192. # to carry its own copy of the same table to tell a user why a print halted
  193. # (#2926). English only and not localized — the catalogue ships one language.
  194. # Generated from Bambu Studio's HMS files, keyed by `full_code` and the
  195. # printer model (#2728). None when Bambu publishes no text for the code,
  196. # which it does for some codes it lists. A client should treat null as "no
  197. # text available", never as "no fault" — `full_code` is what identifies the
  198. # fault, and it is always present.
  199. description: str | None = None
  200. def hms_error_responses(errors) -> list[HMSErrorResponse]:
  201. """A printer's live HMS faults (``PrinterState.hms_errors``) as API rows.
  202. Shared by the printer status route and the webhook status route, so a
  203. fault reads the same to the UI and to an API-key client (#2919).
  204. """
  205. return [
  206. HMSErrorResponse(
  207. code=e.code,
  208. attr=e.attr,
  209. module=e.module,
  210. severity=e.severity,
  211. actions=e.actions,
  212. job_id=e.job_id,
  213. full_code=e.full_code,
  214. description=e.description,
  215. )
  216. for e in (errors or [])
  217. ]
  218. class AMSTray(BaseModel):
  219. id: int
  220. tray_color: str | None = None
  221. tray_type: str | None = None
  222. tray_sub_brands: str | None = None # Full name like "PLA Basic", "PETG HF"
  223. tray_id_name: str | None = None # Bambu filament ID like "A00-Y2" (can decode to color)
  224. tray_info_idx: str | None = None # Filament preset ID like "GFA00"
  225. remain: int = 0
  226. k: float | None = None # Pressure advance value (from tray or K-profile lookup)
  227. cali_idx: int | None = None # Calibration index for K-profile lookup
  228. tag_uid: str | None = None # RFID tag UID (any tag)
  229. tray_uuid: str | None = None # Bambu Lab spool UUID (32-char hex)
  230. nozzle_temp_min: int | None = None # Min nozzle temperature
  231. nozzle_temp_max: int | None = None # Max nozzle temperature
  232. drying_temp: int | None = None # RFID-recommended drying temp
  233. drying_time: int | None = None # RFID-recommended drying time (hours)
  234. state: int | None = None # AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  235. # Firmware's authoritative "spool physically present" bit (from tray_exist_bits).
  236. # True for a non-RFID spool the firmware can't identify — the UI shows "?" rather
  237. # than "Empty" (#2527). None when the bitmask was unavailable (→ state-based fallback).
  238. exists: bool | None = None
  239. class AMSUnit(BaseModel):
  240. id: int
  241. humidity: int | None = None
  242. temp: float | None = None
  243. is_ams_ht: bool = False # True for AMS-HT (single spool), False for regular AMS (4 spools)
  244. tray: list[AMSTray] = []
  245. serial_number: str = "" # AMS unit serial number (sn from MQTT)
  246. sw_ver: str = "" # AMS firmware version (from get_version info.module)
  247. dry_time: int = 0 # Minutes remaining (0 = not drying, >0 = drying active)
  248. # True when dry_time > 0 but the countdown has not ticked for over
  249. # DRY_COUNTDOWN_STALL_SECONDS with no active dry_status phase: the timer is
  250. # set but no cycle is running (never started, or paused partway).
  251. dry_countdown_stalled: bool = False
  252. dry_status: int = 0 # 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  253. dry_sub_status: int = 0 # 0=Off, 1=Heating, 2=Dehumidify
  254. dry_sf_reason: list[int] = [] # Cannot-dry reasons from firmware (see CannotDryReason)
  255. dry_target_temp: int | None = None # Active-cycle target °C (Bambu doesn't echo this)
  256. dry_filament: str | None = None # Active-cycle filament name we sent
  257. module_type: str = "" # "ams", "n3f", "n3s"
  258. class NozzleInfoResponse(BaseModel):
  259. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  260. nozzle_diameter: str = "" # e.g., "0.4"
  261. class NozzleRackSlot(BaseModel):
  262. """H2C nozzle rack slot (6-position tool-changer dock)."""
  263. id: int = 0
  264. nozzle_type: str = ""
  265. nozzle_diameter: str = ""
  266. wear: int | None = None
  267. stat: int | None = None # Nozzle status (e.g. mounted/docked)
  268. max_temp: int = 0 # Max temperature rating °C (0 = not set)
  269. serial_number: str = "" # Nozzle serial number
  270. filament_color: str = "" # RGBA hex ("00000000" = no filament)
  271. filament_id: str = "" # Bambu filament ID
  272. filament_type: str = "" # Material type (e.g. "PLA", "PETG")
  273. class AmsLabelBody(BaseModel):
  274. label: str = Field(..., min_length=1, max_length=100)
  275. ams_serial: str = Field(default="", max_length=50)
  276. class HmsActionBody(BaseModel):
  277. # Canonical hex identifier (HMSErrorResponse.full_code): 8 chars for
  278. # `print_error`-sourced faults, 16 chars for `hms[]`-array faults whose
  279. # full 64-bit code is the firmware's matching key. Length-bounded to
  280. # those two valid shapes to keep stray input from reaching the dispatcher.
  281. print_error: str = Field(..., min_length=8, max_length=16, pattern=r"^[0-9A-Fa-f]{8}([0-9A-Fa-f]{8})?$")
  282. # One of the HMSAction enum values. Length-capped to keep stray input from
  283. # reaching the dispatcher's `match` statement.
  284. action: str = Field(..., min_length=1, max_length=64)
  285. # The `subtask_id` snapshot from the HMSError that surfaced this dialog.
  286. # Bambu echoes it back in HMS-aware commands. Optional for idle errors.
  287. job_id: str | None = Field(default=None, max_length=64)
  288. class FilaSwitchResponse(BaseModel):
  289. """Filament Track Switch (FTS) state — accessory that mediates AMS-to-extruder routing.
  290. When installed, the AMS info field reports bits 8-11 = 0xE (uninitialized)
  291. because slots are dynamically routed via the FTS rather than tied to a
  292. specific extruder. Frontend uses `installed` to suppress the per-extruder
  293. slot filter in the print modal. See #1162.
  294. """
  295. installed: bool = False
  296. # in[track] = currently loaded slot for that track (-1 = empty)
  297. in_slots: list[int] = []
  298. # out[track] = extruder this track terminates at (0 = right, 1 = left)
  299. out_extruders: list[int] = []
  300. stat: int = 0
  301. info: int = 0
  302. # Whether the switch is set up: every AMS bound to one of its two inlets.
  303. # A load cannot be routed until it is, so the UI blocks on this rather than
  304. # sending a command the firmware will drop.
  305. ready: bool = False
  306. class ExtruderSlotResponse(BaseModel):
  307. """Which AMS slot one hotend is currently fed from.
  308. From ``device.extruder.info[i].snow``. Needed because ``tray_now`` is a
  309. single printer-wide value: on a dual-nozzle machine with both hotends
  310. loaded it names only one of them, so it cannot say which hotend holds a
  311. given slot.
  312. """
  313. # None when the hotend is not fed from any slot.
  314. ams_id: int | None = None
  315. slot_id: int | None = None
  316. has_filament: bool = False
  317. class PrintOptionsResponse(BaseModel):
  318. """AI detection and print options from xcam data."""
  319. # Core AI detectors
  320. spaghetti_detector: bool = False
  321. print_halt: bool = False
  322. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  323. first_layer_inspector: bool = False
  324. printing_monitor: bool = False
  325. buildplate_marker_detector: bool = False
  326. allow_skip_parts: bool = False
  327. # Additional AI detectors (decoded from cfg bitmask)
  328. nozzle_clumping_detector: bool = True
  329. nozzle_clumping_sensitivity: str = "medium"
  330. pileup_detector: bool = True
  331. pileup_sensitivity: str = "medium"
  332. airprint_detector: bool = True
  333. airprint_sensitivity: str = "medium"
  334. auto_recovery_step_loss: bool = True
  335. filament_tangle_detect: bool = False
  336. class PrinterStatus(BaseModel):
  337. id: int
  338. name: str
  339. connected: bool
  340. state: str | None = None
  341. current_print: str | None = None
  342. subtask_name: str | None = None
  343. gcode_file: str | None = None
  344. progress: float | None = None
  345. remaining_time: int | None = None
  346. layer_num: int | None = None
  347. total_layers: int | None = None
  348. temperatures: dict | None = None
  349. cover_url: str | None = None
  350. hms_errors: list[HMSErrorResponse] = []
  351. ams: list[AMSUnit] = []
  352. ams_exists: bool = False
  353. vt_tray: list[AMSTray] = [] # Virtual tray / external spool(s)
  354. sdcard: bool = False # SD card inserted
  355. store_to_sdcard: bool = False # Store sent files on SD card
  356. timelapse: bool = False # Timelapse recording active
  357. ipcam: bool = False # Live view enabled
  358. wifi_signal: int | None = None # WiFi signal strength in dBm
  359. wired_network: bool = False # Ethernet connection detected
  360. door_open: bool = False # Enclosure door open (X1/P1S/P2S/H2*)
  361. nozzles: list[NozzleInfoResponse] = [] # Nozzle hardware info (index 0=left/primary, 1=right)
  362. nozzle_rack: list[NozzleRackSlot] = [] # H2C 6-nozzle tool-changer rack
  363. print_options: PrintOptionsResponse | None = None # AI detection and print options
  364. # Calibration stage tracking
  365. stg_cur: int = -1 # Current stage number (-1 = not calibrating)
  366. stg_cur_name: str | None = None # Human-readable current stage name
  367. stg: list[int] = [] # List of stage numbers in calibration sequence
  368. # Air conditioning mode (0=cooling, 1=heating)
  369. airduct_mode: int = 0
  370. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  371. speed_level: int = 2
  372. # Chamber light on/off
  373. chamber_light: bool = False
  374. # Active extruder for dual nozzle (0=right, 1=left)
  375. active_extruder: int = 0
  376. # AMS mapping for dual nozzle: which AMS is connected to which nozzle
  377. ams_mapping: list[int] = []
  378. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  379. ams_extruder_map: dict[str, int] = {}
  380. # Filament Track Switch (FTS) accessory — when installed, AMS reports
  381. # bits 8-11 = 0xE (uninitialized) and routing is dynamic via the FTS. See #1162.
  382. fila_switch: FilaSwitchResponse | None = None
  383. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}, from AMS info bits 24-27.
  384. # Which of the switch's two inlets each AMS is plumbed into, as set on the
  385. # printer's "Manual AMS Setup" screen. Empty unless an FTS is installed —
  386. # an FTS-bound AMS reaches BOTH nozzles, so it has no entry in
  387. # ams_extruder_map and must not be labelled left or right.
  388. ams_switch_inlet: dict[str, str] = {}
  389. # Which AMS slot each hotend is fed from, keyed by extruder id as a string
  390. # ("0" = right/main, "1" = left/deputy). Empty on printers that do not
  391. # report ``device.extruder.info``.
  392. extruder_slots: dict[str, ExtruderSlotResponse] = {}
  393. # Currently loaded tray (global ID): 254 = external spool, 255 = no filament
  394. tray_now: int = 255
  395. # The trays this print has drawn from, in order: [[global tray ID, layer the
  396. # switch happened at], ...]. A tray outside the job's AMS mapping is a backup
  397. # spool the printer switched to (AMS Filament Backup); the queue card shows it
  398. # in place of the slot that ran out. Reset at the start of each print.
  399. tray_change_log: list[list[int]] = []
  400. # Runout / filament-replacement guidance (#2587). Populated only while the
  401. # print is PAUSED. Both are globalised tray IDs (ams_id*4+slot, or 128-135 for
  402. # AMS-HT, or 254 for external) so the frontend can highlight them with the same
  403. # logic it uses for tray_now:
  404. # expected_tray = the slot the firmware now expects filament in (from tray_tar).
  405. # None when idle, not paused, or the slot can't be resolved
  406. # (multi-AMS ambiguity) — the UI then says "check the printer".
  407. # previous_tray = the slot loaded before the pause, i.e. the one that ran out
  408. # (from tray_pre). None when unknown.
  409. expected_tray: int | None = None
  410. previous_tray: int | None = None
  411. # AMS status for filament change tracking
  412. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  413. ams_status_main: int = 0
  414. # Sub status: specific step within filament change (when main=1)
  415. # Known values: 4=retraction, 6=load verification, 7=purge
  416. ams_status_sub: int = 0
  417. # mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  418. mc_print_sub_stage: int = 0
  419. # Timestamp of last AMS data update (for RFID refresh detection)
  420. last_ams_update: float = 0.0
  421. # Number of printable objects in current print (for skip objects feature)
  422. printable_objects_count: int = 0
  423. # Fan speeds (0-100 percentage, None if not available for this model)
  424. cooling_fan_speed: int | None = None # Part cooling fan
  425. big_fan1_speed: int | None = None # Auxiliary fan
  426. big_fan2_speed: int | None = None # Chamber/exhaust fan
  427. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  428. # Left auxiliary part cooling fan (optional P2S/X2D accessory, airduct part id 10).
  429. # None = not installed / not reported by this model.
  430. left_aux_fan_speed: int | None = None
  431. # Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit; airduct part id 3).
  432. exhaust_fan_present: bool = False
  433. # Firmware version (from info.module[name="ota"].sw_ver)
  434. firmware_version: str | None = None
  435. # Developer LAN mode: True = enabled, False = disabled (MQTT encryption), None = unknown
  436. developer_mode: bool | None = None
  437. # AMS Filament Backup ("auto-switch" to a second spool when one runs out).
  438. # True = ON, False = OFF, None = unknown / unsupported (A1 family — protocol field
  439. # not yet identified). UI treats None as "status unavailable", not as a hard disable.
  440. ams_filament_backup: bool | None = None
  441. # Queue: printer is awaiting the user to acknowledge the build plate is cleared
  442. # after a finished/failed print. Persisted across restarts (#961).
  443. awaiting_plate_clear: bool = False
  444. # AMS drying support
  445. supports_drying: bool = False
  446. # AMS "Print While Drying" — drying mid-print. Verified per Bambu wiki release notes;
  447. # see _DRY_WHILE_PRINTING_MIN_FIRMWARE in printer_manager.py for the matrix.
  448. supports_drying_while_printing: bool = False
  449. # The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  450. # supports_drying is False on these; the UI keeps the control visible but disabled
  451. # and says why, rather than dropping it without explanation.
  452. drying_screen_only: bool = False
  453. # Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  454. supports_chamber_heater: bool = False
  455. # Linked archive for the active print (resolved via subtask_id). Frontend uses
  456. # this to fetch plate metadata and show the plate name when the source 3MF is
  457. # multi-plate (#881 follow-up).
  458. current_archive_id: int | None = None
  459. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  460. # Set for every active print regardless of plate count; the frontend decides
  461. # whether to render it based on current_archive_id's is_multi_plate flag.
  462. current_plate_id: int | None = None
  463. class DiagnosticCheck(BaseModel):
  464. """One connection-diagnostic check result.
  465. ``id`` is a stable key (port_mqtt, port_ftps, port_rtsps,
  466. macos_local_network, network_mode, subnet, external_storage, mqtt_auth,
  467. developer_mode, printer_publishing); the frontend renders the localized
  468. title and fix text from id + status. ``params`` carries interpolation
  469. values (e.g. network mode, IP addresses) for that text.
  470. Not every check is emitted on every run: ``macos_local_network`` appears
  471. only on macOS, where it is the only platform it can say anything about.
  472. """
  473. id: str
  474. status: str # "pass" | "fail" | "warn" | "skip"
  475. params: dict = Field(default_factory=dict)
  476. class PrinterDiagnosticResult(BaseModel):
  477. """Result of a printer connection diagnostic run."""
  478. printer_id: int | None = None
  479. ip_address: str
  480. overall: str # "ok" | "warnings" | "problems"
  481. checks: list[DiagnosticCheck]
  482. class DiagnosticRequest(BaseModel):
  483. """Pre-save (Add Printer) connection diagnostic request.
  484. serial_number + access_code are optional: when both are present the
  485. diagnostic also probes MQTT credentials, otherwise only the
  486. network-level checks run.
  487. """
  488. ip_address: str
  489. serial_number: str | None = None
  490. access_code: str | None = None
  491. class PrinterFilesDownloadRequest(BaseModel):
  492. """Printer paths selected for a bulk download."""
  493. paths: list[str] = Field(..., max_length=1000)
  494. sizes: dict[str, int] = Field(default_factory=dict, max_length=1000)
  495. @model_validator(mode="after")
  496. def _validate_sizes(self):
  497. """Validate optional FTP-reported sizes used for early rejection."""
  498. if self.sizes and set(self.sizes) != set(self.paths):
  499. raise ValueError("A size is required for every selected printer path")
  500. if any(size < 0 for size in self.sizes.values()):
  501. raise ValueError("Printer file sizes must not be negative")
  502. return self
  503. class PrinterFilesJobRequest(PrinterFilesDownloadRequest):
  504. """Browser preparation request, including native download presentation."""
  505. filename: str = Field(default="printer-files.zip", min_length=1, max_length=255)
  506. as_zip: bool = True