printer_manager.py 47 KB

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