printer_manager.py 78 KB

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