printer.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. from datetime import datetime
  2. from pydantic import BaseModel, Field, field_validator
  3. class PrinterBase(BaseModel):
  4. name: str = Field(..., min_length=1, max_length=100)
  5. serial_number: str = Field(..., min_length=1, max_length=50)
  6. @field_validator("serial_number")
  7. @classmethod
  8. def _normalize_serial_number(cls, v: str) -> str:
  9. """Uppercase and trim the serial number.
  10. Bambu serial numbers are uppercase alphanumeric, and the MQTT report
  11. topic ``device/<serial>/report`` is case-sensitive. A serial entered
  12. in the wrong case (or with stray whitespace) connects and subscribes
  13. without error but never receives a message — the printer publishes to
  14. the correctly-cased topic, so every status field stays unknown (#1465).
  15. Normalising on input makes the subscribed topic always match.
  16. """
  17. normalized = v.strip().upper()
  18. if not normalized:
  19. raise ValueError("serial_number must not be blank")
  20. return normalized
  21. ip_address: str = Field(
  22. ...,
  23. max_length=253,
  24. 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])?)*)$",
  25. )
  26. access_code: str = Field(..., min_length=1, max_length=20)
  27. model: str | None = None
  28. location: str | None = None # Group/location name
  29. auto_archive: bool = True
  30. external_camera_url: str | None = None
  31. external_camera_type: str | None = None # "mjpeg", "rtsp", "snapshot", "usb"
  32. external_camera_enabled: bool = False
  33. external_camera_snapshot_url: str | None = None # Optional single-frame override; #1177
  34. camera_rotation: int = 0 # 0, 90, 180, 270 degrees
  35. class PrinterCreate(PrinterBase):
  36. pass
  37. class PlateDetectionROI(BaseModel):
  38. """Region of interest for plate detection (percentages 0.0-1.0)."""
  39. x: float = Field(..., ge=0.0, le=1.0) # X start %
  40. y: float = Field(..., ge=0.0, le=1.0) # Y start %
  41. w: float = Field(..., ge=0.0, le=1.0) # Width %
  42. h: float = Field(..., ge=0.0, le=1.0) # Height %
  43. class PrinterUpdate(BaseModel):
  44. name: str | None = None
  45. ip_address: str | None = Field(
  46. default=None,
  47. max_length=253,
  48. 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])?)*)$",
  49. )
  50. access_code: str | None = None
  51. model: str | None = None
  52. location: str | None = None
  53. is_active: bool | None = None
  54. auto_archive: bool | None = None
  55. print_hours_offset: float | None = None
  56. external_camera_url: str | None = None
  57. external_camera_type: str | None = None
  58. external_camera_enabled: bool | None = None
  59. external_camera_snapshot_url: str | None = None # #1177
  60. camera_rotation: int | None = None # 0, 90, 180, 270 degrees
  61. plate_detection_enabled: bool | None = None
  62. plate_detection_roi: PlateDetectionROI | None = None
  63. class PrinterResponse(PrinterBase):
  64. id: int
  65. is_active: bool
  66. nozzle_count: int = 1 # 1 or 2, auto-detected from MQTT
  67. print_hours_offset: float = 0.0
  68. external_camera_url: str | None = None
  69. external_camera_type: str | None = None
  70. external_camera_enabled: bool = False
  71. external_camera_snapshot_url: str | None = None # #1177
  72. camera_rotation: int = 0 # 0, 90, 180, 270 degrees
  73. plate_detection_enabled: bool = False
  74. plate_detection_roi: PlateDetectionROI | None = None
  75. created_at: datetime
  76. updated_at: datetime
  77. class Config:
  78. from_attributes = True
  79. @classmethod
  80. def from_orm_with_roi(cls, printer) -> "PrinterResponse":
  81. """Create response from ORM model, converting ROI fields to nested object."""
  82. data = {
  83. "id": printer.id,
  84. "name": printer.name,
  85. "serial_number": printer.serial_number,
  86. "ip_address": printer.ip_address,
  87. "access_code": printer.access_code,
  88. "model": printer.model,
  89. "location": printer.location,
  90. "auto_archive": printer.auto_archive,
  91. "external_camera_url": printer.external_camera_url,
  92. "external_camera_type": printer.external_camera_type,
  93. "external_camera_enabled": printer.external_camera_enabled,
  94. "external_camera_snapshot_url": printer.external_camera_snapshot_url,
  95. "camera_rotation": printer.camera_rotation,
  96. "is_active": printer.is_active,
  97. "nozzle_count": printer.nozzle_count,
  98. "print_hours_offset": printer.print_hours_offset,
  99. "plate_detection_enabled": printer.plate_detection_enabled,
  100. "created_at": printer.created_at,
  101. "updated_at": printer.updated_at,
  102. }
  103. # Build ROI object if any ROI field is set
  104. if any(
  105. [
  106. printer.plate_detection_roi_x is not None,
  107. printer.plate_detection_roi_y is not None,
  108. printer.plate_detection_roi_w is not None,
  109. printer.plate_detection_roi_h is not None,
  110. ]
  111. ):
  112. data["plate_detection_roi"] = PlateDetectionROI(
  113. x=printer.plate_detection_roi_x or 0.15,
  114. y=printer.plate_detection_roi_y or 0.35,
  115. w=printer.plate_detection_roi_w or 0.70,
  116. h=printer.plate_detection_roi_h or 0.55,
  117. )
  118. return cls(**data)
  119. class HMSErrorResponse(BaseModel):
  120. code: str
  121. attr: int = 0 # Attribute value for constructing wiki URL
  122. module: int
  123. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  124. class AMSTray(BaseModel):
  125. id: int
  126. tray_color: str | None = None
  127. tray_type: str | None = None
  128. tray_sub_brands: str | None = None # Full name like "PLA Basic", "PETG HF"
  129. tray_id_name: str | None = None # Bambu filament ID like "A00-Y2" (can decode to color)
  130. tray_info_idx: str | None = None # Filament preset ID like "GFA00"
  131. remain: int = 0
  132. k: float | None = None # Pressure advance value (from tray or K-profile lookup)
  133. cali_idx: int | None = None # Calibration index for K-profile lookup
  134. tag_uid: str | None = None # RFID tag UID (any tag)
  135. tray_uuid: str | None = None # Bambu Lab spool UUID (32-char hex)
  136. nozzle_temp_min: int | None = None # Min nozzle temperature
  137. nozzle_temp_max: int | None = None # Max nozzle temperature
  138. drying_temp: int | None = None # RFID-recommended drying temp
  139. drying_time: int | None = None # RFID-recommended drying time (hours)
  140. state: int | None = None # AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  141. class AMSUnit(BaseModel):
  142. id: int
  143. humidity: int | None = None
  144. temp: float | None = None
  145. is_ams_ht: bool = False # True for AMS-HT (single spool), False for regular AMS (4 spools)
  146. tray: list[AMSTray] = []
  147. serial_number: str = "" # AMS unit serial number (sn from MQTT)
  148. sw_ver: str = "" # AMS firmware version (from get_version info.module)
  149. dry_time: int = 0 # Minutes remaining (0 = not drying, >0 = drying active)
  150. dry_status: int = 0 # 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  151. dry_sub_status: int = 0 # 0=Off, 1=Heating, 2=Dehumidify
  152. dry_sf_reason: list[int] = [] # Cannot-dry reasons from firmware (see CannotDryReason)
  153. module_type: str = "" # "ams", "n3f", "n3s"
  154. class NozzleInfoResponse(BaseModel):
  155. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  156. nozzle_diameter: str = "" # e.g., "0.4"
  157. class NozzleRackSlot(BaseModel):
  158. """H2C nozzle rack slot (6-position tool-changer dock)."""
  159. id: int = 0
  160. nozzle_type: str = ""
  161. nozzle_diameter: str = ""
  162. wear: int | None = None
  163. stat: int | None = None # Nozzle status (e.g. mounted/docked)
  164. max_temp: int = 0 # Max temperature rating °C (0 = not set)
  165. serial_number: str = "" # Nozzle serial number
  166. filament_color: str = "" # RGBA hex ("00000000" = no filament)
  167. filament_id: str = "" # Bambu filament ID
  168. filament_type: str = "" # Material type (e.g. "PLA", "PETG")
  169. class AmsLabelBody(BaseModel):
  170. label: str = Field(..., min_length=1, max_length=100)
  171. ams_serial: str = Field(default="", max_length=50)
  172. class FilaSwitchResponse(BaseModel):
  173. """Filament Track Switch (FTS) state — accessory that mediates AMS-to-extruder routing.
  174. When installed, the AMS info field reports bits 8-11 = 0xE (uninitialized)
  175. because slots are dynamically routed via the FTS rather than tied to a
  176. specific extruder. Frontend uses `installed` to suppress the per-extruder
  177. slot filter in the print modal. See #1162.
  178. """
  179. installed: bool = False
  180. # in[track] = currently loaded slot for that track (-1 = empty)
  181. in_slots: list[int] = []
  182. # out[track] = extruder this track terminates at (0 = right, 1 = left)
  183. out_extruders: list[int] = []
  184. stat: int = 0
  185. info: int = 0
  186. class PrintOptionsResponse(BaseModel):
  187. """AI detection and print options from xcam data."""
  188. # Core AI detectors
  189. spaghetti_detector: bool = False
  190. print_halt: bool = False
  191. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  192. first_layer_inspector: bool = False
  193. printing_monitor: bool = False
  194. buildplate_marker_detector: bool = False
  195. allow_skip_parts: bool = False
  196. # Additional AI detectors (decoded from cfg bitmask)
  197. nozzle_clumping_detector: bool = True
  198. nozzle_clumping_sensitivity: str = "medium"
  199. pileup_detector: bool = True
  200. pileup_sensitivity: str = "medium"
  201. airprint_detector: bool = True
  202. airprint_sensitivity: str = "medium"
  203. auto_recovery_step_loss: bool = True
  204. filament_tangle_detect: bool = False
  205. class PrinterStatus(BaseModel):
  206. id: int
  207. name: str
  208. connected: bool
  209. state: str | None = None
  210. current_print: str | None = None
  211. subtask_name: str | None = None
  212. gcode_file: str | None = None
  213. progress: float | None = None
  214. remaining_time: int | None = None
  215. layer_num: int | None = None
  216. total_layers: int | None = None
  217. temperatures: dict | None = None
  218. cover_url: str | None = None
  219. hms_errors: list[HMSErrorResponse] = []
  220. ams: list[AMSUnit] = []
  221. ams_exists: bool = False
  222. vt_tray: list[AMSTray] = [] # Virtual tray / external spool(s)
  223. sdcard: bool = False # SD card inserted
  224. store_to_sdcard: bool = False # Store sent files on SD card
  225. timelapse: bool = False # Timelapse recording active
  226. ipcam: bool = False # Live view enabled
  227. wifi_signal: int | None = None # WiFi signal strength in dBm
  228. wired_network: bool = False # Ethernet connection detected
  229. door_open: bool = False # Enclosure door open (X1/P1S/P2S/H2*)
  230. nozzles: list[NozzleInfoResponse] = [] # Nozzle hardware info (index 0=left/primary, 1=right)
  231. nozzle_rack: list[NozzleRackSlot] = [] # H2C 6-nozzle tool-changer rack
  232. print_options: PrintOptionsResponse | None = None # AI detection and print options
  233. # Calibration stage tracking
  234. stg_cur: int = -1 # Current stage number (-1 = not calibrating)
  235. stg_cur_name: str | None = None # Human-readable current stage name
  236. stg: list[int] = [] # List of stage numbers in calibration sequence
  237. # Air conditioning mode (0=cooling, 1=heating)
  238. airduct_mode: int = 0
  239. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  240. speed_level: int = 2
  241. # Chamber light on/off
  242. chamber_light: bool = False
  243. # Active extruder for dual nozzle (0=right, 1=left)
  244. active_extruder: int = 0
  245. # AMS mapping for dual nozzle: which AMS is connected to which nozzle
  246. ams_mapping: list[int] = []
  247. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  248. ams_extruder_map: dict[str, int] = {}
  249. # Filament Track Switch (FTS) accessory — when installed, AMS reports
  250. # bits 8-11 = 0xE (uninitialized) and routing is dynamic via the FTS. See #1162.
  251. fila_switch: FilaSwitchResponse | None = None
  252. # Currently loaded tray (global ID): 254 = external spool, 255 = no filament
  253. tray_now: int = 255
  254. # AMS status for filament change tracking
  255. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  256. ams_status_main: int = 0
  257. # Sub status: specific step within filament change (when main=1)
  258. # Known values: 4=retraction, 6=load verification, 7=purge
  259. ams_status_sub: int = 0
  260. # mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  261. mc_print_sub_stage: int = 0
  262. # Timestamp of last AMS data update (for RFID refresh detection)
  263. last_ams_update: float = 0.0
  264. # Number of printable objects in current print (for skip objects feature)
  265. printable_objects_count: int = 0
  266. # Fan speeds (0-100 percentage, None if not available for this model)
  267. cooling_fan_speed: int | None = None # Part cooling fan
  268. big_fan1_speed: int | None = None # Auxiliary fan
  269. big_fan2_speed: int | None = None # Chamber/exhaust fan
  270. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  271. # Firmware version (from info.module[name="ota"].sw_ver)
  272. firmware_version: str | None = None
  273. # Developer LAN mode: True = enabled, False = disabled (MQTT encryption), None = unknown
  274. developer_mode: bool | None = None
  275. # Queue: printer is awaiting the user to acknowledge the build plate is cleared
  276. # after a finished/failed print. Persisted across restarts (#961).
  277. awaiting_plate_clear: bool = False
  278. # AMS drying support
  279. supports_drying: bool = False
  280. # Linked archive for the active print (resolved via subtask_id). Frontend uses
  281. # this to fetch plate metadata and show the plate name when the source 3MF is
  282. # multi-plate (#881 follow-up).
  283. current_archive_id: int | None = None
  284. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  285. # Set for every active print regardless of plate count; the frontend decides
  286. # whether to render it based on current_archive_id's is_multi_plate flag.
  287. current_plate_id: int | None = None
  288. class DiagnosticCheck(BaseModel):
  289. """One connection-diagnostic check result.
  290. ``id`` is a stable key (port_mqtt, port_ftps, port_rtsps, network_mode,
  291. subnet, mqtt_auth, developer_mode); the frontend renders the localized
  292. title and fix text from id + status. ``params`` carries interpolation
  293. values (e.g. network mode, IP addresses) for that text.
  294. """
  295. id: str
  296. status: str # "pass" | "fail" | "warn" | "skip"
  297. params: dict = Field(default_factory=dict)
  298. class PrinterDiagnosticResult(BaseModel):
  299. """Result of a printer connection diagnostic run."""
  300. printer_id: int | None = None
  301. ip_address: str
  302. overall: str # "ok" | "warnings" | "problems"
  303. checks: list[DiagnosticCheck]
  304. class DiagnosticRequest(BaseModel):
  305. """Pre-save (Add Printer) connection diagnostic request.
  306. serial_number + access_code are optional: when both are present the
  307. diagnostic also probes MQTT credentials, otherwise only the
  308. network-level checks run.
  309. """
  310. ip_address: str
  311. serial_number: str | None = None
  312. access_code: str | None = None