printer_manager.py 73 KB

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