printer_manager.py 85 KB

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