printer_manager.py 41 KB

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