printer.py 30 KB

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