printer_manager.py 82 KB

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