printer_manager.py 86 KB

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