printer_manager.py 36 KB

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