printer_manager.py 41 KB

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