printer_manager.py 77 KB

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