printer_manager.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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. # Models with a cooling / heating airduct flap. Same set as the frontend
  110. # PrintersPage airduct-toggle whitelist (P2S, X2D, H2D, H2C, H2S, H2D Pro).
  111. # X1E has a chamber heater but NO airduct flap — the warm-air recirculation
  112. # happens via the fixed front-door inlet, so no `set_airduct` command is
  113. # needed (and the firmware ignores it). P2S has an airduct but no heater —
  114. # the flap manages chamber airflow even without an active heater. The
  115. # intersection (chamber heater AND airduct) is what the preheat stage cares
  116. # about: when M141 fires we also need to assert heating mode, otherwise the
  117. # default cooling mode actively fights the chamber heater.
  118. CHAMBER_AIRDUCT_MODELS = frozenset(
  119. [
  120. # Display names
  121. "P2S",
  122. "X2D",
  123. "H2C",
  124. "H2D",
  125. "H2DPRO",
  126. "H2S",
  127. # Internal codes (from MQTT/SSDP)
  128. "N7", # P2S
  129. "N6", # X2D
  130. "O1C", # H2C
  131. "O1C2", # H2C dual-nozzle variant
  132. "O1D", # H2D
  133. "O1E", # H2D Pro
  134. "O2D", # H2D Pro alternate code
  135. "O1S", # H2S
  136. ]
  137. )
  138. def supports_airduct(model: str | None) -> bool:
  139. """Check if a printer model has a cooling / heating airduct mode toggle.
  140. Mirrors the frontend PrintersPage `['P2S', 'X2D', 'H2D', 'H2C', 'H2S']`
  141. + H2D Pro whitelist. Distinct from `supports_chamber_heater` — P2S has
  142. the airduct toggle but no active heater, and X1E has the heater but no
  143. airduct. The preheat stage cares about the intersection (heater AND
  144. airduct) so it can flip the flap to heating before energising M141.
  145. """
  146. if not model:
  147. return False
  148. return model.strip().upper() in CHAMBER_AIRDUCT_MODELS
  149. def has_stg_cur_idle_bug(model: str | None) -> bool:
  150. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  151. Some firmware versions report stg_cur=0 (which maps to "Printing")
  152. even when the printer is idle. Originally observed on A1/A1 Mini via the
  153. Home Assistant Bambu Lab integration, also confirmed on P1S.
  154. """
  155. if not model:
  156. return False
  157. model_upper = model.strip().upper()
  158. return model_upper in STG_CUR_IDLE_BUG_MODELS
  159. def is_bed_slinger(model: str | None) -> bool:
  160. """Whether the printer's Z axis controls the *toolhead*, not the bed.
  161. Bambu's A1 family (A1, A1 Mini; internal codes N1 / N2S) are open-frame
  162. bed-slingers: the bed moves on Y, the toolhead moves on X+Z. On every
  163. other current model (X1, P1, H2, H2C, H2D, H2S, P2S, ...) the bed moves
  164. on Z and the toolhead is fixed in Z.
  165. G-code direction is opposite on these two families. `G1 Z-10` reduces
  166. the nozzle-bed gap on both, but on bed-on-Z machines it does so by
  167. moving the BED up, while on bed-slingers it does so by moving the
  168. TOOLHEAD down — which is what crashed the nozzle in #1334.
  169. """
  170. if not model:
  171. return False
  172. return model.strip().upper() in A1_MODELS
  173. # Minimum firmware versions for AMS drying support (confirmed via capture testing)
  174. # Keys are exact model names (upper-cased). Do NOT use substring matching — it would
  175. # incorrectly gate X1E (matched by "X1") and H2D Pro (matched by "H2D").
  176. _DRYING_MIN_FIRMWARE: dict[str, str] = {
  177. "H2D": "01.02.30.00",
  178. "H2S": "01.02.00.00",
  179. "H2C": "01.02.00.00",
  180. "O1C": "01.02.00.00", # H2C SSDP model code
  181. "O1C2": "01.02.00.00", # H2C dual-nozzle SSDP model code
  182. "X1": "01.09.00.00",
  183. "X1C": "01.09.00.00",
  184. "P2S": "01.02.00.00",
  185. "N7": "01.02.00.00", # P2S internal model code
  186. }
  187. # Models that definitely don't support AMS drying (no AMS 2 Pro / AMS-HT compatibility)
  188. _DRYING_UNSUPPORTED_MODELS = frozenset({"A1", "A1MINI", "A1-MINI", "A1 MINI", "O1S", "N1", "N2S"})
  189. # Models whose AMS can dry, but only from the printer's own touchscreen. Bambu's P1
  190. # manual is explicit: "P1S connected AMS drying functions may only be controlled from
  191. # the P1S screen." The firmware still answers `ams_filament_drying` with
  192. # result: success and then does nothing — the reporter of #2533 sent it three times
  193. # on an idle P1S with an AMS 2 Pro and the unit never left dry_status 0. Bambuddy
  194. # originally listed P1P/P1S here as fw-gated (01.08+, #292); that version is when P1
  195. # firmware gained AMS 2 Pro *support*, not remote drying, and it was never verified
  196. # against a live P1. Nothing we can send will start a cycle, so we don't offer to.
  197. _DRYING_SCREEN_ONLY_MODELS = frozenset({"P1P", "P1S"})
  198. def drying_screen_only(model: str | None) -> bool:
  199. """True when the model's AMS dries only via the printer's own screen (#2533).
  200. Distinct from "unsupported": these printers *can* dry, and Bambuddy still shows
  201. a cycle started on the printer. They just can't be commanded to start or stop
  202. one remotely, so the UI explains that instead of silently dropping the control.
  203. """
  204. if not model:
  205. return False
  206. return model.strip().upper() in _DRYING_SCREEN_ONLY_MODELS
  207. def supports_drying(model: str | None, firmware: str | None) -> bool:
  208. """Check if a printer model accepts remote AMS drying commands.
  209. Known models with confirmed min firmware get version-gated.
  210. Known unsupported models, and models that only dry from their own screen,
  211. are blocked.
  212. All other models (H2D Pro, X1E, future models) are allowed —
  213. the command fails gracefully with result: "fail" if unsupported.
  214. """
  215. if not model:
  216. return False
  217. model_upper = model.strip().upper()
  218. if model_upper in _DRYING_UNSUPPORTED_MODELS or model_upper in _DRYING_SCREEN_ONLY_MODELS:
  219. return False
  220. if model_upper in _DRYING_MIN_FIRMWARE:
  221. return bool(firmware and firmware >= _DRYING_MIN_FIRMWARE[model_upper])
  222. # For all other models: allow
  223. return True
  224. # Minimum firmware versions for AMS "Print While Drying" — drying that runs CONCURRENTLY
  225. # with an active print. Strictly stricter than _DRYING_MIN_FIRMWARE (idle drying). Verified
  226. # against Bambu wiki release notes — the canonical phrasing on every supported model is
  227. # "printing while filament is drying" / "Print While Drying". Models absent from the wiki
  228. # release notes (A1, A1 Mini, P1*, X1 non-C, X1E) are intentionally excluded — the firmware
  229. # will reject the command in those cases anyway via dry_sf_reason=[0] (TaskOccupied).
  230. _DRY_WHILE_PRINTING_MIN_FIRMWARE: dict[str, str] = {
  231. "H2D": "01.03.00.00",
  232. "H2D PRO": "01.02.00.00",
  233. "H2DPRO": "01.02.00.00",
  234. "O1E": "01.02.00.00", # H2D Pro SSDP code
  235. "O2D": "01.02.00.00", # H2D Pro alternate code
  236. "H2C": "01.02.00.00",
  237. "O1C": "01.02.00.00", # H2C SSDP code
  238. "O1C2": "01.02.00.00", # H2C dual-nozzle SSDP code
  239. "H2S": "01.02.00.00",
  240. "X2D": "01.01.00.00",
  241. "N6": "01.01.00.00", # X2D internal code
  242. "X1C": "01.11.02.00",
  243. "BL-P001": "01.11.02.00", # X1C internal code
  244. "P2S": "01.02.00.00",
  245. "N7": "01.02.00.00", # P2S internal code
  246. "A2L": "01.01.00.00",
  247. "N9": "01.01.00.00", # A2L internal code
  248. }
  249. def supports_drying_while_printing(model: str | None, firmware: str | None) -> bool:
  250. """Check if a printer model+firmware supports running AMS drying CONCURRENTLY
  251. with an active print.
  252. Distinct from supports_drying() — that gates idle drying. This gate is strict:
  253. only models explicitly confirmed by Bambu wiki release notes are allowed.
  254. On unsupported models the firmware returns dry_sf_reason=[0] (TaskOccupied)
  255. while a print is running, so being conservative here costs nothing — the
  256. firmware is the ultimate arbiter, this gate just hides UI affordances.
  257. """
  258. if not model:
  259. return False
  260. model_upper = model.strip().upper()
  261. if model_upper not in _DRY_WHILE_PRINTING_MIN_FIRMWARE:
  262. return False
  263. return bool(firmware and firmware >= _DRY_WHILE_PRINTING_MIN_FIRMWARE[model_upper])
  264. class PrinterInfo:
  265. """Basic printer info for callbacks."""
  266. def __init__(self, name: str, serial_number: str):
  267. self.name = name
  268. self.serial_number = serial_number
  269. class PrinterManager:
  270. """Manager for multiple printer connections."""
  271. def __init__(self):
  272. self._clients: dict[int, BambuMQTTClient] = {}
  273. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  274. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  275. self._on_print_start: Callable[[int, dict], None] | None = None
  276. self._on_print_complete: Callable[[int, dict], None] | None = None
  277. self._on_print_running_observed: Callable[[int, dict], None] | None = None
  278. self._on_finish_photo_moment: Callable[[int, dict], None] | None = None
  279. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  280. self._on_ams_change: Callable[[int, list], None] | None = None
  281. self._on_layer_change: Callable[[int, int], None] | None = None
  282. self._on_print_progress: Callable[[int, int], None] | None = None
  283. self._on_bed_temp_update: Callable[[int, float], None] | None = None
  284. self._on_drying_complete: Callable[[int, int], None] | None = None
  285. self._on_assignment_verified: Callable[[int, int, int, bool, dict], None] | None = None
  286. self._loop: asyncio.AbstractEventLoop | None = None
  287. # Track who started the current print (Issue #206)
  288. self._current_print_user: dict[int, dict] = {} # {printer_id: {"user_id": int, "username": str}}
  289. # Track printers awaiting plate-clear acknowledgment after a finished/failed print.
  290. # Persisted to DB (printers.awaiting_plate_clear) so the gate survives restarts/power
  291. # cycles — see issue #961. Loaded into this set at startup via load_awaiting_plate_clear_from_db().
  292. self._awaiting_plate_clear: set[int] = set()
  293. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  294. """Get printer info by ID."""
  295. return self._printer_info.get(printer_id)
  296. def set_current_print_user(self, printer_id: int, user_id: int, username: str):
  297. """Track who started the current print (Issue #206)."""
  298. self._current_print_user[printer_id] = {"user_id": user_id, "username": username}
  299. def get_current_print_user(self, printer_id: int) -> dict | None:
  300. """Get the user who started the current print (Issue #206)."""
  301. return self._current_print_user.get(printer_id)
  302. def clear_current_print_user(self, printer_id: int):
  303. """Clear the current print user when print completes (Issue #206)."""
  304. self._current_print_user.pop(printer_id, None)
  305. def is_awaiting_plate_clear(self, printer_id: int) -> bool:
  306. """Return True when the printer finished/failed a print and is waiting for the
  307. user to acknowledge the plate is cleared before the queue may dispatch the next job.
  308. """
  309. return printer_id in self._awaiting_plate_clear
  310. def set_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  311. """Set/clear the awaiting-plate-clear gate and persist it to DB.
  312. Persisted so the gate survives Bambuddy/printer restarts (#961): after Auto Off
  313. cycles the printer, the printer boots into IDLE with no memory of the previous
  314. finish, and without persistence the queue would bypass the confirmation prompt.
  315. Also broadcasts an updated ``printer_status`` over the WebSocket (#1128).
  316. ``awaiting_plate_clear`` is a Bambuddy-side flag — toggling it does not
  317. produce an MQTT push from the printer, so without an explicit broadcast
  318. any UI subscriber that's NOT the originating tab would stay stale until
  319. the next coincidental status refresh. The plate-clear button on the
  320. printer card disappeared "immediately" only because of an optimistic
  321. React Query cache update on the click path; clearing the flag through
  322. any other route (an admin script, a second tab, an automation that
  323. hits ``POST /printers/{id}/clear-plate`` directly) silently broke the
  324. UI without it. Centralised here so every current AND future caller is
  325. covered without each one having to remember to broadcast.
  326. """
  327. # Callers re-assert the current value routinely (the queue clears the gate
  328. # on every dispatch, whether or not it was up), so the outward-facing
  329. # emissions below are edge-triggered — an MQTT subscriber or a phone
  330. # notification must not see a "plate cleared" for a plate that was never
  331. # dirty. Persistence and the WebSocket broadcast stay unconditional: they
  332. # are idempotent and predate this (#961/#1128).
  333. changed = awaiting != (printer_id in self._awaiting_plate_clear)
  334. if awaiting:
  335. self._awaiting_plate_clear.add(printer_id)
  336. else:
  337. self._awaiting_plate_clear.discard(printer_id)
  338. # Only create the coroutine when there is a loop to run it on — otherwise Python
  339. # emits "coroutine was never awaited" warnings (e.g. in sync unit tests).
  340. if self._loop and self._loop.is_running():
  341. self._schedule_async(self._persist_awaiting_plate_clear(printer_id, awaiting))
  342. self._schedule_async(self._broadcast_status_change(printer_id))
  343. if changed:
  344. self._schedule_async(self._emit_plate_clear_change(printer_id, awaiting))
  345. async def _emit_plate_clear_change(self, printer_id: int, awaiting: bool) -> None:
  346. """Relay a plate-clear gate transition to MQTT and notifications (#2525).
  347. The flag is Bambuddy-side, so nothing about it reaches an external
  348. automation on its own — the printer's own MQTT push knows only
  349. RUNNING/PAUSE/FAILED/FINISH/IDLE. Emitted from here rather than from the
  350. three call sites so every current and future caller is covered, the same
  351. reasoning as the WebSocket broadcast above.
  352. Imports are local: ``mqtt_relay`` and ``notification_service`` both sit
  353. above this module in the dependency order.
  354. """
  355. printer = self.get_printer(printer_id)
  356. if not printer:
  357. return
  358. try:
  359. from backend.app.services.mqtt_relay import mqtt_relay
  360. await mqtt_relay.on_plate_clear_state(printer_id, printer.name, printer.serial_number, awaiting)
  361. except Exception as e:
  362. logger.warning("Failed to publish plate-clear state for printer %d: %s", printer_id, e)
  363. # Only the rising edge is worth a notification — "the bed is now free"
  364. # is not an action item, and the queue clears the gate by itself.
  365. if not awaiting:
  366. return
  367. try:
  368. from backend.app.core.database import async_session
  369. from backend.app.services.notification_service import notification_service
  370. async with async_session() as db:
  371. await notification_service.on_plate_clear_required(printer_id, printer.name, db)
  372. except Exception as e:
  373. logger.warning("Failed to send plate-clear notification for printer %d: %s", printer_id, e)
  374. async def _broadcast_status_change(self, printer_id: int) -> None:
  375. """Emit a ``printer_status`` WebSocket update for this printer (#1128).
  376. Used for state changes that don't come from MQTT — currently just the
  377. ``awaiting_plate_clear`` flag, but any future Bambuddy-side flag added
  378. to ``printer_state_to_dict`` should plumb through here too. The
  379. existing MQTT-driven broadcast in ``main.on_printer_status_change``
  380. deduplicates on a status_key that intentionally excludes Bambuddy
  381. flags (so e.g. queue-state changes don't get echoed as printer
  382. events), which is precisely why those flags need their own emit.
  383. Lazy-imports ``ws_manager`` to keep ``printer_manager`` clean of
  384. application-layer infra at module-import time — the broadcast is the
  385. only thing here that needs it.
  386. """
  387. state = self.get_status(printer_id)
  388. if not state:
  389. # Printer disconnected or unknown — nothing to broadcast. The
  390. # next reconnect will produce a fresh status push anyway, so the
  391. # UI eventually catches up without us forcing a stale snapshot
  392. # on subscribers now.
  393. return
  394. try:
  395. from backend.app.core.websocket import ws_manager
  396. await ws_manager.send_printer_status(
  397. printer_id,
  398. printer_state_to_dict(
  399. state,
  400. printer_id,
  401. self.get_model(printer_id),
  402. self.get_drying_targets(printer_id),
  403. ),
  404. )
  405. except Exception as e:
  406. logger.warning(
  407. "Failed to broadcast printer_status after Bambuddy-side state change for printer %d: %s",
  408. printer_id,
  409. e,
  410. )
  411. async def _persist_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  412. from backend.app.core.database import run_with_retry
  413. async def _do(db):
  414. printer = await db.get(Printer, printer_id)
  415. if printer is not None:
  416. printer.awaiting_plate_clear = awaiting
  417. await db.commit()
  418. try:
  419. await run_with_retry(_do, label=f"persist awaiting_plate_clear printer={printer_id}")
  420. except Exception as e:
  421. logger.warning("Failed to persist awaiting_plate_clear for printer %d: %s", printer_id, e)
  422. async def load_awaiting_plate_clear_from_db(self):
  423. """Rehydrate the awaiting-plate-clear set from the printers table on startup."""
  424. from backend.app.core.database import async_session
  425. try:
  426. async with async_session() as db:
  427. result = await db.execute(select(Printer.id).where(Printer.awaiting_plate_clear.is_(True)))
  428. ids = {row[0] for row in result.all()}
  429. self._awaiting_plate_clear = ids
  430. if ids:
  431. logger.info("Loaded %d printer(s) awaiting plate-clear acknowledgment: %s", len(ids), sorted(ids))
  432. except Exception as e:
  433. logger.warning("Failed to load awaiting_plate_clear from DB: %s", e)
  434. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  435. """Set the event loop for async callbacks."""
  436. self._loop = loop
  437. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  438. """Set callback for print start events."""
  439. self._on_print_start = callback
  440. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  441. """Set callback for print completion events."""
  442. self._on_print_complete = callback
  443. def set_print_running_observed_callback(self, callback: Callable[[int, dict], None]):
  444. """Set callback for restart-recovery RUNNING-state observations (#1485
  445. follow-up). Fires the first time we see ``state == RUNNING`` for a
  446. printer that started its print before Bambuddy came up — the #1304
  447. guard suppresses ``on_print_start`` for these, so anything that
  448. normally hangs off it (e.g. timelapse baseline capture) needs this
  449. hook to recover."""
  450. self._on_print_running_observed = callback
  451. def set_finish_photo_moment_callback(self, callback: Callable[[int, dict], None]):
  452. """Set callback for the #1721 finish-photo moment.
  453. Fires on the stage-22 (\"Filament unloading\") edge at end-of-print
  454. — the framing window where the toolhead is parked but the bed
  455. hasn't dropped yet. Falls back to firing at the FINISH-state
  456. transition for prints that skip stage 22 (cancel, external-spool-
  457. only, HMS halt, firmware variants). Payload includes the
  458. ``trigger`` key (``\"stage_22\"`` or ``\"finish_state\"``) and
  459. ``timelapse_was_active`` so the photo path can choose between
  460. live-camera capture and timelapse last-frame extraction."""
  461. self._on_finish_photo_moment = callback
  462. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  463. """Set callback for status change events."""
  464. self._on_status_change = callback
  465. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  466. """Set callback for AMS data change events."""
  467. self._on_ams_change = callback
  468. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  469. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  470. self._on_layer_change = callback
  471. def set_print_progress_callback(self, callback: Callable[[int, int], None]):
  472. """Set callback for print-progress advances (#2547).
  473. Receives (printer_id, percent) each time `mc_percent` increases during a
  474. running print — including the final layer, where layer-change events
  475. have already stopped.
  476. """
  477. self._on_print_progress = callback
  478. def set_bed_temp_update_callback(self, callback: Callable[[int, float], None]):
  479. """Set callback for bed temperature updates. Receives (printer_id, bed_temp)."""
  480. self._on_bed_temp_update = callback
  481. def set_drying_complete_callback(self, callback: Callable[[int, int], None]):
  482. """Set callback for AMS drying completion events (#1349).
  483. Receives ``(printer_id, ams_id)``. Fires once per falling edge of
  484. ``dry_time`` (>0 → 0) for each AMS unit.
  485. """
  486. self._on_drying_complete = callback
  487. def set_assignment_verified_callback(self, callback: Callable[[int, int, int, bool, dict], None]):
  488. """Set callback for spool-assignment read-back verification (#2582).
  489. Receives ``(printer_id, ams_id, tray_id, verified, detail)``. Fires once
  490. per assignment either when the tray telemetry confirms the pushed
  491. filament id or when the verification window elapses without it.
  492. """
  493. self._on_assignment_verified = callback
  494. def _schedule_async(self, coro):
  495. """Schedule an async coroutine from a sync context.
  496. Captures exceptions from the coroutine and logs them to prevent
  497. silent failures in callbacks.
  498. """
  499. if self._loop and self._loop.is_running():
  500. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  501. def handle_exception(f):
  502. try:
  503. # This will re-raise any exception from the coroutine
  504. f.result()
  505. except Exception as e:
  506. import logging
  507. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  508. future.add_done_callback(handle_exception)
  509. async def connect_printer(self, printer: Printer) -> bool:
  510. """Connect to a printer."""
  511. if printer.id in self._clients:
  512. self.disconnect_printer(printer.id)
  513. printer_id = printer.id
  514. def on_state_change(state: PrinterState):
  515. if self._on_status_change:
  516. self._schedule_async(self._on_status_change(printer_id, state))
  517. def on_print_start(data: dict):
  518. if self._on_print_start:
  519. self._schedule_async(self._on_print_start(printer_id, data))
  520. def on_print_complete(data: dict):
  521. if self._on_print_complete:
  522. self._schedule_async(self._on_print_complete(printer_id, data))
  523. def on_print_running_observed(data: dict):
  524. if self._on_print_running_observed:
  525. self._schedule_async(self._on_print_running_observed(printer_id, data))
  526. def on_finish_photo_moment(data: dict):
  527. if self._on_finish_photo_moment:
  528. self._schedule_async(self._on_finish_photo_moment(printer_id, data))
  529. def on_ams_change(ams_data: list):
  530. if self._on_ams_change:
  531. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  532. def on_layer_change(layer_num: int):
  533. if self._on_layer_change:
  534. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  535. def on_print_progress(percent: int):
  536. if self._on_print_progress:
  537. self._schedule_async(self._on_print_progress(printer_id, percent))
  538. def on_bed_temp_update(bed_temp: float):
  539. if self._on_bed_temp_update:
  540. self._schedule_async(self._on_bed_temp_update(printer_id, bed_temp))
  541. def on_drying_complete(ams_id: int):
  542. if self._on_drying_complete:
  543. self._schedule_async(self._on_drying_complete(printer_id, ams_id))
  544. def on_assignment_verified(ams_id: int, tray_id: int, verified: bool, detail: dict):
  545. if self._on_assignment_verified:
  546. self._schedule_async(self._on_assignment_verified(printer_id, ams_id, tray_id, verified, detail))
  547. client = BambuMQTTClient(
  548. ip_address=printer.ip_address,
  549. serial_number=printer.serial_number,
  550. access_code=printer.access_code,
  551. model=printer.model,
  552. on_state_change=on_state_change,
  553. on_print_start=on_print_start,
  554. on_print_complete=on_print_complete,
  555. on_ams_change=on_ams_change,
  556. on_layer_change=on_layer_change,
  557. on_print_progress=on_print_progress,
  558. on_bed_temp_update=on_bed_temp_update,
  559. on_drying_complete=on_drying_complete,
  560. on_print_running_observed=on_print_running_observed,
  561. on_finish_photo_moment=on_finish_photo_moment,
  562. on_assignment_verified=on_assignment_verified,
  563. )
  564. client.connect()
  565. self._clients[printer_id] = client
  566. self._models[printer_id] = printer.model # Cache model for feature detection
  567. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  568. # Wait a moment for connection
  569. await asyncio.sleep(1)
  570. return client.state.connected
  571. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  572. """Disconnect from a printer."""
  573. if printer_id in self._clients:
  574. self._clients[printer_id].disconnect(timeout=timeout)
  575. del self._clients[printer_id]
  576. self._models.pop(printer_id, None) # Clean up model cache
  577. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  578. def disconnect_all(self, timeout: float = 0):
  579. """Disconnect from all printers."""
  580. for printer_id in list(self._clients.keys()):
  581. self.disconnect_printer(printer_id, timeout=timeout)
  582. def get_status(self, printer_id: int) -> PrinterState | None:
  583. """Get the current status of a printer (checks for stale connections)."""
  584. if printer_id in self._clients:
  585. client = self._clients[printer_id]
  586. # Check staleness and update connected state if needed
  587. client.check_staleness()
  588. return client.state
  589. return None
  590. # Gcode states in which a job is loaded / in progress and cutting power
  591. # would ruin the print. PAUSE is included on purpose — a paused print is
  592. # still loaded on the bed. Used by the smart-plug auto-off guard (#1890) so
  593. # a re-print started from the touchscreen isn't killed mid-print.
  594. ACTIVE_PRINT_STATES = ("RUNNING", "PAUSE", "PREPARE", "SLICING")
  595. def is_print_active(self, printer_id: int) -> bool:
  596. """True when the printer currently has a print loaded / in progress.
  597. Returns False when disconnected or in any idle/terminal state
  598. (IDLE / FINISH / FAILED / unknown), so callers fail *open* only for
  599. the safe "nothing is printing" case. #1890.
  600. """
  601. state = self.get_status(printer_id)
  602. if not state or not state.connected:
  603. return False
  604. return state.state in self.ACTIVE_PRINT_STATES
  605. def get_model(self, printer_id: int) -> str | None:
  606. """Get the cached model for a printer."""
  607. return self._models.get(printer_id)
  608. def get_drying_targets(self, printer_id: int) -> dict[int, dict] | None:
  609. """Get cached active drying target params keyed by AMS id.
  610. Returned dict shape: ``{ams_id: {"filament": str, "temp": int}}``.
  611. Returns ``None`` when the printer is not connected. The cache is
  612. seeded by ``send_drying_command(mode=1)`` and cleared when drying
  613. stops or on the ``dry_time`` falling edge (handled inside
  614. ``BambuMQTTClient``).
  615. """
  616. client = self._clients.get(printer_id)
  617. return client._drying_targets if client else None
  618. def get_all_statuses(self) -> dict[int, PrinterState]:
  619. """Get status of all connected printers (checks for stale connections)."""
  620. result = {}
  621. for printer_id, client in self._clients.items():
  622. # Check staleness and update connected state if needed
  623. client.check_staleness()
  624. result[printer_id] = client.state
  625. return result
  626. def is_connected(self, printer_id: int) -> bool:
  627. """Check if a printer is connected (checks for stale connections)."""
  628. if printer_id in self._clients:
  629. client = self._clients[printer_id]
  630. # Check staleness and update connected state if needed
  631. return client.check_staleness()
  632. return False
  633. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  634. """Get the MQTT client for a printer."""
  635. return self._clients.get(printer_id)
  636. def mark_printer_offline(self, printer_id: int):
  637. """Mark a printer as offline and trigger status callback.
  638. This is used when we know the printer power was cut (e.g., smart plug turned off)
  639. to immediately update the UI without waiting for MQTT timeout.
  640. The mark is a presumption, not a fact: the plug may not actually feed
  641. the printer. ``BambuMQTTClient.mark_power_off`` records the state it
  642. overwrites so the client can undo it as soon as the printer sends
  643. another report (#2629).
  644. """
  645. import logging
  646. logger = logging.getLogger(__name__)
  647. if printer_id in self._clients:
  648. client = self._clients[printer_id]
  649. if client.mark_power_off():
  650. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  651. # Trigger the status change callback to broadcast via WebSocket
  652. if self._on_status_change:
  653. self._schedule_async(self._on_status_change(printer_id, client.state))
  654. def start_print(
  655. self,
  656. printer_id: int,
  657. filename: str,
  658. plate_id: int = 1,
  659. ams_mapping: list[int] | None = None,
  660. bed_levelling: str = "auto",
  661. flow_cali: str = "auto",
  662. vibration_cali: bool = True,
  663. layer_inspect: bool = False,
  664. timelapse: bool = False,
  665. use_ams: bool = True,
  666. nozzle_offset_cali: str = "auto",
  667. nozzle_mapping: str | None = None,
  668. ) -> bool:
  669. """Start a print on a connected printer.
  670. ``nozzle_mapping`` is an opaque JSON string captured from BambuStudio's
  671. project_file MQTT command (H2C rack-swap slicer pick preservation,
  672. #1780). It rides through to the MQTT client untouched; the dispatch
  673. builder there parses + injects it only on dual-nozzle models.
  674. """
  675. caller = traceback.extract_stack(limit=3)[0]
  676. logger.info(
  677. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  678. printer_id,
  679. filename,
  680. caller.filename.split("/")[-1],
  681. caller.lineno,
  682. caller.name,
  683. )
  684. if printer_id in self._clients:
  685. return self._clients[printer_id].start_print(
  686. filename,
  687. plate_id,
  688. ams_mapping=ams_mapping,
  689. timelapse=timelapse,
  690. bed_levelling=bed_levelling,
  691. flow_cali=flow_cali,
  692. vibration_cali=vibration_cali,
  693. layer_inspect=layer_inspect,
  694. use_ams=use_ams,
  695. nozzle_offset_cali=nozzle_offset_cali,
  696. nozzle_mapping=nozzle_mapping,
  697. )
  698. return False
  699. def stop_print(self, printer_id: int) -> bool:
  700. """Stop the current print on a connected printer."""
  701. if printer_id in self._clients:
  702. return self._clients[printer_id].stop_print()
  703. return False
  704. async def wait_for_cooldown(
  705. self,
  706. printer_id: int,
  707. target_temp: float = 50.0,
  708. timeout: int = 600,
  709. check_interval: int = 10,
  710. ) -> bool:
  711. """Wait for the nozzle to cool down to a safe temperature.
  712. Args:
  713. printer_id: The printer to monitor
  714. target_temp: Target temperature to wait for (default 50°C)
  715. timeout: Maximum seconds to wait (default 600s = 10 min)
  716. check_interval: Seconds between temperature checks (default 10s)
  717. Returns:
  718. True if cooled down, False if timeout or not connected
  719. """
  720. import logging
  721. logger = logging.getLogger(__name__)
  722. elapsed = 0
  723. while elapsed < timeout:
  724. state = self.get_status(printer_id)
  725. if not state or not state.connected:
  726. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  727. return False
  728. # Check nozzle temperature (and nozzle_2 for dual extruders)
  729. nozzle_temp = state.temperatures.get("nozzle", 0)
  730. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  731. max_temp = max(nozzle_temp, nozzle_2_temp)
  732. if max_temp <= target_temp:
  733. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  734. return True
  735. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  736. await asyncio.sleep(check_interval)
  737. elapsed += check_interval
  738. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  739. return False
  740. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  741. """Enable or disable MQTT logging for a printer."""
  742. if printer_id in self._clients:
  743. self._clients[printer_id].enable_logging(enabled)
  744. return True
  745. return False
  746. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  747. """Get MQTT logs for a printer."""
  748. if printer_id in self._clients:
  749. return self._clients[printer_id].get_logs()
  750. return []
  751. def clear_logs(self, printer_id: int) -> bool:
  752. """Clear MQTT logs for a printer."""
  753. if printer_id in self._clients:
  754. self._clients[printer_id].clear_logs()
  755. return True
  756. return False
  757. def is_logging_enabled(self, printer_id: int) -> bool:
  758. """Check if logging is enabled for a printer."""
  759. if printer_id in self._clients:
  760. return self._clients[printer_id].logging_enabled
  761. return False
  762. def send_drying_command(
  763. self,
  764. printer_id: int,
  765. ams_id: int,
  766. temp: int,
  767. duration: int,
  768. mode: int = 1,
  769. filament: str = "",
  770. rotate_tray: bool = False,
  771. ) -> bool:
  772. """Send AMS drying command to printer."""
  773. if printer_id not in self._clients:
  774. return False
  775. return self._clients[printer_id].send_drying_command(ams_id, temp, duration, mode, filament, rotate_tray)
  776. def request_status_update(self, printer_id: int) -> bool:
  777. """Request a full status update from the printer.
  778. This sends a 'pushall' command to get the latest data including nozzle info.
  779. """
  780. if printer_id in self._clients:
  781. return self._clients[printer_id].request_status_update()
  782. return False
  783. # Probe budget for test_connection (#1445). Was a fixed 2s sleep, which was
  784. # too short for P1S firmware whose broker / TLS handshake routinely takes
  785. # 3–5s to surface a CONNACK on a cold MQTT session. We now poll up to
  786. # PROBE_TIMEOUT_SECONDS and early-return the moment we see connected=True,
  787. # so happy-path connections still finish in ~1–2s and slow brokers get the
  788. # headroom they need instead of getting falsely rejected.
  789. PROBE_TIMEOUT_SECONDS = 8.0
  790. PROBE_POLL_INTERVAL_SECONDS = 0.2
  791. async def test_connection(
  792. self,
  793. ip_address: str,
  794. serial_number: str,
  795. access_code: str,
  796. ) -> dict:
  797. """Test connection to a printer without persisting.
  798. Polls for up to PROBE_TIMEOUT_SECONDS and tears the probe client down
  799. off-loop. The teardown matters: `client.disconnect()` ends in paho's
  800. `loop_stop()` which `join()`s the network thread — if the thread is
  801. still mid-TLS-handshake to a slow printer, that join blocks the
  802. asyncio event loop and every other HTTP request queues behind it. The
  803. original synchronous teardown produced the #1445 "Docker container
  804. hangs" symptom on P1S when called from POST /printers/.
  805. """
  806. client = BambuMQTTClient(
  807. ip_address=ip_address,
  808. serial_number=serial_number,
  809. access_code=access_code,
  810. )
  811. try:
  812. client.connect()
  813. deadline = asyncio.get_running_loop().time() + self.PROBE_TIMEOUT_SECONDS
  814. while not client.state.connected and asyncio.get_running_loop().time() < deadline:
  815. await asyncio.sleep(self.PROBE_POLL_INTERVAL_SECONDS)
  816. result = {
  817. "success": client.state.connected,
  818. "state": client.state.state if client.state.connected else None,
  819. "model": client.state.raw_data.get("device_model"),
  820. # Why the probe failed, when the printer told us: one of the
  821. # CONNECT_ERROR_* slugs, else None. Lets the add-printer flow
  822. # and the connection diagnostic say "the printer rejected the
  823. # access code" instead of an unqualified failure (#2698).
  824. "reason": None if client.state.connected else client.last_connect_error,
  825. }
  826. finally:
  827. # Off-loop teardown — see docstring. paho's loop_stop() joins the
  828. # network thread which may still be in a slow TLS handshake.
  829. await asyncio.to_thread(client.disconnect)
  830. return result
  831. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  832. """
  833. Compute a human-readable status name based on printer state.
  834. Uses stg_cur when available, otherwise derives status from temperature data
  835. when the printer is heating before a print starts.
  836. Args:
  837. state: The printer state to analyze
  838. model: Optional printer model for model-specific workarounds
  839. """
  840. # Firmware bug: some models (A1, P1P, P1S) report stg_cur=0 when not printing.
  841. # stg_cur=0 maps to "Printing" in STAGE_NAMES, which incorrectly overrides the
  842. # real state (IDLE, FINISH, FAILED, etc.). Only trust stg_cur when the printer
  843. # is actually in an active print state (RUNNING or PAUSE).
  844. if state.state not in ("RUNNING", "PAUSE") and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  845. return None
  846. # If we have a valid calibration stage, use it
  847. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  848. # Valid stage numbers are 0-254
  849. if 0 <= state.stg_cur < 255:
  850. return get_stage_name(state.stg_cur)
  851. # If not in RUNNING state, no derived status needed
  852. if state.state != "RUNNING":
  853. return None
  854. # Check if we're in an early phase where temperatures are heating
  855. temps = state.temperatures or {}
  856. progress = state.progress or 0
  857. # Only derive heating status when progress is very low (< 2%)
  858. # This indicates we're in the preparation phase, not actually printing
  859. if progress >= 2:
  860. return None
  861. # Check bed temperature - if target is set and current is significantly below
  862. bed_temp = temps.get("bed", 0)
  863. bed_target = temps.get("bed_target", 0)
  864. # Check nozzle temperature
  865. nozzle_temp = temps.get("nozzle", 0)
  866. nozzle_target = temps.get("nozzle_target", 0)
  867. # Temperature thresholds: consider "heating" if more than 10°C below target
  868. TEMP_THRESHOLD = 10
  869. # Determine what's heating (prioritize bed since it takes longer)
  870. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  871. return "Heating heatbed"
  872. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  873. return "Heating nozzle"
  874. # If targets are set but we're close to them, we might be in final prep
  875. if bed_target > 30 or nozzle_target > 30:
  876. if progress == 0 and state.layer_num == 0:
  877. return "Preparing"
  878. return None
  879. _PLATE_ID_RE = re.compile(r"plate_(\d+)\.gcode")
  880. def parse_plate_id(gcode_file: str | None) -> int | None:
  881. """Extract the 1-indexed plate number from a Bambu gcode_file path.
  882. Returns None when the path is missing or has no `plate_N.gcode` segment.
  883. Shared by the REST status route and the WebSocket push path so both agree
  884. on the value sent to the frontend (#881 follow-up).
  885. """
  886. if not gcode_file:
  887. return None
  888. match = _PLATE_ID_RE.search(gcode_file)
  889. return int(match.group(1)) if match else None
  890. def resolve_plate_id(state) -> int | None:
  891. """Resolve the active plate number from a PrinterState.
  892. Some firmware versions (e.g. P1S 01.10.00.00, #1166) put only the .3mf
  893. filename in print.gcode_file, so parse_plate_id() returns None and the
  894. printer card falls back to plate 1 — wrong thumbnail. When Bambuddy
  895. dispatched the print itself we already know the right plate, so we prefer
  896. that over the gcode_file echo. The subtask check prevents stale values
  897. from a previous Bambuddy-dispatched print bleeding into a Studio-direct
  898. print on the same printer.
  899. """
  900. dispatched_plate = getattr(state, "dispatched_plate_id", None)
  901. dispatched_subtask = getattr(state, "dispatched_subtask", None)
  902. if (
  903. dispatched_plate is not None
  904. and dispatched_subtask is not None
  905. and state.subtask_name
  906. and dispatched_subtask == state.subtask_name
  907. ):
  908. return dispatched_plate
  909. return parse_plate_id(state.gcode_file)
  910. def resolve_expected_tray(
  911. raw_slot: int | None,
  912. ams_layout: list[tuple[int, bool]],
  913. mapping_raw: object,
  914. ) -> int | None:
  915. """Globalise a raw firmware ``tray_tar``/``tray_pre`` value for the runout UI (#2587).
  916. The firmware reports the target/previous slot as a bare number whose meaning
  917. depends on the AMS layout (see ``PrinterState.tray_tar``). This mirrors the
  918. ``tray_now`` handling so the resolved ID lines up with what the AMS graphic
  919. already highlights via ``ams_id*4 + slot``.
  920. ``ams_layout`` is a list of ``(ams_id, is_ams_ht)`` for the connected units.
  921. - ``255``/``-1`` (none/idle) -> ``None``
  922. - ``254`` (external spool) -> ``254``
  923. - ``128``-``135`` (AMS-HT) -> already global, returned as-is
  924. - ``0``-``3`` local slot:
  925. * exactly one regular AMS -> ``ams_id*4 + slot``
  926. * several regular AMS -> resolved via the snow-encoded ``mapping`` field
  927. (each entry = ``ams_hw_id*256 + slot``; ``65535`` = unmapped), or
  928. ``None`` when it stays ambiguous (honest "can't determine")
  929. * no regular AMS -> ``None``
  930. - ``4``-``15`` -> already a global regular-AMS ID, returned as-is
  931. Returns ``None`` for anything it can't place, so the caller surfaces a
  932. "check the printer" message instead of pointing at the wrong slot.
  933. """
  934. if raw_slot is None or raw_slot in (255, -1):
  935. return None
  936. if raw_slot == 254:
  937. return 254
  938. if 128 <= raw_slot <= 135:
  939. return raw_slot
  940. if 0 <= raw_slot <= 3:
  941. regular = [ams_id for ams_id, is_ht in ams_layout if not is_ht]
  942. if len(regular) == 1:
  943. return regular[0] * 4 + raw_slot
  944. if len(regular) > 1:
  945. if not isinstance(mapping_raw, list):
  946. return None
  947. candidates: set[int] = set()
  948. for value in mapping_raw:
  949. if not isinstance(value, int) or value >= 65535:
  950. continue
  951. ams_hw_id = value >> 8
  952. slot = value & 0xFF
  953. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == raw_slot:
  954. candidates.add(ams_hw_id * 4 + raw_slot)
  955. elif 128 <= ams_hw_id <= 135 and raw_slot == 0:
  956. candidates.add(ams_hw_id)
  957. return candidates.pop() if len(candidates) == 1 else None
  958. return None
  959. if 4 <= raw_slot <= 15:
  960. return raw_slot
  961. # 24-27 = A2L AMS-Lite (normalised unit 6) global tray ids, already resolved.
  962. if 24 <= raw_slot <= 27:
  963. return raw_slot
  964. return None
  965. def printer_state_to_dict(
  966. state: PrinterState,
  967. printer_id: int | None = None,
  968. model: str | None = None,
  969. drying_targets: dict[int, dict] | None = None,
  970. ) -> dict:
  971. """Convert PrinterState to a JSON-serializable dict.
  972. Args:
  973. state: The printer state to convert
  974. printer_id: Optional printer ID for generating cover URLs
  975. model: Optional printer model for filtering unsupported features
  976. drying_targets: Optional per-AMS active-cycle params
  977. (``{ams_id: {"filament": str, "temp": int}}``) sourced from the
  978. BambuMQTTClient cache so the badge can display "PETG @ 65°C".
  979. """
  980. # Parse AMS data from raw_data
  981. ams_units = []
  982. vt_tray = []
  983. raw_data = state.raw_data or {}
  984. # Build K-profile lookup map: cali_idx -> k_value
  985. kprofile_map: dict[int, float] = {}
  986. for kp in state.kprofiles or []:
  987. if kp.slot_id is not None and kp.k_value:
  988. try:
  989. kprofile_map[kp.slot_id] = float(kp.k_value)
  990. except (ValueError, TypeError):
  991. pass # Skip K-profile entries with unparseable values
  992. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  993. for ams_data in raw_data["ams"]:
  994. trays = []
  995. for tray in ams_data.get("tray", []):
  996. tag_uid = tray.get("tag_uid")
  997. if tag_uid in ("", "0000000000000000"):
  998. tag_uid = None
  999. tray_uuid = tray.get("tray_uuid")
  1000. if tray_uuid in ("", "00000000000000000000000000000000"):
  1001. tray_uuid = None
  1002. # Get K value: first try tray's k field, then lookup from K-profiles
  1003. k_value = tray.get("k")
  1004. cali_idx = tray.get("cali_idx")
  1005. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  1006. k_value = kprofile_map[cali_idx]
  1007. # P1S / A1 Mini physically-empty-slot signal (#1322 follow-up by
  1008. # @RosdasHH): for a truly empty slot the firmware sends only
  1009. # {"id": N} — no state, no tray_type, no anything else. Treat
  1010. # that as the firmware's "no spool" indicator (state=9) so the
  1011. # assign-spool path in inventory.py can short-circuit a MQTT
  1012. # publish the firmware would silently drop anyway. The
  1013. # post-"Reset Slot" A1 Mini BMCU case sends a populated payload
  1014. # (state=3, tray_type="") — different shape, doesn't match this
  1015. # guard, still attempts the MQTT push per the #1322 fix.
  1016. state_val = tray.get("state")
  1017. if state_val is None and len(tray) == 1 and "id" in tray:
  1018. state_val = 9
  1019. trays.append(
  1020. {
  1021. "id": int(tray.get("id", 0)),
  1022. "tray_color": tray.get("tray_color"),
  1023. "tray_type": tray.get("tray_type"),
  1024. "tray_sub_brands": tray.get("tray_sub_brands"),
  1025. "tray_id_name": tray.get("tray_id_name"),
  1026. "tray_info_idx": tray.get("tray_info_idx"),
  1027. "remain": tray.get("remain", 0),
  1028. "k": k_value,
  1029. "cali_idx": cali_idx,
  1030. "tag_uid": tag_uid,
  1031. "tray_uuid": tray_uuid,
  1032. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  1033. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  1034. "drying_temp": tray.get("drying_temp"),
  1035. "drying_time": tray.get("drying_time"),
  1036. "state": state_val,
  1037. # Firmware's authoritative presence bit (tray_exist_bits),
  1038. # set by apply_tray_exist_bits. The REST serializer already
  1039. # emits it (routes/printers.py); without it here the WS
  1040. # shallow-merge drops `exists` after the first frame and
  1041. # getEmptySlotKind falls back to the firmware-variant state
  1042. # 9/10 heuristic — wrong for AMS-HT in both directions (#2670).
  1043. "exists": tray.get("exists"),
  1044. }
  1045. )
  1046. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  1047. humidity_raw = ams_data.get("humidity_raw")
  1048. humidity_idx = ams_data.get("humidity")
  1049. humidity_value = None
  1050. if humidity_raw is not None:
  1051. try:
  1052. humidity_value = int(humidity_raw)
  1053. except (ValueError, TypeError):
  1054. pass # Skip unparseable humidity; will try index fallback
  1055. # Fall back to index if no raw value (index is 1-5, not percentage)
  1056. if humidity_value is None and humidity_idx is not None:
  1057. try:
  1058. humidity_value = int(humidity_idx)
  1059. except (ValueError, TypeError):
  1060. pass # Skip unparseable humidity index; humidity remains None
  1061. # AMS-HT has 1 tray, regular AMS has 4 trays
  1062. is_ams_ht = len(trays) == 1
  1063. # Active-cycle filament + target temperature for the badge.
  1064. # Bambu does not echo the cycle's chosen filament/temp on the
  1065. # per-tick AMS push, so prefer the cached target from the last
  1066. # ``send_drying_command``. When we have no record (drying
  1067. # started in a previous backend lifetime, or the cache was
  1068. # never seeded), fall back to the first loaded tray's
  1069. # tray_type + RFID-recommended drying_temp — the same heuristic
  1070. # the popover already uses to seed defaults.
  1071. ams_id_int = int(ams_data.get("id", 0))
  1072. target = (drying_targets or {}).get(ams_id_int)
  1073. dry_target_temp: int | None = None
  1074. dry_filament: str | None = None
  1075. if target:
  1076. temp_val = target.get("temp")
  1077. fil_val = target.get("filament") or ""
  1078. if temp_val is not None:
  1079. try:
  1080. dry_target_temp = int(temp_val)
  1081. except (TypeError, ValueError):
  1082. dry_target_temp = None
  1083. if fil_val:
  1084. dry_filament = str(fil_val)
  1085. if dry_target_temp is None or not dry_filament:
  1086. for tray in trays:
  1087. if tray.get("tray_type"):
  1088. if not dry_filament:
  1089. dry_filament = str(tray["tray_type"])
  1090. if dry_target_temp is None and tray.get("drying_temp"):
  1091. try:
  1092. dry_target_temp = int(tray["drying_temp"])
  1093. except (TypeError, ValueError):
  1094. pass
  1095. break
  1096. ams_units.append(
  1097. {
  1098. "id": ams_id_int,
  1099. "humidity": humidity_value,
  1100. "temp": ams_data.get("temp"),
  1101. "is_ams_ht": is_ams_ht,
  1102. "tray": trays,
  1103. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  1104. "serial_number": str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  1105. # Firmware version: populated by _handle_version_info from get_version
  1106. "sw_ver": str(ams_data.get("sw_ver") or ""),
  1107. # Drying: dry_time > 0 means drying is active (minutes remaining)
  1108. "dry_time": int(ams_data.get("dry_time") or 0),
  1109. # Drying status from info hex bits (0=Off, 1=Checking, 2=Drying, 3=Cooling, etc.)
  1110. "dry_status": int(ams_data.get("dry_status") or 0),
  1111. "dry_sub_status": int(ams_data.get("dry_sub_status") or 0),
  1112. # Cannot-dry reasons from firmware (e.g. 1=InsufficientPower, 8=NeedPluginPower)
  1113. "dry_sf_reason": list(ams_data.get("dry_sf_reason") or []),
  1114. # Active-cycle filament name + target temperature
  1115. "dry_target_temp": dry_target_temp,
  1116. "dry_filament": dry_filament,
  1117. # Module type: "ams", "n3f", "n3s" (from get_version)
  1118. "module_type": str(ams_data.get("module_type") or ""),
  1119. }
  1120. )
  1121. # Parse virtual tray (external spool) — now a list
  1122. if "vt_tray" in raw_data:
  1123. vt_tray_raw = raw_data["vt_tray"]
  1124. # Defensive: MQTT sends vt_tray as a dict; normalize to list
  1125. if isinstance(vt_tray_raw, dict):
  1126. vt_tray_raw = [vt_tray_raw]
  1127. elif not isinstance(vt_tray_raw, list):
  1128. vt_tray_raw = []
  1129. for vt_data in vt_tray_raw:
  1130. vt_tag_uid = vt_data.get("tag_uid")
  1131. if vt_tag_uid in ("", "0000000000000000"):
  1132. vt_tag_uid = None
  1133. vt_tray_uuid = vt_data.get("tray_uuid")
  1134. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  1135. vt_tray_uuid = None
  1136. # Get K value for vt_tray
  1137. vt_k_value = vt_data.get("k")
  1138. vt_cali_idx = vt_data.get("cali_idx")
  1139. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  1140. vt_k_value = kprofile_map[vt_cali_idx]
  1141. tray_id = int(vt_data.get("id", 254))
  1142. vt_tray.append(
  1143. {
  1144. "id": tray_id,
  1145. "tray_color": vt_data.get("tray_color"),
  1146. "tray_type": vt_data.get("tray_type"),
  1147. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  1148. "tray_id_name": vt_data.get("tray_id_name"),
  1149. "tray_info_idx": vt_data.get("tray_info_idx"),
  1150. "remain": vt_data.get("remain", 0),
  1151. "k": vt_k_value,
  1152. "cali_idx": vt_cali_idx,
  1153. "tag_uid": vt_tag_uid,
  1154. "tray_uuid": vt_tray_uuid,
  1155. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  1156. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  1157. }
  1158. )
  1159. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  1160. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  1161. # Filter out chamber temp for models that don't have a real sensor
  1162. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  1163. temperatures = state.temperatures
  1164. if not supports_chamber_temp(model):
  1165. temperatures = {
  1166. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  1167. }
  1168. result = {
  1169. "connected": state.connected,
  1170. "state": state.state,
  1171. "current_print": state.current_print,
  1172. "subtask_name": state.subtask_name,
  1173. "gcode_file": state.gcode_file,
  1174. "progress": state.progress,
  1175. "remaining_time": state.remaining_time,
  1176. "layer_num": state.layer_num,
  1177. "total_layers": state.total_layers,
  1178. "temperatures": temperatures,
  1179. "hms_errors": [
  1180. {
  1181. "code": e.code,
  1182. "attr": e.attr,
  1183. "module": e.module,
  1184. "severity": e.severity,
  1185. "actions": e.actions,
  1186. "job_id": e.job_id,
  1187. "full_code": e.full_code,
  1188. }
  1189. for e in (state.hms_errors or [])
  1190. ],
  1191. # AMS data for filament colors
  1192. "ams": ams_units if ams_units else None,
  1193. "vt_tray": vt_tray,
  1194. # AMS status for filament change tracking
  1195. "ams_status_main": state.ams_status_main,
  1196. "ams_status_sub": state.ams_status_sub,
  1197. "tray_now": state.tray_now,
  1198. # Runout / filament-replacement guidance (#2587). Only meaningful while
  1199. # PAUSED — resolve the firmware's target/previous slot to a global tray ID
  1200. # so the AMS graphic can highlight the slot the print now expects and name
  1201. # the one that ran out. None when idle, not paused, or unresolvable.
  1202. "expected_tray": (
  1203. resolve_expected_tray(
  1204. state.tray_tar,
  1205. [(u["id"], u.get("is_ams_ht", False)) for u in ams_units],
  1206. raw_data.get("mapping"),
  1207. )
  1208. if state.state == "PAUSE"
  1209. else None
  1210. ),
  1211. "previous_tray": (
  1212. resolve_expected_tray(
  1213. state.tray_pre,
  1214. [(u["id"], u.get("is_ams_ht", False)) for u in ams_units],
  1215. raw_data.get("mapping"),
  1216. )
  1217. if state.state == "PAUSE"
  1218. else None
  1219. ),
  1220. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  1221. "ams_extruder_map": ams_extruder_map,
  1222. # WiFi signal strength
  1223. "wifi_signal": state.wifi_signal,
  1224. "wired_network": state.wired_network,
  1225. "door_open": state.door_open,
  1226. # AMS Filament Backup state (auto-switch to second spool). Tri-state:
  1227. # True / False / None. None = unknown or unsupported (A1 family). UI
  1228. # uses this to drive the small status icon next to the AMS drying icon.
  1229. "ams_filament_backup": state.ams_filament_backup,
  1230. # Calibration stage tracking
  1231. "stg_cur": state.stg_cur,
  1232. "stg_cur_name": get_derived_status_name(state, model),
  1233. # Printable objects count for skip objects feature
  1234. "printable_objects_count": len(state.printable_objects),
  1235. # Fan speeds (0-100 percentage, None if not available)
  1236. "cooling_fan_speed": state.cooling_fan_speed,
  1237. "big_fan1_speed": state.big_fan1_speed,
  1238. "big_fan2_speed": state.big_fan2_speed,
  1239. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  1240. "left_aux_fan_speed": state.left_aux_fan_speed,
  1241. "exhaust_fan_present": state.exhaust_fan_present,
  1242. # Chamber light state
  1243. "chamber_light": state.chamber_light,
  1244. # Active extruder for dual-nozzle printers (0=right, 1=left)
  1245. "active_extruder": state.active_extruder,
  1246. # Print speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1247. "speed_level": state.speed_level,
  1248. # H2C nozzle rack (tool-changer dock positions)
  1249. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  1250. "nozzle_rack": [
  1251. {
  1252. "id": n.get("id", 0),
  1253. "nozzle_type": n.get("type", ""),
  1254. "nozzle_diameter": n.get("diameter", ""),
  1255. "wear": n.get("wear"),
  1256. "stat": n.get("stat"),
  1257. "max_temp": n.get("max_temp", 0),
  1258. "serial_number": n.get("serial_number", ""),
  1259. "filament_color": n.get("filament_color", ""),
  1260. "filament_id": n.get("filament_id", ""),
  1261. }
  1262. for n in (state.nozzle_rack or [])
  1263. ],
  1264. # AMS drying support
  1265. "supports_drying": supports_drying(model, state.firmware_version),
  1266. "supports_drying_while_printing": supports_drying_while_printing(model, state.firmware_version),
  1267. "drying_screen_only": drying_screen_only(model),
  1268. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  1269. # Pushed via WebSocket so the printer card picks up plate transitions within
  1270. # a multi-plate 3MF without waiting for the 30 s REST poll (#881 follow-up).
  1271. # current_archive_id is intentionally REST-only — it's stable for the life
  1272. # of a print and needs a DB lookup the WebSocket path shouldn't pay for.
  1273. "current_plate_id": resolve_plate_id(state),
  1274. # Plate-clear gate (#939). Lives on the PrinterManager rather than PrinterState,
  1275. # so surface it here — without this, WebSocket merges drop the flag and the
  1276. # "Clear Plate" button only appears when the 30 s REST fallback poll runs.
  1277. "awaiting_plate_clear": printer_manager.is_awaiting_plate_clear(printer_id) if printer_id else False,
  1278. }
  1279. # Add cover URL if there's an active print and printer_id is provided
  1280. # Include PAUSE state so skip objects modal can show cover
  1281. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  1282. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  1283. else:
  1284. result["cover_url"] = None
  1285. # Surface the display name + model so WS consumers (gcode viewer printer
  1286. # selector) can render proper labels on the initial snapshot without racing
  1287. # a separate /api/v1/printers fetch (#963 follow-up). PrinterInfo only
  1288. # carries name/serial_number; the model comes through via the `model` arg.
  1289. if printer_id:
  1290. _printer_info = printer_manager.get_printer(printer_id)
  1291. if _printer_info is not None:
  1292. result["name"] = _printer_info.name
  1293. if model:
  1294. result["model"] = model
  1295. return result
  1296. # Global printer manager instance
  1297. printer_manager = PrinterManager()
  1298. async def init_printer_connections(db: AsyncSession):
  1299. """Initialize connections to all active printers.
  1300. Connections are started concurrently. ``connect_printer()`` is non-blocking
  1301. apart from a fixed 1-second settle wait — ``BambuMQTTClient.connect()`` only
  1302. calls ``connect_async()`` + ``loop_start()``, so the handshake happens on a
  1303. background thread and the coroutine's only real cost is that ``sleep(1)``. A
  1304. serial loop therefore spent one whole second per printer inside the FastAPI
  1305. lifespan *before* the ASGI server begins serving: on a large farm that was
  1306. ~100s of dead air before port 8000 responded (issue #2572, reporter's
  1307. 93-printer farm). Gathering overlaps the settle waits so the whole step takes
  1308. ~1s regardless of fleet size. Exceptions are isolated per printer with
  1309. ``return_exceptions=True`` so one unreachable row can't abort the rest — or
  1310. startup itself, which the old serial loop's un-caught await would have done.
  1311. All columns ``connect_printer`` reads are eagerly loaded by the SELECT above
  1312. and touched synchronously before its trailing ``await``, so no concurrent
  1313. lazy-load is triggered on the shared session.
  1314. """
  1315. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1316. printers = result.scalars().all()
  1317. outcomes = await asyncio.gather(
  1318. *(printer_manager.connect_printer(printer) for printer in printers),
  1319. return_exceptions=True,
  1320. )
  1321. for printer, outcome in zip(printers, outcomes, strict=True):
  1322. if isinstance(outcome, Exception):
  1323. logger.warning(
  1324. "Failed to connect printer %s (%s) at startup: %s",
  1325. printer.id,
  1326. printer.name,
  1327. outcome,
  1328. )