printer.py 24 KB

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