printer_manager.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. import asyncio
  2. import logging
  3. import traceback
  4. from collections.abc import Callable
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.models.printer import Printer
  8. from backend.app.services.bambu_mqtt import BambuMQTTClient, MQTTLogEntry, PrinterState, get_stage_name
  9. logger = logging.getLogger(__name__)
  10. # Models that have a real chamber temperature sensor
  11. # Based on Home Assistant Bambu Lab integration
  12. # P1P/P1S and A1/A1Mini do NOT have chamber temp sensors
  13. # Includes both display names and internal codes from MQTT/SSDP
  14. CHAMBER_TEMP_SUPPORTED_MODELS = frozenset(
  15. [
  16. # Display names
  17. "X1",
  18. "X1C",
  19. "X1E", # X1 series
  20. "P2S", # P2 series
  21. "H2C",
  22. "H2D",
  23. "H2DPRO",
  24. "H2S", # H2 series
  25. # Internal codes (from MQTT/SSDP)
  26. "BL-P001", # X1/X1C
  27. "C13", # X1E
  28. "O1D", # H2D
  29. "O1C", # H2C
  30. "O1C2", # H2C (dual nozzle variant)
  31. "O1S", # H2S
  32. "O1E", # H2D Pro
  33. "O2D", # H2D Pro (alternate code)
  34. "N7", # P2S
  35. ]
  36. )
  37. # Models that may incorrectly report stg_cur=0 when idle (firmware bug)
  38. # Based on Home Assistant Bambu Lab integration observations
  39. # See: https://github.com/greghesp/ha-bambulab/blob/main/custom_components/bambu_lab/pybambu/models.py
  40. A1_MODELS = frozenset(
  41. [
  42. # Display names
  43. "A1",
  44. "A1 MINI",
  45. "A1-MINI",
  46. "A1MINI",
  47. # Internal codes (from MQTT/SSDP)
  48. "N1", # A1 Mini
  49. "N2S", # A1
  50. ]
  51. )
  52. def supports_chamber_temp(model: str | None) -> bool:
  53. """Check if a printer model has a real chamber temperature sensor.
  54. P1P, P1S, A1, and A1Mini do NOT have chamber temp sensors.
  55. The 'chamber_temper' value they report is meaningless.
  56. """
  57. if not model:
  58. return False
  59. # Normalize model name (uppercase, strip whitespace)
  60. model_upper = model.strip().upper()
  61. return model_upper in CHAMBER_TEMP_SUPPORTED_MODELS
  62. def has_stg_cur_idle_bug(model: str | None) -> bool:
  63. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  64. Some A1/A1 Mini firmware versions report stg_cur=0 (which maps to "Printing")
  65. even when the printer is idle. This is a known firmware bug that was observed
  66. in the Home Assistant Bambu Lab integration.
  67. """
  68. if not model:
  69. return False
  70. model_upper = model.strip().upper()
  71. return model_upper in A1_MODELS
  72. class PrinterInfo:
  73. """Basic printer info for callbacks."""
  74. def __init__(self, name: str, serial_number: str):
  75. self.name = name
  76. self.serial_number = serial_number
  77. class PrinterManager:
  78. """Manager for multiple printer connections."""
  79. def __init__(self):
  80. self._clients: dict[int, BambuMQTTClient] = {}
  81. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  82. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  83. self._on_print_start: Callable[[int, dict], None] | None = None
  84. self._on_print_complete: Callable[[int, dict], None] | None = None
  85. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  86. self._on_ams_change: Callable[[int, list], None] | None = None
  87. self._on_layer_change: Callable[[int, int], None] | None = None
  88. self._loop: asyncio.AbstractEventLoop | None = None
  89. # Track who started the current print (Issue #206)
  90. self._current_print_user: dict[int, dict] = {} # {printer_id: {"user_id": int, "username": str}}
  91. # Track plate-cleared acknowledgments for queue flow
  92. self._plate_cleared: set[int] = set() # printer_ids where user confirmed plate is cleared
  93. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  94. """Get printer info by ID."""
  95. return self._printer_info.get(printer_id)
  96. def set_current_print_user(self, printer_id: int, user_id: int, username: str):
  97. """Track who started the current print (Issue #206)."""
  98. self._current_print_user[printer_id] = {"user_id": user_id, "username": username}
  99. def get_current_print_user(self, printer_id: int) -> dict | None:
  100. """Get the user who started the current print (Issue #206)."""
  101. return self._current_print_user.get(printer_id)
  102. def clear_current_print_user(self, printer_id: int):
  103. """Clear the current print user when print completes (Issue #206)."""
  104. self._current_print_user.pop(printer_id, None)
  105. def set_plate_cleared(self, printer_id: int):
  106. """Mark that user has cleared the build plate for this printer."""
  107. self._plate_cleared.add(printer_id)
  108. def is_plate_cleared(self, printer_id: int) -> bool:
  109. """Check if user has confirmed the plate is cleared."""
  110. return printer_id in self._plate_cleared
  111. def consume_plate_cleared(self, printer_id: int):
  112. """Clear the plate-cleared flag (called when scheduler starts next print)."""
  113. self._plate_cleared.discard(printer_id)
  114. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  115. """Set the event loop for async callbacks."""
  116. self._loop = loop
  117. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  118. """Set callback for print start events."""
  119. self._on_print_start = callback
  120. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  121. """Set callback for print completion events."""
  122. self._on_print_complete = callback
  123. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  124. """Set callback for status change events."""
  125. self._on_status_change = callback
  126. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  127. """Set callback for AMS data change events."""
  128. self._on_ams_change = callback
  129. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  130. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  131. self._on_layer_change = callback
  132. def _schedule_async(self, coro):
  133. """Schedule an async coroutine from a sync context.
  134. Captures exceptions from the coroutine and logs them to prevent
  135. silent failures in callbacks.
  136. """
  137. if self._loop and self._loop.is_running():
  138. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  139. def handle_exception(f):
  140. try:
  141. # This will re-raise any exception from the coroutine
  142. f.result()
  143. except Exception as e:
  144. import logging
  145. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  146. future.add_done_callback(handle_exception)
  147. async def connect_printer(self, printer: Printer) -> bool:
  148. """Connect to a printer."""
  149. if printer.id in self._clients:
  150. self.disconnect_printer(printer.id)
  151. printer_id = printer.id
  152. def on_state_change(state: PrinterState):
  153. if self._on_status_change:
  154. self._schedule_async(self._on_status_change(printer_id, state))
  155. def on_print_start(data: dict):
  156. if self._on_print_start:
  157. self._schedule_async(self._on_print_start(printer_id, data))
  158. def on_print_complete(data: dict):
  159. if self._on_print_complete:
  160. self._schedule_async(self._on_print_complete(printer_id, data))
  161. def on_ams_change(ams_data: list):
  162. if self._on_ams_change:
  163. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  164. def on_layer_change(layer_num: int):
  165. if self._on_layer_change:
  166. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  167. client = BambuMQTTClient(
  168. ip_address=printer.ip_address,
  169. serial_number=printer.serial_number,
  170. access_code=printer.access_code,
  171. model=printer.model,
  172. on_state_change=on_state_change,
  173. on_print_start=on_print_start,
  174. on_print_complete=on_print_complete,
  175. on_ams_change=on_ams_change,
  176. on_layer_change=on_layer_change,
  177. )
  178. client.connect()
  179. self._clients[printer_id] = client
  180. self._models[printer_id] = printer.model # Cache model for feature detection
  181. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  182. # Wait a moment for connection
  183. await asyncio.sleep(1)
  184. return client.state.connected
  185. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  186. """Disconnect from a printer."""
  187. if printer_id in self._clients:
  188. self._clients[printer_id].disconnect(timeout=timeout)
  189. del self._clients[printer_id]
  190. self._models.pop(printer_id, None) # Clean up model cache
  191. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  192. def disconnect_all(self, timeout: float = 0):
  193. """Disconnect from all printers."""
  194. for printer_id in list(self._clients.keys()):
  195. self.disconnect_printer(printer_id, timeout=timeout)
  196. def get_status(self, printer_id: int) -> PrinterState | None:
  197. """Get the current status of a printer (checks for stale connections)."""
  198. if printer_id in self._clients:
  199. client = self._clients[printer_id]
  200. # Check staleness and update connected state if needed
  201. client.check_staleness()
  202. return client.state
  203. return None
  204. def get_model(self, printer_id: int) -> str | None:
  205. """Get the cached model for a printer."""
  206. return self._models.get(printer_id)
  207. def get_all_statuses(self) -> dict[int, PrinterState]:
  208. """Get status of all connected printers (checks for stale connections)."""
  209. result = {}
  210. for printer_id, client in self._clients.items():
  211. # Check staleness and update connected state if needed
  212. client.check_staleness()
  213. result[printer_id] = client.state
  214. return result
  215. def is_connected(self, printer_id: int) -> bool:
  216. """Check if a printer is connected (checks for stale connections)."""
  217. if printer_id in self._clients:
  218. client = self._clients[printer_id]
  219. # Check staleness and update connected state if needed
  220. return client.check_staleness()
  221. return False
  222. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  223. """Get the MQTT client for a printer."""
  224. return self._clients.get(printer_id)
  225. def mark_printer_offline(self, printer_id: int):
  226. """Mark a printer as offline and trigger status callback.
  227. This is used when we know the printer power was cut (e.g., smart plug turned off)
  228. to immediately update the UI without waiting for MQTT timeout.
  229. """
  230. import logging
  231. logger = logging.getLogger(__name__)
  232. if printer_id in self._clients:
  233. client = self._clients[printer_id]
  234. if client.state.connected:
  235. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  236. client.state.connected = False
  237. client.state.state = "unknown"
  238. # Trigger the status change callback to broadcast via WebSocket
  239. if self._on_status_change:
  240. self._schedule_async(self._on_status_change(printer_id, client.state))
  241. def start_print(
  242. self,
  243. printer_id: int,
  244. filename: str,
  245. plate_id: int = 1,
  246. ams_mapping: list[int] | None = None,
  247. bed_levelling: bool = True,
  248. flow_cali: bool = False,
  249. vibration_cali: bool = True,
  250. layer_inspect: bool = False,
  251. timelapse: bool = False,
  252. use_ams: bool = True,
  253. ) -> bool:
  254. """Start a print on a connected printer."""
  255. caller = traceback.extract_stack(limit=3)[0]
  256. logger.info(
  257. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  258. printer_id,
  259. filename,
  260. caller.filename.split("/")[-1],
  261. caller.lineno,
  262. caller.name,
  263. )
  264. if printer_id in self._clients:
  265. return self._clients[printer_id].start_print(
  266. filename,
  267. plate_id,
  268. ams_mapping=ams_mapping,
  269. timelapse=timelapse,
  270. bed_levelling=bed_levelling,
  271. flow_cali=flow_cali,
  272. vibration_cali=vibration_cali,
  273. layer_inspect=layer_inspect,
  274. use_ams=use_ams,
  275. )
  276. return False
  277. def stop_print(self, printer_id: int) -> bool:
  278. """Stop the current print on a connected printer."""
  279. if printer_id in self._clients:
  280. return self._clients[printer_id].stop_print()
  281. return False
  282. async def wait_for_cooldown(
  283. self,
  284. printer_id: int,
  285. target_temp: float = 50.0,
  286. timeout: int = 600,
  287. check_interval: int = 10,
  288. ) -> bool:
  289. """Wait for the nozzle to cool down to a safe temperature.
  290. Args:
  291. printer_id: The printer to monitor
  292. target_temp: Target temperature to wait for (default 50°C)
  293. timeout: Maximum seconds to wait (default 600s = 10 min)
  294. check_interval: Seconds between temperature checks (default 10s)
  295. Returns:
  296. True if cooled down, False if timeout or not connected
  297. """
  298. import logging
  299. logger = logging.getLogger(__name__)
  300. elapsed = 0
  301. while elapsed < timeout:
  302. state = self.get_status(printer_id)
  303. if not state or not state.connected:
  304. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  305. return False
  306. # Check nozzle temperature (and nozzle_2 for dual extruders)
  307. nozzle_temp = state.temperatures.get("nozzle", 0)
  308. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  309. max_temp = max(nozzle_temp, nozzle_2_temp)
  310. if max_temp <= target_temp:
  311. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  312. return True
  313. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  314. await asyncio.sleep(check_interval)
  315. elapsed += check_interval
  316. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  317. return False
  318. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  319. """Enable or disable MQTT logging for a printer."""
  320. if printer_id in self._clients:
  321. self._clients[printer_id].enable_logging(enabled)
  322. return True
  323. return False
  324. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  325. """Get MQTT logs for a printer."""
  326. if printer_id in self._clients:
  327. return self._clients[printer_id].get_logs()
  328. return []
  329. def clear_logs(self, printer_id: int) -> bool:
  330. """Clear MQTT logs for a printer."""
  331. if printer_id in self._clients:
  332. self._clients[printer_id].clear_logs()
  333. return True
  334. return False
  335. def is_logging_enabled(self, printer_id: int) -> bool:
  336. """Check if logging is enabled for a printer."""
  337. if printer_id in self._clients:
  338. return self._clients[printer_id].logging_enabled
  339. return False
  340. def request_status_update(self, printer_id: int) -> bool:
  341. """Request a full status update from the printer.
  342. This sends a 'pushall' command to get the latest data including nozzle info.
  343. """
  344. if printer_id in self._clients:
  345. return self._clients[printer_id].request_status_update()
  346. return False
  347. async def test_connection(
  348. self,
  349. ip_address: str,
  350. serial_number: str,
  351. access_code: str,
  352. ) -> dict:
  353. """Test connection to a printer without persisting."""
  354. client = BambuMQTTClient(
  355. ip_address=ip_address,
  356. serial_number=serial_number,
  357. access_code=access_code,
  358. )
  359. try:
  360. client.connect()
  361. await asyncio.sleep(2)
  362. result = {
  363. "success": client.state.connected,
  364. "state": client.state.state if client.state.connected else None,
  365. "model": client.state.raw_data.get("device_model"),
  366. }
  367. finally:
  368. client.disconnect()
  369. return result
  370. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  371. """
  372. Compute a human-readable status name based on printer state.
  373. Uses stg_cur when available, otherwise derives status from temperature data
  374. when the printer is heating before a print starts.
  375. Args:
  376. state: The printer state to analyze
  377. model: Optional printer model for model-specific workarounds
  378. """
  379. # A1/A1 Mini firmware bug: some versions report stg_cur=0 when idle
  380. # Only correct this specific case (IDLE + stg_cur=0) for affected models
  381. if state.state == "IDLE" and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  382. return None
  383. # If we have a valid calibration stage, use it
  384. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  385. # Valid stage numbers are 0-254
  386. if 0 <= state.stg_cur < 255:
  387. return get_stage_name(state.stg_cur)
  388. # If not in RUNNING state, no derived status needed
  389. if state.state != "RUNNING":
  390. return None
  391. # Check if we're in an early phase where temperatures are heating
  392. temps = state.temperatures or {}
  393. progress = state.progress or 0
  394. # Only derive heating status when progress is very low (< 2%)
  395. # This indicates we're in the preparation phase, not actually printing
  396. if progress >= 2:
  397. return None
  398. # Check bed temperature - if target is set and current is significantly below
  399. bed_temp = temps.get("bed", 0)
  400. bed_target = temps.get("bed_target", 0)
  401. # Check nozzle temperature
  402. nozzle_temp = temps.get("nozzle", 0)
  403. nozzle_target = temps.get("nozzle_target", 0)
  404. # Temperature thresholds: consider "heating" if more than 10°C below target
  405. TEMP_THRESHOLD = 10
  406. # Determine what's heating (prioritize bed since it takes longer)
  407. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  408. return "Heating heatbed"
  409. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  410. return "Heating nozzle"
  411. # If targets are set but we're close to them, we might be in final prep
  412. if bed_target > 30 or nozzle_target > 30:
  413. if progress == 0 and state.layer_num == 0:
  414. return "Preparing"
  415. return None
  416. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None, model: str | None = None) -> dict:
  417. """Convert PrinterState to a JSON-serializable dict.
  418. Args:
  419. state: The printer state to convert
  420. printer_id: Optional printer ID for generating cover URLs
  421. model: Optional printer model for filtering unsupported features
  422. """
  423. # Parse AMS data from raw_data
  424. ams_units = []
  425. vt_tray = []
  426. raw_data = state.raw_data or {}
  427. # Build K-profile lookup map: cali_idx -> k_value
  428. kprofile_map: dict[int, float] = {}
  429. for kp in state.kprofiles or []:
  430. if kp.slot_id is not None and kp.k_value:
  431. try:
  432. kprofile_map[kp.slot_id] = float(kp.k_value)
  433. except (ValueError, TypeError):
  434. pass # Skip K-profile entries with unparseable values
  435. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  436. for ams_data in raw_data["ams"]:
  437. trays = []
  438. for tray in ams_data.get("tray", []):
  439. tag_uid = tray.get("tag_uid")
  440. if tag_uid in ("", "0000000000000000"):
  441. tag_uid = None
  442. tray_uuid = tray.get("tray_uuid")
  443. if tray_uuid in ("", "00000000000000000000000000000000"):
  444. tray_uuid = None
  445. # Get K value: first try tray's k field, then lookup from K-profiles
  446. k_value = tray.get("k")
  447. cali_idx = tray.get("cali_idx")
  448. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  449. k_value = kprofile_map[cali_idx]
  450. trays.append(
  451. {
  452. "id": int(tray.get("id", 0)),
  453. "tray_color": tray.get("tray_color"),
  454. "tray_type": tray.get("tray_type"),
  455. "tray_sub_brands": tray.get("tray_sub_brands"),
  456. "tray_id_name": tray.get("tray_id_name"),
  457. "tray_info_idx": tray.get("tray_info_idx"),
  458. "remain": tray.get("remain", 0),
  459. "k": k_value,
  460. "cali_idx": cali_idx,
  461. "tag_uid": tag_uid,
  462. "tray_uuid": tray_uuid,
  463. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  464. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  465. }
  466. )
  467. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  468. humidity_raw = ams_data.get("humidity_raw")
  469. humidity_idx = ams_data.get("humidity")
  470. humidity_value = None
  471. if humidity_raw is not None:
  472. try:
  473. humidity_value = int(humidity_raw)
  474. except (ValueError, TypeError):
  475. pass # Skip unparseable humidity; will try index fallback
  476. # Fall back to index if no raw value (index is 1-5, not percentage)
  477. if humidity_value is None and humidity_idx is not None:
  478. try:
  479. humidity_value = int(humidity_idx)
  480. except (ValueError, TypeError):
  481. pass # Skip unparseable humidity index; humidity remains None
  482. # AMS-HT has 1 tray, regular AMS has 4 trays
  483. is_ams_ht = len(trays) == 1
  484. ams_units.append(
  485. {
  486. "id": int(ams_data.get("id", 0)),
  487. "humidity": humidity_value,
  488. "temp": ams_data.get("temp"),
  489. "is_ams_ht": is_ams_ht,
  490. "tray": trays,
  491. }
  492. )
  493. # Parse virtual tray (external spool) — now a list
  494. if "vt_tray" in raw_data:
  495. for vt_data in raw_data["vt_tray"]:
  496. vt_tag_uid = vt_data.get("tag_uid")
  497. if vt_tag_uid in ("", "0000000000000000"):
  498. vt_tag_uid = None
  499. vt_tray_uuid = vt_data.get("tray_uuid")
  500. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  501. vt_tray_uuid = None
  502. # Get K value for vt_tray
  503. vt_k_value = vt_data.get("k")
  504. vt_cali_idx = vt_data.get("cali_idx")
  505. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  506. vt_k_value = kprofile_map[vt_cali_idx]
  507. tray_id = int(vt_data.get("id", 254))
  508. vt_tray.append(
  509. {
  510. "id": tray_id,
  511. "tray_color": vt_data.get("tray_color"),
  512. "tray_type": vt_data.get("tray_type"),
  513. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  514. "tray_id_name": vt_data.get("tray_id_name"),
  515. "tray_info_idx": vt_data.get("tray_info_idx"),
  516. "remain": vt_data.get("remain", 0),
  517. "k": vt_k_value,
  518. "cali_idx": vt_cali_idx,
  519. "tag_uid": vt_tag_uid,
  520. "tray_uuid": vt_tray_uuid,
  521. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  522. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  523. }
  524. )
  525. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  526. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  527. # Filter out chamber temp for models that don't have a real sensor
  528. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  529. temperatures = state.temperatures
  530. if not supports_chamber_temp(model):
  531. temperatures = {
  532. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  533. }
  534. result = {
  535. "connected": state.connected,
  536. "state": state.state,
  537. "current_print": state.current_print,
  538. "subtask_name": state.subtask_name,
  539. "gcode_file": state.gcode_file,
  540. "progress": state.progress,
  541. "remaining_time": state.remaining_time,
  542. "layer_num": state.layer_num,
  543. "total_layers": state.total_layers,
  544. "temperatures": temperatures,
  545. "hms_errors": [
  546. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  547. for e in (state.hms_errors or [])
  548. ],
  549. # AMS data for filament colors
  550. "ams": ams_units if ams_units else None,
  551. "vt_tray": vt_tray,
  552. # AMS status for filament change tracking
  553. "ams_status_main": state.ams_status_main,
  554. "ams_status_sub": state.ams_status_sub,
  555. "tray_now": state.tray_now,
  556. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  557. "ams_extruder_map": ams_extruder_map,
  558. # WiFi signal strength
  559. "wifi_signal": state.wifi_signal,
  560. # Calibration stage tracking
  561. "stg_cur": state.stg_cur,
  562. "stg_cur_name": get_derived_status_name(state, model),
  563. # Printable objects count for skip objects feature
  564. "printable_objects_count": len(state.printable_objects),
  565. # Fan speeds (0-100 percentage, None if not available)
  566. "cooling_fan_speed": state.cooling_fan_speed,
  567. "big_fan1_speed": state.big_fan1_speed,
  568. "big_fan2_speed": state.big_fan2_speed,
  569. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  570. # Chamber light state
  571. "chamber_light": state.chamber_light,
  572. # Active extruder for dual-nozzle printers (0=right, 1=left)
  573. "active_extruder": state.active_extruder,
  574. # H2C nozzle rack (tool-changer dock positions)
  575. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  576. "nozzle_rack": [
  577. {
  578. "id": n.get("id", 0),
  579. "nozzle_type": n.get("type", ""),
  580. "nozzle_diameter": n.get("diameter", ""),
  581. "wear": n.get("wear"),
  582. "stat": n.get("stat"),
  583. "max_temp": n.get("max_temp", 0),
  584. "serial_number": n.get("serial_number", ""),
  585. "filament_color": n.get("filament_color", ""),
  586. "filament_id": n.get("filament_id", ""),
  587. }
  588. for n in (state.nozzle_rack or [])
  589. ],
  590. }
  591. # Add cover URL if there's an active print and printer_id is provided
  592. # Include PAUSE state so skip objects modal can show cover
  593. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  594. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  595. else:
  596. result["cover_url"] = None
  597. return result
  598. # Global printer manager instance
  599. printer_manager = PrinterManager()
  600. async def init_printer_connections(db: AsyncSession):
  601. """Initialize connections to all active printers."""
  602. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  603. printers = result.scalars().all()
  604. for printer in printers:
  605. await printer_manager.connect_printer(printer)