printer.py 16 KB

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