printer_manager.py 75 KB

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