printer_manager.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. # Models affected by the stg_cur=0 idle bug (firmware reports stg_cur=0 when idle,
  53. # which maps to "Printing" in STAGE_NAMES and overrides the correct IDLE state)
  54. STG_CUR_IDLE_BUG_MODELS = A1_MODELS | frozenset(
  55. [
  56. # Display names
  57. "P1P",
  58. "P1S",
  59. # Internal codes (from MQTT/SSDP)
  60. "C11", # P1P
  61. "C12", # P1S
  62. ]
  63. )
  64. def supports_chamber_temp(model: str | None) -> bool:
  65. """Check if a printer model has a real chamber temperature sensor.
  66. P1P, P1S, A1, and A1Mini do NOT have chamber temp sensors.
  67. The 'chamber_temper' value they report is meaningless.
  68. """
  69. if not model:
  70. return False
  71. # Normalize model name (uppercase, strip whitespace)
  72. model_upper = model.strip().upper()
  73. return model_upper in CHAMBER_TEMP_SUPPORTED_MODELS
  74. def has_stg_cur_idle_bug(model: str | None) -> bool:
  75. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  76. Some firmware versions report stg_cur=0 (which maps to "Printing")
  77. even when the printer is idle. Originally observed on A1/A1 Mini via the
  78. Home Assistant Bambu Lab integration, also confirmed on P1S.
  79. """
  80. if not model:
  81. return False
  82. model_upper = model.strip().upper()
  83. return model_upper in STG_CUR_IDLE_BUG_MODELS
  84. # Minimum firmware versions for AMS drying support (confirmed via capture testing)
  85. # Keys are exact model names (upper-cased). Do NOT use substring matching — it would
  86. # incorrectly gate X1E (matched by "X1") and H2D Pro (matched by "H2D").
  87. _DRYING_MIN_FIRMWARE: dict[str, str] = {
  88. "H2D": "01.02.30.00",
  89. "H2S": "01.02.00.00",
  90. "X1": "01.09.00.00",
  91. "X1C": "01.09.00.00",
  92. "P1P": "01.08.00.00",
  93. "P1S": "01.08.00.00",
  94. "P2S": "01.02.00.00",
  95. "N7": "01.02.00.00", # P2S internal model code
  96. }
  97. # Models that definitely don't support AMS drying (no AMS 2 Pro / AMS-HT compatibility)
  98. _DRYING_UNSUPPORTED_MODELS = frozenset({"A1", "A1MINI", "A1-MINI", "A1 MINI", "H2C", "O1C", "O1C2", "O1S", "N1", "N2S"})
  99. def supports_drying(model: str | None, firmware: str | None) -> bool:
  100. """Check if a printer model supports AMS drying commands.
  101. Known models with confirmed min firmware get version-gated.
  102. Known unsupported models are blocked.
  103. All other models (H2D Pro, X1E, future models) are allowed —
  104. the command fails gracefully with result: "fail" if unsupported.
  105. """
  106. if not model:
  107. return False
  108. model_upper = model.strip().upper()
  109. if model_upper in _DRYING_UNSUPPORTED_MODELS:
  110. return False
  111. if model_upper in _DRYING_MIN_FIRMWARE:
  112. return bool(firmware and firmware >= _DRYING_MIN_FIRMWARE[model_upper])
  113. # For all other models: allow
  114. return True
  115. class PrinterInfo:
  116. """Basic printer info for callbacks."""
  117. def __init__(self, name: str, serial_number: str):
  118. self.name = name
  119. self.serial_number = serial_number
  120. class PrinterManager:
  121. """Manager for multiple printer connections."""
  122. def __init__(self):
  123. self._clients: dict[int, BambuMQTTClient] = {}
  124. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  125. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  126. self._on_print_start: Callable[[int, dict], None] | None = None
  127. self._on_print_complete: Callable[[int, dict], None] | None = None
  128. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  129. self._on_ams_change: Callable[[int, list], None] | None = None
  130. self._on_layer_change: Callable[[int, int], None] | None = None
  131. self._on_bed_temp_update: Callable[[int, float], None] | None = None
  132. self._loop: asyncio.AbstractEventLoop | None = None
  133. # Track who started the current print (Issue #206)
  134. self._current_print_user: dict[int, dict] = {} # {printer_id: {"user_id": int, "username": str}}
  135. # Track printers awaiting plate-clear acknowledgment after a finished/failed print.
  136. # Persisted to DB (printers.awaiting_plate_clear) so the gate survives restarts/power
  137. # cycles — see issue #961. Loaded into this set at startup via load_awaiting_plate_clear_from_db().
  138. self._awaiting_plate_clear: set[int] = set()
  139. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  140. """Get printer info by ID."""
  141. return self._printer_info.get(printer_id)
  142. def set_current_print_user(self, printer_id: int, user_id: int, username: str):
  143. """Track who started the current print (Issue #206)."""
  144. self._current_print_user[printer_id] = {"user_id": user_id, "username": username}
  145. def get_current_print_user(self, printer_id: int) -> dict | None:
  146. """Get the user who started the current print (Issue #206)."""
  147. return self._current_print_user.get(printer_id)
  148. def clear_current_print_user(self, printer_id: int):
  149. """Clear the current print user when print completes (Issue #206)."""
  150. self._current_print_user.pop(printer_id, None)
  151. def is_awaiting_plate_clear(self, printer_id: int) -> bool:
  152. """Return True when the printer finished/failed a print and is waiting for the
  153. user to acknowledge the plate is cleared before the queue may dispatch the next job.
  154. """
  155. return printer_id in self._awaiting_plate_clear
  156. def set_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  157. """Set/clear the awaiting-plate-clear gate and persist it to DB.
  158. Persisted so the gate survives Bambuddy/printer restarts (#961): after Auto Off
  159. cycles the printer, the printer boots into IDLE with no memory of the previous
  160. finish, and without persistence the queue would bypass the confirmation prompt.
  161. """
  162. if awaiting:
  163. self._awaiting_plate_clear.add(printer_id)
  164. else:
  165. self._awaiting_plate_clear.discard(printer_id)
  166. # Only create the coroutine when there is a loop to run it on — otherwise Python
  167. # emits "coroutine was never awaited" warnings (e.g. in sync unit tests).
  168. if self._loop and self._loop.is_running():
  169. self._schedule_async(self._persist_awaiting_plate_clear(printer_id, awaiting))
  170. async def _persist_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  171. from backend.app.core.database import async_session
  172. try:
  173. async with async_session() as db:
  174. printer = await db.get(Printer, printer_id)
  175. if printer is not None:
  176. printer.awaiting_plate_clear = awaiting
  177. await db.commit()
  178. except Exception as e:
  179. logger.warning("Failed to persist awaiting_plate_clear for printer %d: %s", printer_id, e)
  180. async def load_awaiting_plate_clear_from_db(self):
  181. """Rehydrate the awaiting-plate-clear set from the printers table on startup."""
  182. from backend.app.core.database import async_session
  183. try:
  184. async with async_session() as db:
  185. result = await db.execute(select(Printer.id).where(Printer.awaiting_plate_clear.is_(True)))
  186. ids = {row[0] for row in result.all()}
  187. self._awaiting_plate_clear = ids
  188. if ids:
  189. logger.info("Loaded %d printer(s) awaiting plate-clear acknowledgment: %s", len(ids), sorted(ids))
  190. except Exception as e:
  191. logger.warning("Failed to load awaiting_plate_clear from DB: %s", e)
  192. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  193. """Set the event loop for async callbacks."""
  194. self._loop = loop
  195. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  196. """Set callback for print start events."""
  197. self._on_print_start = callback
  198. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  199. """Set callback for print completion events."""
  200. self._on_print_complete = callback
  201. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  202. """Set callback for status change events."""
  203. self._on_status_change = callback
  204. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  205. """Set callback for AMS data change events."""
  206. self._on_ams_change = callback
  207. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  208. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  209. self._on_layer_change = callback
  210. def set_bed_temp_update_callback(self, callback: Callable[[int, float], None]):
  211. """Set callback for bed temperature updates. Receives (printer_id, bed_temp)."""
  212. self._on_bed_temp_update = callback
  213. def _schedule_async(self, coro):
  214. """Schedule an async coroutine from a sync context.
  215. Captures exceptions from the coroutine and logs them to prevent
  216. silent failures in callbacks.
  217. """
  218. if self._loop and self._loop.is_running():
  219. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  220. def handle_exception(f):
  221. try:
  222. # This will re-raise any exception from the coroutine
  223. f.result()
  224. except Exception as e:
  225. import logging
  226. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  227. future.add_done_callback(handle_exception)
  228. async def connect_printer(self, printer: Printer) -> bool:
  229. """Connect to a printer."""
  230. if printer.id in self._clients:
  231. self.disconnect_printer(printer.id)
  232. printer_id = printer.id
  233. def on_state_change(state: PrinterState):
  234. if self._on_status_change:
  235. self._schedule_async(self._on_status_change(printer_id, state))
  236. def on_print_start(data: dict):
  237. if self._on_print_start:
  238. self._schedule_async(self._on_print_start(printer_id, data))
  239. def on_print_complete(data: dict):
  240. if self._on_print_complete:
  241. self._schedule_async(self._on_print_complete(printer_id, data))
  242. def on_ams_change(ams_data: list):
  243. if self._on_ams_change:
  244. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  245. def on_layer_change(layer_num: int):
  246. if self._on_layer_change:
  247. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  248. def on_bed_temp_update(bed_temp: float):
  249. if self._on_bed_temp_update:
  250. self._schedule_async(self._on_bed_temp_update(printer_id, bed_temp))
  251. client = BambuMQTTClient(
  252. ip_address=printer.ip_address,
  253. serial_number=printer.serial_number,
  254. access_code=printer.access_code,
  255. model=printer.model,
  256. on_state_change=on_state_change,
  257. on_print_start=on_print_start,
  258. on_print_complete=on_print_complete,
  259. on_ams_change=on_ams_change,
  260. on_layer_change=on_layer_change,
  261. on_bed_temp_update=on_bed_temp_update,
  262. )
  263. client.connect()
  264. self._clients[printer_id] = client
  265. self._models[printer_id] = printer.model # Cache model for feature detection
  266. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  267. # Wait a moment for connection
  268. await asyncio.sleep(1)
  269. return client.state.connected
  270. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  271. """Disconnect from a printer."""
  272. if printer_id in self._clients:
  273. self._clients[printer_id].disconnect(timeout=timeout)
  274. del self._clients[printer_id]
  275. self._models.pop(printer_id, None) # Clean up model cache
  276. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  277. def disconnect_all(self, timeout: float = 0):
  278. """Disconnect from all printers."""
  279. for printer_id in list(self._clients.keys()):
  280. self.disconnect_printer(printer_id, timeout=timeout)
  281. def get_status(self, printer_id: int) -> PrinterState | None:
  282. """Get the current status of a printer (checks for stale connections)."""
  283. if printer_id in self._clients:
  284. client = self._clients[printer_id]
  285. # Check staleness and update connected state if needed
  286. client.check_staleness()
  287. return client.state
  288. return None
  289. def get_model(self, printer_id: int) -> str | None:
  290. """Get the cached model for a printer."""
  291. return self._models.get(printer_id)
  292. def get_all_statuses(self) -> dict[int, PrinterState]:
  293. """Get status of all connected printers (checks for stale connections)."""
  294. result = {}
  295. for printer_id, client in self._clients.items():
  296. # Check staleness and update connected state if needed
  297. client.check_staleness()
  298. result[printer_id] = client.state
  299. return result
  300. def is_connected(self, printer_id: int) -> bool:
  301. """Check if a printer is connected (checks for stale connections)."""
  302. if printer_id in self._clients:
  303. client = self._clients[printer_id]
  304. # Check staleness and update connected state if needed
  305. return client.check_staleness()
  306. return False
  307. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  308. """Get the MQTT client for a printer."""
  309. return self._clients.get(printer_id)
  310. def mark_printer_offline(self, printer_id: int):
  311. """Mark a printer as offline and trigger status callback.
  312. This is used when we know the printer power was cut (e.g., smart plug turned off)
  313. to immediately update the UI without waiting for MQTT timeout.
  314. """
  315. import logging
  316. logger = logging.getLogger(__name__)
  317. if printer_id in self._clients:
  318. client = self._clients[printer_id]
  319. if client.state.connected:
  320. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  321. client.state.connected = False
  322. client.state.state = "unknown"
  323. # Trigger the status change callback to broadcast via WebSocket
  324. if self._on_status_change:
  325. self._schedule_async(self._on_status_change(printer_id, client.state))
  326. def start_print(
  327. self,
  328. printer_id: int,
  329. filename: str,
  330. plate_id: int = 1,
  331. ams_mapping: list[int] | None = None,
  332. bed_levelling: bool = True,
  333. flow_cali: bool = False,
  334. vibration_cali: bool = True,
  335. layer_inspect: bool = False,
  336. timelapse: bool = False,
  337. use_ams: bool = True,
  338. ) -> bool:
  339. """Start a print on a connected printer."""
  340. caller = traceback.extract_stack(limit=3)[0]
  341. logger.info(
  342. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  343. printer_id,
  344. filename,
  345. caller.filename.split("/")[-1],
  346. caller.lineno,
  347. caller.name,
  348. )
  349. if printer_id in self._clients:
  350. return self._clients[printer_id].start_print(
  351. filename,
  352. plate_id,
  353. ams_mapping=ams_mapping,
  354. timelapse=timelapse,
  355. bed_levelling=bed_levelling,
  356. flow_cali=flow_cali,
  357. vibration_cali=vibration_cali,
  358. layer_inspect=layer_inspect,
  359. use_ams=use_ams,
  360. )
  361. return False
  362. def stop_print(self, printer_id: int) -> bool:
  363. """Stop the current print on a connected printer."""
  364. if printer_id in self._clients:
  365. return self._clients[printer_id].stop_print()
  366. return False
  367. async def wait_for_cooldown(
  368. self,
  369. printer_id: int,
  370. target_temp: float = 50.0,
  371. timeout: int = 600,
  372. check_interval: int = 10,
  373. ) -> bool:
  374. """Wait for the nozzle to cool down to a safe temperature.
  375. Args:
  376. printer_id: The printer to monitor
  377. target_temp: Target temperature to wait for (default 50°C)
  378. timeout: Maximum seconds to wait (default 600s = 10 min)
  379. check_interval: Seconds between temperature checks (default 10s)
  380. Returns:
  381. True if cooled down, False if timeout or not connected
  382. """
  383. import logging
  384. logger = logging.getLogger(__name__)
  385. elapsed = 0
  386. while elapsed < timeout:
  387. state = self.get_status(printer_id)
  388. if not state or not state.connected:
  389. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  390. return False
  391. # Check nozzle temperature (and nozzle_2 for dual extruders)
  392. nozzle_temp = state.temperatures.get("nozzle", 0)
  393. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  394. max_temp = max(nozzle_temp, nozzle_2_temp)
  395. if max_temp <= target_temp:
  396. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  397. return True
  398. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  399. await asyncio.sleep(check_interval)
  400. elapsed += check_interval
  401. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  402. return False
  403. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  404. """Enable or disable MQTT logging for a printer."""
  405. if printer_id in self._clients:
  406. self._clients[printer_id].enable_logging(enabled)
  407. return True
  408. return False
  409. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  410. """Get MQTT logs for a printer."""
  411. if printer_id in self._clients:
  412. return self._clients[printer_id].get_logs()
  413. return []
  414. def clear_logs(self, printer_id: int) -> bool:
  415. """Clear MQTT logs for a printer."""
  416. if printer_id in self._clients:
  417. self._clients[printer_id].clear_logs()
  418. return True
  419. return False
  420. def is_logging_enabled(self, printer_id: int) -> bool:
  421. """Check if logging is enabled for a printer."""
  422. if printer_id in self._clients:
  423. return self._clients[printer_id].logging_enabled
  424. return False
  425. def send_drying_command(
  426. self,
  427. printer_id: int,
  428. ams_id: int,
  429. temp: int,
  430. duration: int,
  431. mode: int = 1,
  432. filament: str = "",
  433. rotate_tray: bool = False,
  434. ) -> bool:
  435. """Send AMS drying command to printer."""
  436. if printer_id not in self._clients:
  437. return False
  438. return self._clients[printer_id].send_drying_command(ams_id, temp, duration, mode, filament, rotate_tray)
  439. def request_status_update(self, printer_id: int) -> bool:
  440. """Request a full status update from the printer.
  441. This sends a 'pushall' command to get the latest data including nozzle info.
  442. """
  443. if printer_id in self._clients:
  444. return self._clients[printer_id].request_status_update()
  445. return False
  446. async def test_connection(
  447. self,
  448. ip_address: str,
  449. serial_number: str,
  450. access_code: str,
  451. ) -> dict:
  452. """Test connection to a printer without persisting."""
  453. client = BambuMQTTClient(
  454. ip_address=ip_address,
  455. serial_number=serial_number,
  456. access_code=access_code,
  457. )
  458. try:
  459. client.connect()
  460. await asyncio.sleep(2)
  461. result = {
  462. "success": client.state.connected,
  463. "state": client.state.state if client.state.connected else None,
  464. "model": client.state.raw_data.get("device_model"),
  465. }
  466. finally:
  467. client.disconnect()
  468. return result
  469. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  470. """
  471. Compute a human-readable status name based on printer state.
  472. Uses stg_cur when available, otherwise derives status from temperature data
  473. when the printer is heating before a print starts.
  474. Args:
  475. state: The printer state to analyze
  476. model: Optional printer model for model-specific workarounds
  477. """
  478. # Firmware bug: some models (A1, P1P, P1S) report stg_cur=0 when not printing.
  479. # stg_cur=0 maps to "Printing" in STAGE_NAMES, which incorrectly overrides the
  480. # real state (IDLE, FINISH, FAILED, etc.). Only trust stg_cur when the printer
  481. # is actually in an active print state (RUNNING or PAUSE).
  482. if state.state not in ("RUNNING", "PAUSE") and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  483. return None
  484. # If we have a valid calibration stage, use it
  485. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  486. # Valid stage numbers are 0-254
  487. if 0 <= state.stg_cur < 255:
  488. return get_stage_name(state.stg_cur)
  489. # If not in RUNNING state, no derived status needed
  490. if state.state != "RUNNING":
  491. return None
  492. # Check if we're in an early phase where temperatures are heating
  493. temps = state.temperatures or {}
  494. progress = state.progress or 0
  495. # Only derive heating status when progress is very low (< 2%)
  496. # This indicates we're in the preparation phase, not actually printing
  497. if progress >= 2:
  498. return None
  499. # Check bed temperature - if target is set and current is significantly below
  500. bed_temp = temps.get("bed", 0)
  501. bed_target = temps.get("bed_target", 0)
  502. # Check nozzle temperature
  503. nozzle_temp = temps.get("nozzle", 0)
  504. nozzle_target = temps.get("nozzle_target", 0)
  505. # Temperature thresholds: consider "heating" if more than 10°C below target
  506. TEMP_THRESHOLD = 10
  507. # Determine what's heating (prioritize bed since it takes longer)
  508. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  509. return "Heating heatbed"
  510. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  511. return "Heating nozzle"
  512. # If targets are set but we're close to them, we might be in final prep
  513. if bed_target > 30 or nozzle_target > 30:
  514. if progress == 0 and state.layer_num == 0:
  515. return "Preparing"
  516. return None
  517. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None, model: str | None = None) -> dict:
  518. """Convert PrinterState to a JSON-serializable dict.
  519. Args:
  520. state: The printer state to convert
  521. printer_id: Optional printer ID for generating cover URLs
  522. model: Optional printer model for filtering unsupported features
  523. """
  524. # Parse AMS data from raw_data
  525. ams_units = []
  526. vt_tray = []
  527. raw_data = state.raw_data or {}
  528. # Build K-profile lookup map: cali_idx -> k_value
  529. kprofile_map: dict[int, float] = {}
  530. for kp in state.kprofiles or []:
  531. if kp.slot_id is not None and kp.k_value:
  532. try:
  533. kprofile_map[kp.slot_id] = float(kp.k_value)
  534. except (ValueError, TypeError):
  535. pass # Skip K-profile entries with unparseable values
  536. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  537. for ams_data in raw_data["ams"]:
  538. trays = []
  539. for tray in ams_data.get("tray", []):
  540. tag_uid = tray.get("tag_uid")
  541. if tag_uid in ("", "0000000000000000"):
  542. tag_uid = None
  543. tray_uuid = tray.get("tray_uuid")
  544. if tray_uuid in ("", "00000000000000000000000000000000"):
  545. tray_uuid = None
  546. # Get K value: first try tray's k field, then lookup from K-profiles
  547. k_value = tray.get("k")
  548. cali_idx = tray.get("cali_idx")
  549. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  550. k_value = kprofile_map[cali_idx]
  551. trays.append(
  552. {
  553. "id": int(tray.get("id", 0)),
  554. "tray_color": tray.get("tray_color"),
  555. "tray_type": tray.get("tray_type"),
  556. "tray_sub_brands": tray.get("tray_sub_brands"),
  557. "tray_id_name": tray.get("tray_id_name"),
  558. "tray_info_idx": tray.get("tray_info_idx"),
  559. "remain": tray.get("remain", 0),
  560. "k": k_value,
  561. "cali_idx": cali_idx,
  562. "tag_uid": tag_uid,
  563. "tray_uuid": tray_uuid,
  564. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  565. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  566. "drying_temp": tray.get("drying_temp"),
  567. "drying_time": tray.get("drying_time"),
  568. "state": tray.get("state"),
  569. }
  570. )
  571. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  572. humidity_raw = ams_data.get("humidity_raw")
  573. humidity_idx = ams_data.get("humidity")
  574. humidity_value = None
  575. if humidity_raw is not None:
  576. try:
  577. humidity_value = int(humidity_raw)
  578. except (ValueError, TypeError):
  579. pass # Skip unparseable humidity; will try index fallback
  580. # Fall back to index if no raw value (index is 1-5, not percentage)
  581. if humidity_value is None and humidity_idx is not None:
  582. try:
  583. humidity_value = int(humidity_idx)
  584. except (ValueError, TypeError):
  585. pass # Skip unparseable humidity index; humidity remains None
  586. # AMS-HT has 1 tray, regular AMS has 4 trays
  587. is_ams_ht = len(trays) == 1
  588. ams_units.append(
  589. {
  590. "id": int(ams_data.get("id", 0)),
  591. "humidity": humidity_value,
  592. "temp": ams_data.get("temp"),
  593. "is_ams_ht": is_ams_ht,
  594. "tray": trays,
  595. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  596. "serial_number": str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  597. # Firmware version: populated by _handle_version_info from get_version
  598. "sw_ver": str(ams_data.get("sw_ver") or ""),
  599. # Drying: dry_time > 0 means drying is active (minutes remaining)
  600. "dry_time": int(ams_data.get("dry_time") or 0),
  601. # Drying status from info hex bits (0=Off, 1=Checking, 2=Drying, 3=Cooling, etc.)
  602. "dry_status": int(ams_data.get("dry_status") or 0),
  603. "dry_sub_status": int(ams_data.get("dry_sub_status") or 0),
  604. # Cannot-dry reasons from firmware (e.g. 1=InsufficientPower, 8=NeedPluginPower)
  605. "dry_sf_reason": list(ams_data.get("dry_sf_reason") or []),
  606. # Module type: "ams", "n3f", "n3s" (from get_version)
  607. "module_type": str(ams_data.get("module_type") or ""),
  608. }
  609. )
  610. # Parse virtual tray (external spool) — now a list
  611. if "vt_tray" in raw_data:
  612. vt_tray_raw = raw_data["vt_tray"]
  613. # Defensive: MQTT sends vt_tray as a dict; normalize to list
  614. if isinstance(vt_tray_raw, dict):
  615. vt_tray_raw = [vt_tray_raw]
  616. elif not isinstance(vt_tray_raw, list):
  617. vt_tray_raw = []
  618. for vt_data in vt_tray_raw:
  619. vt_tag_uid = vt_data.get("tag_uid")
  620. if vt_tag_uid in ("", "0000000000000000"):
  621. vt_tag_uid = None
  622. vt_tray_uuid = vt_data.get("tray_uuid")
  623. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  624. vt_tray_uuid = None
  625. # Get K value for vt_tray
  626. vt_k_value = vt_data.get("k")
  627. vt_cali_idx = vt_data.get("cali_idx")
  628. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  629. vt_k_value = kprofile_map[vt_cali_idx]
  630. tray_id = int(vt_data.get("id", 254))
  631. vt_tray.append(
  632. {
  633. "id": tray_id,
  634. "tray_color": vt_data.get("tray_color"),
  635. "tray_type": vt_data.get("tray_type"),
  636. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  637. "tray_id_name": vt_data.get("tray_id_name"),
  638. "tray_info_idx": vt_data.get("tray_info_idx"),
  639. "remain": vt_data.get("remain", 0),
  640. "k": vt_k_value,
  641. "cali_idx": vt_cali_idx,
  642. "tag_uid": vt_tag_uid,
  643. "tray_uuid": vt_tray_uuid,
  644. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  645. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  646. }
  647. )
  648. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  649. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  650. # Filter out chamber temp for models that don't have a real sensor
  651. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  652. temperatures = state.temperatures
  653. if not supports_chamber_temp(model):
  654. temperatures = {
  655. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  656. }
  657. result = {
  658. "connected": state.connected,
  659. "state": state.state,
  660. "current_print": state.current_print,
  661. "subtask_name": state.subtask_name,
  662. "gcode_file": state.gcode_file,
  663. "progress": state.progress,
  664. "remaining_time": state.remaining_time,
  665. "layer_num": state.layer_num,
  666. "total_layers": state.total_layers,
  667. "temperatures": temperatures,
  668. "hms_errors": [
  669. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  670. for e in (state.hms_errors or [])
  671. ],
  672. # AMS data for filament colors
  673. "ams": ams_units if ams_units else None,
  674. "vt_tray": vt_tray,
  675. # AMS status for filament change tracking
  676. "ams_status_main": state.ams_status_main,
  677. "ams_status_sub": state.ams_status_sub,
  678. "tray_now": state.tray_now,
  679. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  680. "ams_extruder_map": ams_extruder_map,
  681. # WiFi signal strength
  682. "wifi_signal": state.wifi_signal,
  683. "wired_network": state.wired_network,
  684. "door_open": state.door_open,
  685. # Calibration stage tracking
  686. "stg_cur": state.stg_cur,
  687. "stg_cur_name": get_derived_status_name(state, model),
  688. # Printable objects count for skip objects feature
  689. "printable_objects_count": len(state.printable_objects),
  690. # Fan speeds (0-100 percentage, None if not available)
  691. "cooling_fan_speed": state.cooling_fan_speed,
  692. "big_fan1_speed": state.big_fan1_speed,
  693. "big_fan2_speed": state.big_fan2_speed,
  694. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  695. # Chamber light state
  696. "chamber_light": state.chamber_light,
  697. # Active extruder for dual-nozzle printers (0=right, 1=left)
  698. "active_extruder": state.active_extruder,
  699. # Print speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  700. "speed_level": state.speed_level,
  701. # H2C nozzle rack (tool-changer dock positions)
  702. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  703. "nozzle_rack": [
  704. {
  705. "id": n.get("id", 0),
  706. "nozzle_type": n.get("type", ""),
  707. "nozzle_diameter": n.get("diameter", ""),
  708. "wear": n.get("wear"),
  709. "stat": n.get("stat"),
  710. "max_temp": n.get("max_temp", 0),
  711. "serial_number": n.get("serial_number", ""),
  712. "filament_color": n.get("filament_color", ""),
  713. "filament_id": n.get("filament_id", ""),
  714. }
  715. for n in (state.nozzle_rack or [])
  716. ],
  717. # AMS drying support
  718. "supports_drying": supports_drying(model, state.firmware_version),
  719. }
  720. # Add cover URL if there's an active print and printer_id is provided
  721. # Include PAUSE state so skip objects modal can show cover
  722. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  723. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  724. else:
  725. result["cover_url"] = None
  726. return result
  727. # Global printer manager instance
  728. printer_manager = PrinterManager()
  729. async def init_printer_connections(db: AsyncSession):
  730. """Initialize connections to all active printers."""
  731. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  732. printers = result.scalars().all()
  733. for printer in printers:
  734. await printer_manager.connect_printer(printer)