printer_manager.py 83 KB

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