printer_manager.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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. Also broadcasts an updated ``printer_status`` over the WebSocket (#1128).
  165. ``awaiting_plate_clear`` is a Bambuddy-side flag — toggling it does not
  166. produce an MQTT push from the printer, so without an explicit broadcast
  167. any UI subscriber that's NOT the originating tab would stay stale until
  168. the next coincidental status refresh. The plate-clear button on the
  169. printer card disappeared "immediately" only because of an optimistic
  170. React Query cache update on the click path; clearing the flag through
  171. any other route (an admin script, a second tab, an automation that
  172. hits ``POST /printers/{id}/clear-plate`` directly) silently broke the
  173. UI without it. Centralised here so every current AND future caller is
  174. covered without each one having to remember to broadcast.
  175. """
  176. if awaiting:
  177. self._awaiting_plate_clear.add(printer_id)
  178. else:
  179. self._awaiting_plate_clear.discard(printer_id)
  180. # Only create the coroutine when there is a loop to run it on — otherwise Python
  181. # emits "coroutine was never awaited" warnings (e.g. in sync unit tests).
  182. if self._loop and self._loop.is_running():
  183. self._schedule_async(self._persist_awaiting_plate_clear(printer_id, awaiting))
  184. self._schedule_async(self._broadcast_status_change(printer_id))
  185. async def _broadcast_status_change(self, printer_id: int) -> None:
  186. """Emit a ``printer_status`` WebSocket update for this printer (#1128).
  187. Used for state changes that don't come from MQTT — currently just the
  188. ``awaiting_plate_clear`` flag, but any future Bambuddy-side flag added
  189. to ``printer_state_to_dict`` should plumb through here too. The
  190. existing MQTT-driven broadcast in ``main.on_printer_status_change``
  191. deduplicates on a status_key that intentionally excludes Bambuddy
  192. flags (so e.g. queue-state changes don't get echoed as printer
  193. events), which is precisely why those flags need their own emit.
  194. Lazy-imports ``ws_manager`` to keep ``printer_manager`` clean of
  195. application-layer infra at module-import time — the broadcast is the
  196. only thing here that needs it.
  197. """
  198. state = self.get_status(printer_id)
  199. if not state:
  200. # Printer disconnected or unknown — nothing to broadcast. The
  201. # next reconnect will produce a fresh status push anyway, so the
  202. # UI eventually catches up without us forcing a stale snapshot
  203. # on subscribers now.
  204. return
  205. try:
  206. from backend.app.core.websocket import ws_manager
  207. await ws_manager.send_printer_status(
  208. printer_id,
  209. printer_state_to_dict(state, printer_id, self.get_model(printer_id)),
  210. )
  211. except Exception as e:
  212. logger.warning(
  213. "Failed to broadcast printer_status after Bambuddy-side state change for printer %d: %s",
  214. printer_id,
  215. e,
  216. )
  217. async def _persist_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  218. from backend.app.core.database import async_session
  219. try:
  220. async with async_session() as db:
  221. printer = await db.get(Printer, printer_id)
  222. if printer is not None:
  223. printer.awaiting_plate_clear = awaiting
  224. await db.commit()
  225. except Exception as e:
  226. logger.warning("Failed to persist awaiting_plate_clear for printer %d: %s", printer_id, e)
  227. async def load_awaiting_plate_clear_from_db(self):
  228. """Rehydrate the awaiting-plate-clear set from the printers table on startup."""
  229. from backend.app.core.database import async_session
  230. try:
  231. async with async_session() as db:
  232. result = await db.execute(select(Printer.id).where(Printer.awaiting_plate_clear.is_(True)))
  233. ids = {row[0] for row in result.all()}
  234. self._awaiting_plate_clear = ids
  235. if ids:
  236. logger.info("Loaded %d printer(s) awaiting plate-clear acknowledgment: %s", len(ids), sorted(ids))
  237. except Exception as e:
  238. logger.warning("Failed to load awaiting_plate_clear from DB: %s", e)
  239. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  240. """Set the event loop for async callbacks."""
  241. self._loop = loop
  242. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  243. """Set callback for print start events."""
  244. self._on_print_start = callback
  245. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  246. """Set callback for print completion events."""
  247. self._on_print_complete = callback
  248. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  249. """Set callback for status change events."""
  250. self._on_status_change = callback
  251. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  252. """Set callback for AMS data change events."""
  253. self._on_ams_change = callback
  254. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  255. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  256. self._on_layer_change = callback
  257. def set_bed_temp_update_callback(self, callback: Callable[[int, float], None]):
  258. """Set callback for bed temperature updates. Receives (printer_id, bed_temp)."""
  259. self._on_bed_temp_update = callback
  260. def _schedule_async(self, coro):
  261. """Schedule an async coroutine from a sync context.
  262. Captures exceptions from the coroutine and logs them to prevent
  263. silent failures in callbacks.
  264. """
  265. if self._loop and self._loop.is_running():
  266. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  267. def handle_exception(f):
  268. try:
  269. # This will re-raise any exception from the coroutine
  270. f.result()
  271. except Exception as e:
  272. import logging
  273. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  274. future.add_done_callback(handle_exception)
  275. async def connect_printer(self, printer: Printer) -> bool:
  276. """Connect to a printer."""
  277. if printer.id in self._clients:
  278. self.disconnect_printer(printer.id)
  279. printer_id = printer.id
  280. def on_state_change(state: PrinterState):
  281. if self._on_status_change:
  282. self._schedule_async(self._on_status_change(printer_id, state))
  283. def on_print_start(data: dict):
  284. if self._on_print_start:
  285. self._schedule_async(self._on_print_start(printer_id, data))
  286. def on_print_complete(data: dict):
  287. if self._on_print_complete:
  288. self._schedule_async(self._on_print_complete(printer_id, data))
  289. def on_ams_change(ams_data: list):
  290. if self._on_ams_change:
  291. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  292. def on_layer_change(layer_num: int):
  293. if self._on_layer_change:
  294. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  295. def on_bed_temp_update(bed_temp: float):
  296. if self._on_bed_temp_update:
  297. self._schedule_async(self._on_bed_temp_update(printer_id, bed_temp))
  298. client = BambuMQTTClient(
  299. ip_address=printer.ip_address,
  300. serial_number=printer.serial_number,
  301. access_code=printer.access_code,
  302. model=printer.model,
  303. on_state_change=on_state_change,
  304. on_print_start=on_print_start,
  305. on_print_complete=on_print_complete,
  306. on_ams_change=on_ams_change,
  307. on_layer_change=on_layer_change,
  308. on_bed_temp_update=on_bed_temp_update,
  309. )
  310. client.connect()
  311. self._clients[printer_id] = client
  312. self._models[printer_id] = printer.model # Cache model for feature detection
  313. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  314. # Wait a moment for connection
  315. await asyncio.sleep(1)
  316. return client.state.connected
  317. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  318. """Disconnect from a printer."""
  319. if printer_id in self._clients:
  320. self._clients[printer_id].disconnect(timeout=timeout)
  321. del self._clients[printer_id]
  322. self._models.pop(printer_id, None) # Clean up model cache
  323. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  324. def disconnect_all(self, timeout: float = 0):
  325. """Disconnect from all printers."""
  326. for printer_id in list(self._clients.keys()):
  327. self.disconnect_printer(printer_id, timeout=timeout)
  328. def get_status(self, printer_id: int) -> PrinterState | None:
  329. """Get the current status of a printer (checks for stale connections)."""
  330. if printer_id in self._clients:
  331. client = self._clients[printer_id]
  332. # Check staleness and update connected state if needed
  333. client.check_staleness()
  334. return client.state
  335. return None
  336. def get_model(self, printer_id: int) -> str | None:
  337. """Get the cached model for a printer."""
  338. return self._models.get(printer_id)
  339. def get_all_statuses(self) -> dict[int, PrinterState]:
  340. """Get status of all connected printers (checks for stale connections)."""
  341. result = {}
  342. for printer_id, client in self._clients.items():
  343. # Check staleness and update connected state if needed
  344. client.check_staleness()
  345. result[printer_id] = client.state
  346. return result
  347. def is_connected(self, printer_id: int) -> bool:
  348. """Check if a printer is connected (checks for stale connections)."""
  349. if printer_id in self._clients:
  350. client = self._clients[printer_id]
  351. # Check staleness and update connected state if needed
  352. return client.check_staleness()
  353. return False
  354. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  355. """Get the MQTT client for a printer."""
  356. return self._clients.get(printer_id)
  357. def mark_printer_offline(self, printer_id: int):
  358. """Mark a printer as offline and trigger status callback.
  359. This is used when we know the printer power was cut (e.g., smart plug turned off)
  360. to immediately update the UI without waiting for MQTT timeout.
  361. """
  362. import logging
  363. logger = logging.getLogger(__name__)
  364. if printer_id in self._clients:
  365. client = self._clients[printer_id]
  366. if client.state.connected:
  367. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  368. client.state.connected = False
  369. client.state.state = "unknown"
  370. # Trigger the status change callback to broadcast via WebSocket
  371. if self._on_status_change:
  372. self._schedule_async(self._on_status_change(printer_id, client.state))
  373. def start_print(
  374. self,
  375. printer_id: int,
  376. filename: str,
  377. plate_id: int = 1,
  378. ams_mapping: list[int] | None = None,
  379. bed_levelling: bool = True,
  380. flow_cali: bool = False,
  381. vibration_cali: bool = True,
  382. layer_inspect: bool = False,
  383. timelapse: bool = False,
  384. use_ams: bool = True,
  385. ) -> bool:
  386. """Start a print on a connected printer."""
  387. caller = traceback.extract_stack(limit=3)[0]
  388. logger.info(
  389. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  390. printer_id,
  391. filename,
  392. caller.filename.split("/")[-1],
  393. caller.lineno,
  394. caller.name,
  395. )
  396. if printer_id in self._clients:
  397. return self._clients[printer_id].start_print(
  398. filename,
  399. plate_id,
  400. ams_mapping=ams_mapping,
  401. timelapse=timelapse,
  402. bed_levelling=bed_levelling,
  403. flow_cali=flow_cali,
  404. vibration_cali=vibration_cali,
  405. layer_inspect=layer_inspect,
  406. use_ams=use_ams,
  407. )
  408. return False
  409. def stop_print(self, printer_id: int) -> bool:
  410. """Stop the current print on a connected printer."""
  411. if printer_id in self._clients:
  412. return self._clients[printer_id].stop_print()
  413. return False
  414. async def wait_for_cooldown(
  415. self,
  416. printer_id: int,
  417. target_temp: float = 50.0,
  418. timeout: int = 600,
  419. check_interval: int = 10,
  420. ) -> bool:
  421. """Wait for the nozzle to cool down to a safe temperature.
  422. Args:
  423. printer_id: The printer to monitor
  424. target_temp: Target temperature to wait for (default 50°C)
  425. timeout: Maximum seconds to wait (default 600s = 10 min)
  426. check_interval: Seconds between temperature checks (default 10s)
  427. Returns:
  428. True if cooled down, False if timeout or not connected
  429. """
  430. import logging
  431. logger = logging.getLogger(__name__)
  432. elapsed = 0
  433. while elapsed < timeout:
  434. state = self.get_status(printer_id)
  435. if not state or not state.connected:
  436. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  437. return False
  438. # Check nozzle temperature (and nozzle_2 for dual extruders)
  439. nozzle_temp = state.temperatures.get("nozzle", 0)
  440. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  441. max_temp = max(nozzle_temp, nozzle_2_temp)
  442. if max_temp <= target_temp:
  443. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  444. return True
  445. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  446. await asyncio.sleep(check_interval)
  447. elapsed += check_interval
  448. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  449. return False
  450. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  451. """Enable or disable MQTT logging for a printer."""
  452. if printer_id in self._clients:
  453. self._clients[printer_id].enable_logging(enabled)
  454. return True
  455. return False
  456. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  457. """Get MQTT logs for a printer."""
  458. if printer_id in self._clients:
  459. return self._clients[printer_id].get_logs()
  460. return []
  461. def clear_logs(self, printer_id: int) -> bool:
  462. """Clear MQTT logs for a printer."""
  463. if printer_id in self._clients:
  464. self._clients[printer_id].clear_logs()
  465. return True
  466. return False
  467. def is_logging_enabled(self, printer_id: int) -> bool:
  468. """Check if logging is enabled for a printer."""
  469. if printer_id in self._clients:
  470. return self._clients[printer_id].logging_enabled
  471. return False
  472. def send_drying_command(
  473. self,
  474. printer_id: int,
  475. ams_id: int,
  476. temp: int,
  477. duration: int,
  478. mode: int = 1,
  479. filament: str = "",
  480. rotate_tray: bool = False,
  481. ) -> bool:
  482. """Send AMS drying command to printer."""
  483. if printer_id not in self._clients:
  484. return False
  485. return self._clients[printer_id].send_drying_command(ams_id, temp, duration, mode, filament, rotate_tray)
  486. def request_status_update(self, printer_id: int) -> bool:
  487. """Request a full status update from the printer.
  488. This sends a 'pushall' command to get the latest data including nozzle info.
  489. """
  490. if printer_id in self._clients:
  491. return self._clients[printer_id].request_status_update()
  492. return False
  493. async def test_connection(
  494. self,
  495. ip_address: str,
  496. serial_number: str,
  497. access_code: str,
  498. ) -> dict:
  499. """Test connection to a printer without persisting."""
  500. client = BambuMQTTClient(
  501. ip_address=ip_address,
  502. serial_number=serial_number,
  503. access_code=access_code,
  504. )
  505. try:
  506. client.connect()
  507. await asyncio.sleep(2)
  508. result = {
  509. "success": client.state.connected,
  510. "state": client.state.state if client.state.connected else None,
  511. "model": client.state.raw_data.get("device_model"),
  512. }
  513. finally:
  514. client.disconnect()
  515. return result
  516. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  517. """
  518. Compute a human-readable status name based on printer state.
  519. Uses stg_cur when available, otherwise derives status from temperature data
  520. when the printer is heating before a print starts.
  521. Args:
  522. state: The printer state to analyze
  523. model: Optional printer model for model-specific workarounds
  524. """
  525. # Firmware bug: some models (A1, P1P, P1S) report stg_cur=0 when not printing.
  526. # stg_cur=0 maps to "Printing" in STAGE_NAMES, which incorrectly overrides the
  527. # real state (IDLE, FINISH, FAILED, etc.). Only trust stg_cur when the printer
  528. # is actually in an active print state (RUNNING or PAUSE).
  529. if state.state not in ("RUNNING", "PAUSE") and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  530. return None
  531. # If we have a valid calibration stage, use it
  532. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  533. # Valid stage numbers are 0-254
  534. if 0 <= state.stg_cur < 255:
  535. return get_stage_name(state.stg_cur)
  536. # If not in RUNNING state, no derived status needed
  537. if state.state != "RUNNING":
  538. return None
  539. # Check if we're in an early phase where temperatures are heating
  540. temps = state.temperatures or {}
  541. progress = state.progress or 0
  542. # Only derive heating status when progress is very low (< 2%)
  543. # This indicates we're in the preparation phase, not actually printing
  544. if progress >= 2:
  545. return None
  546. # Check bed temperature - if target is set and current is significantly below
  547. bed_temp = temps.get("bed", 0)
  548. bed_target = temps.get("bed_target", 0)
  549. # Check nozzle temperature
  550. nozzle_temp = temps.get("nozzle", 0)
  551. nozzle_target = temps.get("nozzle_target", 0)
  552. # Temperature thresholds: consider "heating" if more than 10°C below target
  553. TEMP_THRESHOLD = 10
  554. # Determine what's heating (prioritize bed since it takes longer)
  555. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  556. return "Heating heatbed"
  557. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  558. return "Heating nozzle"
  559. # If targets are set but we're close to them, we might be in final prep
  560. if bed_target > 30 or nozzle_target > 30:
  561. if progress == 0 and state.layer_num == 0:
  562. return "Preparing"
  563. return None
  564. _PLATE_ID_RE = re.compile(r"plate_(\d+)\.gcode")
  565. def parse_plate_id(gcode_file: str | None) -> int | None:
  566. """Extract the 1-indexed plate number from a Bambu gcode_file path.
  567. Returns None when the path is missing or has no `plate_N.gcode` segment.
  568. Shared by the REST status route and the WebSocket push path so both agree
  569. on the value sent to the frontend (#881 follow-up).
  570. """
  571. if not gcode_file:
  572. return None
  573. match = _PLATE_ID_RE.search(gcode_file)
  574. return int(match.group(1)) if match else None
  575. def resolve_plate_id(state) -> int | None:
  576. """Resolve the active plate number from a PrinterState.
  577. Some firmware versions (e.g. P1S 01.10.00.00, #1166) put only the .3mf
  578. filename in print.gcode_file, so parse_plate_id() returns None and the
  579. printer card falls back to plate 1 — wrong thumbnail. When Bambuddy
  580. dispatched the print itself we already know the right plate, so we prefer
  581. that over the gcode_file echo. The subtask check prevents stale values
  582. from a previous Bambuddy-dispatched print bleeding into a Studio-direct
  583. print on the same printer.
  584. """
  585. dispatched_plate = getattr(state, "dispatched_plate_id", None)
  586. dispatched_subtask = getattr(state, "dispatched_subtask", None)
  587. if (
  588. dispatched_plate is not None
  589. and dispatched_subtask is not None
  590. and state.subtask_name
  591. and dispatched_subtask == state.subtask_name
  592. ):
  593. return dispatched_plate
  594. return parse_plate_id(state.gcode_file)
  595. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None, model: str | None = None) -> dict:
  596. """Convert PrinterState to a JSON-serializable dict.
  597. Args:
  598. state: The printer state to convert
  599. printer_id: Optional printer ID for generating cover URLs
  600. model: Optional printer model for filtering unsupported features
  601. """
  602. # Parse AMS data from raw_data
  603. ams_units = []
  604. vt_tray = []
  605. raw_data = state.raw_data or {}
  606. # Build K-profile lookup map: cali_idx -> k_value
  607. kprofile_map: dict[int, float] = {}
  608. for kp in state.kprofiles or []:
  609. if kp.slot_id is not None and kp.k_value:
  610. try:
  611. kprofile_map[kp.slot_id] = float(kp.k_value)
  612. except (ValueError, TypeError):
  613. pass # Skip K-profile entries with unparseable values
  614. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  615. for ams_data in raw_data["ams"]:
  616. trays = []
  617. for tray in ams_data.get("tray", []):
  618. tag_uid = tray.get("tag_uid")
  619. if tag_uid in ("", "0000000000000000"):
  620. tag_uid = None
  621. tray_uuid = tray.get("tray_uuid")
  622. if tray_uuid in ("", "00000000000000000000000000000000"):
  623. tray_uuid = None
  624. # Get K value: first try tray's k field, then lookup from K-profiles
  625. k_value = tray.get("k")
  626. cali_idx = tray.get("cali_idx")
  627. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  628. k_value = kprofile_map[cali_idx]
  629. trays.append(
  630. {
  631. "id": int(tray.get("id", 0)),
  632. "tray_color": tray.get("tray_color"),
  633. "tray_type": tray.get("tray_type"),
  634. "tray_sub_brands": tray.get("tray_sub_brands"),
  635. "tray_id_name": tray.get("tray_id_name"),
  636. "tray_info_idx": tray.get("tray_info_idx"),
  637. "remain": tray.get("remain", 0),
  638. "k": k_value,
  639. "cali_idx": cali_idx,
  640. "tag_uid": tag_uid,
  641. "tray_uuid": tray_uuid,
  642. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  643. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  644. "drying_temp": tray.get("drying_temp"),
  645. "drying_time": tray.get("drying_time"),
  646. "state": tray.get("state"),
  647. }
  648. )
  649. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  650. humidity_raw = ams_data.get("humidity_raw")
  651. humidity_idx = ams_data.get("humidity")
  652. humidity_value = None
  653. if humidity_raw is not None:
  654. try:
  655. humidity_value = int(humidity_raw)
  656. except (ValueError, TypeError):
  657. pass # Skip unparseable humidity; will try index fallback
  658. # Fall back to index if no raw value (index is 1-5, not percentage)
  659. if humidity_value is None and humidity_idx is not None:
  660. try:
  661. humidity_value = int(humidity_idx)
  662. except (ValueError, TypeError):
  663. pass # Skip unparseable humidity index; humidity remains None
  664. # AMS-HT has 1 tray, regular AMS has 4 trays
  665. is_ams_ht = len(trays) == 1
  666. ams_units.append(
  667. {
  668. "id": int(ams_data.get("id", 0)),
  669. "humidity": humidity_value,
  670. "temp": ams_data.get("temp"),
  671. "is_ams_ht": is_ams_ht,
  672. "tray": trays,
  673. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  674. "serial_number": str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  675. # Firmware version: populated by _handle_version_info from get_version
  676. "sw_ver": str(ams_data.get("sw_ver") or ""),
  677. # Drying: dry_time > 0 means drying is active (minutes remaining)
  678. "dry_time": int(ams_data.get("dry_time") or 0),
  679. # Drying status from info hex bits (0=Off, 1=Checking, 2=Drying, 3=Cooling, etc.)
  680. "dry_status": int(ams_data.get("dry_status") or 0),
  681. "dry_sub_status": int(ams_data.get("dry_sub_status") or 0),
  682. # Cannot-dry reasons from firmware (e.g. 1=InsufficientPower, 8=NeedPluginPower)
  683. "dry_sf_reason": list(ams_data.get("dry_sf_reason") or []),
  684. # Module type: "ams", "n3f", "n3s" (from get_version)
  685. "module_type": str(ams_data.get("module_type") or ""),
  686. }
  687. )
  688. # Parse virtual tray (external spool) — now a list
  689. if "vt_tray" in raw_data:
  690. vt_tray_raw = raw_data["vt_tray"]
  691. # Defensive: MQTT sends vt_tray as a dict; normalize to list
  692. if isinstance(vt_tray_raw, dict):
  693. vt_tray_raw = [vt_tray_raw]
  694. elif not isinstance(vt_tray_raw, list):
  695. vt_tray_raw = []
  696. for vt_data in vt_tray_raw:
  697. vt_tag_uid = vt_data.get("tag_uid")
  698. if vt_tag_uid in ("", "0000000000000000"):
  699. vt_tag_uid = None
  700. vt_tray_uuid = vt_data.get("tray_uuid")
  701. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  702. vt_tray_uuid = None
  703. # Get K value for vt_tray
  704. vt_k_value = vt_data.get("k")
  705. vt_cali_idx = vt_data.get("cali_idx")
  706. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  707. vt_k_value = kprofile_map[vt_cali_idx]
  708. tray_id = int(vt_data.get("id", 254))
  709. vt_tray.append(
  710. {
  711. "id": tray_id,
  712. "tray_color": vt_data.get("tray_color"),
  713. "tray_type": vt_data.get("tray_type"),
  714. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  715. "tray_id_name": vt_data.get("tray_id_name"),
  716. "tray_info_idx": vt_data.get("tray_info_idx"),
  717. "remain": vt_data.get("remain", 0),
  718. "k": vt_k_value,
  719. "cali_idx": vt_cali_idx,
  720. "tag_uid": vt_tag_uid,
  721. "tray_uuid": vt_tray_uuid,
  722. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  723. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  724. }
  725. )
  726. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  727. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  728. # Filter out chamber temp for models that don't have a real sensor
  729. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  730. temperatures = state.temperatures
  731. if not supports_chamber_temp(model):
  732. temperatures = {
  733. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  734. }
  735. result = {
  736. "connected": state.connected,
  737. "state": state.state,
  738. "current_print": state.current_print,
  739. "subtask_name": state.subtask_name,
  740. "gcode_file": state.gcode_file,
  741. "progress": state.progress,
  742. "remaining_time": state.remaining_time,
  743. "layer_num": state.layer_num,
  744. "total_layers": state.total_layers,
  745. "temperatures": temperatures,
  746. "hms_errors": [
  747. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  748. for e in (state.hms_errors or [])
  749. ],
  750. # AMS data for filament colors
  751. "ams": ams_units if ams_units else None,
  752. "vt_tray": vt_tray,
  753. # AMS status for filament change tracking
  754. "ams_status_main": state.ams_status_main,
  755. "ams_status_sub": state.ams_status_sub,
  756. "tray_now": state.tray_now,
  757. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  758. "ams_extruder_map": ams_extruder_map,
  759. # WiFi signal strength
  760. "wifi_signal": state.wifi_signal,
  761. "wired_network": state.wired_network,
  762. "door_open": state.door_open,
  763. # Calibration stage tracking
  764. "stg_cur": state.stg_cur,
  765. "stg_cur_name": get_derived_status_name(state, model),
  766. # Printable objects count for skip objects feature
  767. "printable_objects_count": len(state.printable_objects),
  768. # Fan speeds (0-100 percentage, None if not available)
  769. "cooling_fan_speed": state.cooling_fan_speed,
  770. "big_fan1_speed": state.big_fan1_speed,
  771. "big_fan2_speed": state.big_fan2_speed,
  772. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  773. # Chamber light state
  774. "chamber_light": state.chamber_light,
  775. # Active extruder for dual-nozzle printers (0=right, 1=left)
  776. "active_extruder": state.active_extruder,
  777. # Print speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  778. "speed_level": state.speed_level,
  779. # H2C nozzle rack (tool-changer dock positions)
  780. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  781. "nozzle_rack": [
  782. {
  783. "id": n.get("id", 0),
  784. "nozzle_type": n.get("type", ""),
  785. "nozzle_diameter": n.get("diameter", ""),
  786. "wear": n.get("wear"),
  787. "stat": n.get("stat"),
  788. "max_temp": n.get("max_temp", 0),
  789. "serial_number": n.get("serial_number", ""),
  790. "filament_color": n.get("filament_color", ""),
  791. "filament_id": n.get("filament_id", ""),
  792. }
  793. for n in (state.nozzle_rack or [])
  794. ],
  795. # AMS drying support
  796. "supports_drying": supports_drying(model, state.firmware_version),
  797. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  798. # Pushed via WebSocket so the printer card picks up plate transitions within
  799. # a multi-plate 3MF without waiting for the 30 s REST poll (#881 follow-up).
  800. # current_archive_id is intentionally REST-only — it's stable for the life
  801. # of a print and needs a DB lookup the WebSocket path shouldn't pay for.
  802. "current_plate_id": resolve_plate_id(state),
  803. # Plate-clear gate (#939). Lives on the PrinterManager rather than PrinterState,
  804. # so surface it here — without this, WebSocket merges drop the flag and the
  805. # "Clear Plate" button only appears when the 30 s REST fallback poll runs.
  806. "awaiting_plate_clear": printer_manager.is_awaiting_plate_clear(printer_id) if printer_id else False,
  807. }
  808. # Add cover URL if there's an active print and printer_id is provided
  809. # Include PAUSE state so skip objects modal can show cover
  810. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  811. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  812. else:
  813. result["cover_url"] = None
  814. # Surface the display name + model so WS consumers (gcode viewer printer
  815. # selector) can render proper labels on the initial snapshot without racing
  816. # a separate /api/v1/printers fetch (#963 follow-up). PrinterInfo only
  817. # carries name/serial_number; the model comes through via the `model` arg.
  818. if printer_id:
  819. _printer_info = printer_manager.get_printer(printer_id)
  820. if _printer_info is not None:
  821. result["name"] = _printer_info.name
  822. if model:
  823. result["model"] = model
  824. return result
  825. # Global printer manager instance
  826. printer_manager = PrinterManager()
  827. async def init_printer_connections(db: AsyncSession):
  828. """Initialize connections to all active printers."""
  829. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  830. printers = result.scalars().all()
  831. for printer in printers:
  832. await printer_manager.connect_printer(printer)