printer_manager.py 34 KB

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