printer_manager.py 42 KB

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