printer_manager.py 87 KB

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