printer_manager.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. import asyncio
  2. import logging
  3. import re
  4. import traceback
  5. from collections.abc import Callable
  6. from sqlalchemy import select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from backend.app.models.printer import Printer
  9. from backend.app.services.bambu_mqtt import BambuMQTTClient, MQTTLogEntry, PrinterState, get_stage_name
  10. logger = logging.getLogger(__name__)
  11. # Models that have a real chamber temperature sensor
  12. # Based on Home Assistant Bambu Lab integration
  13. # P1P/P1S and A1/A1Mini do NOT have chamber temp sensors
  14. # Includes both display names and internal codes from MQTT/SSDP
  15. CHAMBER_TEMP_SUPPORTED_MODELS = frozenset(
  16. [
  17. # Display names
  18. "X1",
  19. "X1C",
  20. "X1E", # X1 series
  21. "X2D", # X2 series
  22. "P2S", # P2 series
  23. "H2C",
  24. "H2D",
  25. "H2DPRO",
  26. "H2S", # H2 series
  27. # Internal codes (from MQTT/SSDP)
  28. "BL-P001", # X1/X1C
  29. "C13", # X1E
  30. "N6", # X2D
  31. "O1D", # H2D
  32. "O1C", # H2C
  33. "O1C2", # H2C (dual nozzle variant)
  34. "O1S", # H2S
  35. "O1E", # H2D Pro
  36. "O2D", # H2D Pro (alternate code)
  37. "N7", # P2S
  38. ]
  39. )
  40. # Models that may incorrectly report stg_cur=0 when idle (firmware bug)
  41. # Based on Home Assistant Bambu Lab integration observations
  42. # See: https://github.com/greghesp/ha-bambulab/blob/main/custom_components/bambu_lab/pybambu/models.py
  43. A1_MODELS = frozenset(
  44. [
  45. # Display names
  46. "A1",
  47. "A1 MINI",
  48. "A1-MINI",
  49. "A1MINI",
  50. # Internal codes (from MQTT/SSDP)
  51. "N1", # A1 Mini
  52. "N2S", # A1
  53. ]
  54. )
  55. # Models affected by the stg_cur=0 idle bug (firmware reports stg_cur=0 when idle,
  56. # which maps to "Printing" in STAGE_NAMES and overrides the correct IDLE state)
  57. STG_CUR_IDLE_BUG_MODELS = A1_MODELS | frozenset(
  58. [
  59. # Display names
  60. "P1P",
  61. "P1S",
  62. # Internal codes (from MQTT/SSDP)
  63. "C11", # P1P
  64. "C12", # P1S
  65. ]
  66. )
  67. def supports_chamber_temp(model: str | None) -> bool:
  68. """Check if a printer model has a real chamber temperature sensor.
  69. P1P, P1S, A1, and A1Mini do NOT have chamber temp sensors.
  70. The 'chamber_temper' value they report is meaningless.
  71. """
  72. if not model:
  73. return False
  74. # Normalize model name (uppercase, strip whitespace)
  75. model_upper = model.strip().upper()
  76. return model_upper in CHAMBER_TEMP_SUPPORTED_MODELS
  77. # Models with an ACTIVE chamber heater (M141 has an effect).
  78. # Many printers in CHAMBER_TEMP_SUPPORTED_MODELS only have a passive sensor —
  79. # X1C, X1E, P2S report chamber temperature but cannot actively heat it. Only
  80. # the models below ship a PTC heater that responds to M141.
  81. CHAMBER_HEATER_MODELS = frozenset(
  82. [
  83. # Display names
  84. "H2C",
  85. "H2D",
  86. "H2DPRO",
  87. "H2S",
  88. "X2D",
  89. # Internal codes (from MQTT/SSDP)
  90. "O1C", # H2C
  91. "O1C2", # H2C dual-nozzle variant
  92. "O1D", # H2D
  93. "O1E", # H2D Pro
  94. "O2D", # H2D Pro alternate code
  95. "O1S", # H2S
  96. "N6", # X2D
  97. ]
  98. )
  99. def supports_chamber_heater(model: str | None) -> bool:
  100. """Check if a printer model has an active chamber heater (responds to M141).
  101. The chamber temperature SENSOR is more widely deployed than the chamber
  102. HEATER — X1C/X1E/P2S report chamber temp but ignore M141. Only H2C, H2D,
  103. H2D Pro, H2S, X2D actually heat. Sensor-only models silently swallow the
  104. command at the firmware level, so we 400 at the route to surface that.
  105. """
  106. if not model:
  107. return False
  108. return model.strip().upper() in CHAMBER_HEATER_MODELS
  109. # Models with a cooling / heating airduct flap. Same set as the frontend
  110. # PrintersPage airduct-toggle whitelist (P2S, X2D, H2D, H2C, H2S, H2D Pro).
  111. # X1E has a chamber heater but NO airduct flap — the warm-air recirculation
  112. # happens via the fixed front-door inlet, so no `set_airduct` command is
  113. # needed (and the firmware ignores it). P2S has an airduct but no heater —
  114. # the flap manages chamber airflow even without an active heater. The
  115. # intersection (chamber heater AND airduct) is what the preheat stage cares
  116. # about: when M141 fires we also need to assert heating mode, otherwise the
  117. # default cooling mode actively fights the chamber heater.
  118. CHAMBER_AIRDUCT_MODELS = frozenset(
  119. [
  120. # Display names
  121. "P2S",
  122. "X2D",
  123. "H2C",
  124. "H2D",
  125. "H2DPRO",
  126. "H2S",
  127. # Internal codes (from MQTT/SSDP)
  128. "N7", # P2S
  129. "N6", # X2D
  130. "O1C", # H2C
  131. "O1C2", # H2C dual-nozzle variant
  132. "O1D", # H2D
  133. "O1E", # H2D Pro
  134. "O2D", # H2D Pro alternate code
  135. "O1S", # H2S
  136. ]
  137. )
  138. def supports_airduct(model: str | None) -> bool:
  139. """Check if a printer model has a cooling / heating airduct mode toggle.
  140. Mirrors the frontend PrintersPage `['P2S', 'X2D', 'H2D', 'H2C', 'H2S']`
  141. + H2D Pro whitelist. Distinct from `supports_chamber_heater` — P2S has
  142. the airduct toggle but no active heater, and X1E has the heater but no
  143. airduct. The preheat stage cares about the intersection (heater AND
  144. airduct) so it can flip the flap to heating before energising M141.
  145. """
  146. if not model:
  147. return False
  148. return model.strip().upper() in CHAMBER_AIRDUCT_MODELS
  149. def has_stg_cur_idle_bug(model: str | None) -> bool:
  150. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  151. Some firmware versions report stg_cur=0 (which maps to "Printing")
  152. even when the printer is idle. Originally observed on A1/A1 Mini via the
  153. Home Assistant Bambu Lab integration, also confirmed on P1S.
  154. """
  155. if not model:
  156. return False
  157. model_upper = model.strip().upper()
  158. return model_upper in STG_CUR_IDLE_BUG_MODELS
  159. def is_bed_slinger(model: str | None) -> bool:
  160. """Whether the printer's Z axis controls the *toolhead*, not the bed.
  161. Bambu's A1 family (A1, A1 Mini; internal codes N1 / N2S) are open-frame
  162. bed-slingers: the bed moves on Y, the toolhead moves on X+Z. On every
  163. other current model (X1, P1, H2, H2C, H2D, H2S, P2S, ...) the bed moves
  164. on Z and the toolhead is fixed in Z.
  165. G-code direction is opposite on these two families. `G1 Z-10` reduces
  166. the nozzle-bed gap on both, but on bed-on-Z machines it does so by
  167. moving the BED up, while on bed-slingers it does so by moving the
  168. TOOLHEAD down — which is what crashed the nozzle in #1334.
  169. """
  170. if not model:
  171. return False
  172. return model.strip().upper() in A1_MODELS
  173. # Minimum firmware versions for AMS drying support (confirmed via capture testing)
  174. # Keys are exact model names (upper-cased). Do NOT use substring matching — it would
  175. # incorrectly gate X1E (matched by "X1") and H2D Pro (matched by "H2D").
  176. _DRYING_MIN_FIRMWARE: dict[str, str] = {
  177. "H2D": "01.02.30.00",
  178. "H2S": "01.02.00.00",
  179. "H2C": "01.02.00.00",
  180. "O1C": "01.02.00.00", # H2C SSDP model code
  181. "O1C2": "01.02.00.00", # H2C dual-nozzle SSDP model code
  182. "X1": "01.09.00.00",
  183. "X1C": "01.09.00.00",
  184. "P2S": "01.02.00.00",
  185. "N7": "01.02.00.00", # P2S internal model code
  186. }
  187. # Models that definitely don't support AMS drying (no AMS 2 Pro / AMS-HT compatibility)
  188. _DRYING_UNSUPPORTED_MODELS = frozenset({"A1", "A1MINI", "A1-MINI", "A1 MINI", "O1S", "N1", "N2S"})
  189. # Models whose AMS can dry, but only from the printer's own touchscreen. Bambu's P1
  190. # manual is explicit: "P1S connected AMS drying functions may only be controlled from
  191. # the P1S screen." The firmware still answers `ams_filament_drying` with
  192. # result: success and then does nothing — the reporter of #2533 sent it three times
  193. # on an idle P1S with an AMS 2 Pro and the unit never left dry_status 0. Bambuddy
  194. # originally listed P1P/P1S here as fw-gated (01.08+, #292); that version is when P1
  195. # firmware gained AMS 2 Pro *support*, not remote drying, and it was never verified
  196. # against a live P1. Nothing we can send will start a cycle, so we don't offer to.
  197. _DRYING_SCREEN_ONLY_MODELS = frozenset({"P1P", "P1S"})
  198. def drying_screen_only(model: str | None) -> bool:
  199. """True when the model's AMS dries only via the printer's own screen (#2533).
  200. Distinct from "unsupported": these printers *can* dry, and Bambuddy still shows
  201. a cycle started on the printer. They just can't be commanded to start or stop
  202. one remotely, so the UI explains that instead of silently dropping the control.
  203. """
  204. if not model:
  205. return False
  206. return model.strip().upper() in _DRYING_SCREEN_ONLY_MODELS
  207. def supports_drying(model: str | None, firmware: str | None) -> bool:
  208. """Check if a printer model accepts remote AMS drying commands.
  209. Known models with confirmed min firmware get version-gated.
  210. Known unsupported models, and models that only dry from their own screen,
  211. are blocked.
  212. All other models (H2D Pro, X1E, future models) are allowed —
  213. the command fails gracefully with result: "fail" if unsupported.
  214. """
  215. if not model:
  216. return False
  217. model_upper = model.strip().upper()
  218. if model_upper in _DRYING_UNSUPPORTED_MODELS or model_upper in _DRYING_SCREEN_ONLY_MODELS:
  219. return False
  220. if model_upper in _DRYING_MIN_FIRMWARE:
  221. return bool(firmware and firmware >= _DRYING_MIN_FIRMWARE[model_upper])
  222. # For all other models: allow
  223. return True
  224. # Minimum firmware versions for AMS "Print While Drying" — drying that runs CONCURRENTLY
  225. # with an active print. Strictly stricter than _DRYING_MIN_FIRMWARE (idle drying). Verified
  226. # against Bambu wiki release notes — the canonical phrasing on every supported model is
  227. # "printing while filament is drying" / "Print While Drying". Models absent from the wiki
  228. # release notes (A1, A1 Mini, P1*, X1 non-C, X1E) are intentionally excluded — the firmware
  229. # will reject the command in those cases anyway via dry_sf_reason=[0] (TaskOccupied).
  230. _DRY_WHILE_PRINTING_MIN_FIRMWARE: dict[str, str] = {
  231. "H2D": "01.03.00.00",
  232. "H2D PRO": "01.02.00.00",
  233. "H2DPRO": "01.02.00.00",
  234. "O1E": "01.02.00.00", # H2D Pro SSDP code
  235. "O2D": "01.02.00.00", # H2D Pro alternate code
  236. "H2C": "01.02.00.00",
  237. "O1C": "01.02.00.00", # H2C SSDP code
  238. "O1C2": "01.02.00.00", # H2C dual-nozzle SSDP code
  239. "H2S": "01.02.00.00",
  240. "X2D": "01.01.00.00",
  241. "N6": "01.01.00.00", # X2D internal code
  242. "X1C": "01.11.02.00",
  243. "BL-P001": "01.11.02.00", # X1C internal code
  244. "P2S": "01.02.00.00",
  245. "N7": "01.02.00.00", # P2S internal code
  246. "A2L": "01.01.00.00",
  247. "N9": "01.01.00.00", # A2L internal code
  248. }
  249. def supports_drying_while_printing(model: str | None, firmware: str | None) -> bool:
  250. """Check if a printer model+firmware supports running AMS drying CONCURRENTLY
  251. with an active print.
  252. Distinct from supports_drying() — that gates idle drying. This gate is strict:
  253. only models explicitly confirmed by Bambu wiki release notes are allowed.
  254. On unsupported models the firmware returns dry_sf_reason=[0] (TaskOccupied)
  255. while a print is running, so being conservative here costs nothing — the
  256. firmware is the ultimate arbiter, this gate just hides UI affordances.
  257. """
  258. if not model:
  259. return False
  260. model_upper = model.strip().upper()
  261. if model_upper not in _DRY_WHILE_PRINTING_MIN_FIRMWARE:
  262. return False
  263. return bool(firmware and firmware >= _DRY_WHILE_PRINTING_MIN_FIRMWARE[model_upper])
  264. class PrinterInfo:
  265. """Basic printer info for callbacks."""
  266. def __init__(self, name: str, serial_number: str):
  267. self.name = name
  268. self.serial_number = serial_number
  269. class PrinterManager:
  270. """Manager for multiple printer connections."""
  271. def __init__(self):
  272. self._clients: dict[int, BambuMQTTClient] = {}
  273. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  274. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  275. self._on_print_start: Callable[[int, dict], None] | None = None
  276. self._on_print_complete: Callable[[int, dict], None] | None = None
  277. self._on_print_running_observed: Callable[[int, dict], None] | None = None
  278. self._on_finish_photo_moment: Callable[[int, dict], None] | None = None
  279. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  280. self._on_ams_change: Callable[[int, list], None] | None = None
  281. self._on_layer_change: Callable[[int, int], None] | None = None
  282. self._on_bed_temp_update: Callable[[int, float], None] | None = None
  283. self._on_drying_complete: Callable[[int, int], None] | None = None
  284. self._loop: asyncio.AbstractEventLoop | None = None
  285. # Track who started the current print (Issue #206)
  286. self._current_print_user: dict[int, dict] = {} # {printer_id: {"user_id": int, "username": str}}
  287. # Track printers awaiting plate-clear acknowledgment after a finished/failed print.
  288. # Persisted to DB (printers.awaiting_plate_clear) so the gate survives restarts/power
  289. # cycles — see issue #961. Loaded into this set at startup via load_awaiting_plate_clear_from_db().
  290. self._awaiting_plate_clear: set[int] = set()
  291. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  292. """Get printer info by ID."""
  293. return self._printer_info.get(printer_id)
  294. def set_current_print_user(self, printer_id: int, user_id: int, username: str):
  295. """Track who started the current print (Issue #206)."""
  296. self._current_print_user[printer_id] = {"user_id": user_id, "username": username}
  297. def get_current_print_user(self, printer_id: int) -> dict | None:
  298. """Get the user who started the current print (Issue #206)."""
  299. return self._current_print_user.get(printer_id)
  300. def clear_current_print_user(self, printer_id: int):
  301. """Clear the current print user when print completes (Issue #206)."""
  302. self._current_print_user.pop(printer_id, None)
  303. def is_awaiting_plate_clear(self, printer_id: int) -> bool:
  304. """Return True when the printer finished/failed a print and is waiting for the
  305. user to acknowledge the plate is cleared before the queue may dispatch the next job.
  306. """
  307. return printer_id in self._awaiting_plate_clear
  308. def set_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  309. """Set/clear the awaiting-plate-clear gate and persist it to DB.
  310. Persisted so the gate survives Bambuddy/printer restarts (#961): after Auto Off
  311. cycles the printer, the printer boots into IDLE with no memory of the previous
  312. finish, and without persistence the queue would bypass the confirmation prompt.
  313. Also broadcasts an updated ``printer_status`` over the WebSocket (#1128).
  314. ``awaiting_plate_clear`` is a Bambuddy-side flag — toggling it does not
  315. produce an MQTT push from the printer, so without an explicit broadcast
  316. any UI subscriber that's NOT the originating tab would stay stale until
  317. the next coincidental status refresh. The plate-clear button on the
  318. printer card disappeared "immediately" only because of an optimistic
  319. React Query cache update on the click path; clearing the flag through
  320. any other route (an admin script, a second tab, an automation that
  321. hits ``POST /printers/{id}/clear-plate`` directly) silently broke the
  322. UI without it. Centralised here so every current AND future caller is
  323. covered without each one having to remember to broadcast.
  324. """
  325. if awaiting:
  326. self._awaiting_plate_clear.add(printer_id)
  327. else:
  328. self._awaiting_plate_clear.discard(printer_id)
  329. # Only create the coroutine when there is a loop to run it on — otherwise Python
  330. # emits "coroutine was never awaited" warnings (e.g. in sync unit tests).
  331. if self._loop and self._loop.is_running():
  332. self._schedule_async(self._persist_awaiting_plate_clear(printer_id, awaiting))
  333. self._schedule_async(self._broadcast_status_change(printer_id))
  334. async def _broadcast_status_change(self, printer_id: int) -> None:
  335. """Emit a ``printer_status`` WebSocket update for this printer (#1128).
  336. Used for state changes that don't come from MQTT — currently just the
  337. ``awaiting_plate_clear`` flag, but any future Bambuddy-side flag added
  338. to ``printer_state_to_dict`` should plumb through here too. The
  339. existing MQTT-driven broadcast in ``main.on_printer_status_change``
  340. deduplicates on a status_key that intentionally excludes Bambuddy
  341. flags (so e.g. queue-state changes don't get echoed as printer
  342. events), which is precisely why those flags need their own emit.
  343. Lazy-imports ``ws_manager`` to keep ``printer_manager`` clean of
  344. application-layer infra at module-import time — the broadcast is the
  345. only thing here that needs it.
  346. """
  347. state = self.get_status(printer_id)
  348. if not state:
  349. # Printer disconnected or unknown — nothing to broadcast. The
  350. # next reconnect will produce a fresh status push anyway, so the
  351. # UI eventually catches up without us forcing a stale snapshot
  352. # on subscribers now.
  353. return
  354. try:
  355. from backend.app.core.websocket import ws_manager
  356. await ws_manager.send_printer_status(
  357. printer_id,
  358. printer_state_to_dict(
  359. state,
  360. printer_id,
  361. self.get_model(printer_id),
  362. self.get_drying_targets(printer_id),
  363. ),
  364. )
  365. except Exception as e:
  366. logger.warning(
  367. "Failed to broadcast printer_status after Bambuddy-side state change for printer %d: %s",
  368. printer_id,
  369. e,
  370. )
  371. async def _persist_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  372. from backend.app.core.database import run_with_retry
  373. async def _do(db):
  374. printer = await db.get(Printer, printer_id)
  375. if printer is not None:
  376. printer.awaiting_plate_clear = awaiting
  377. await db.commit()
  378. try:
  379. await run_with_retry(_do, label=f"persist awaiting_plate_clear printer={printer_id}")
  380. except Exception as e:
  381. logger.warning("Failed to persist awaiting_plate_clear for printer %d: %s", printer_id, e)
  382. async def load_awaiting_plate_clear_from_db(self):
  383. """Rehydrate the awaiting-plate-clear set from the printers table on startup."""
  384. from backend.app.core.database import async_session
  385. try:
  386. async with async_session() as db:
  387. result = await db.execute(select(Printer.id).where(Printer.awaiting_plate_clear.is_(True)))
  388. ids = {row[0] for row in result.all()}
  389. self._awaiting_plate_clear = ids
  390. if ids:
  391. logger.info("Loaded %d printer(s) awaiting plate-clear acknowledgment: %s", len(ids), sorted(ids))
  392. except Exception as e:
  393. logger.warning("Failed to load awaiting_plate_clear from DB: %s", e)
  394. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  395. """Set the event loop for async callbacks."""
  396. self._loop = loop
  397. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  398. """Set callback for print start events."""
  399. self._on_print_start = callback
  400. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  401. """Set callback for print completion events."""
  402. self._on_print_complete = callback
  403. def set_print_running_observed_callback(self, callback: Callable[[int, dict], None]):
  404. """Set callback for restart-recovery RUNNING-state observations (#1485
  405. follow-up). Fires the first time we see ``state == RUNNING`` for a
  406. printer that started its print before Bambuddy came up — the #1304
  407. guard suppresses ``on_print_start`` for these, so anything that
  408. normally hangs off it (e.g. timelapse baseline capture) needs this
  409. hook to recover."""
  410. self._on_print_running_observed = callback
  411. def set_finish_photo_moment_callback(self, callback: Callable[[int, dict], None]):
  412. """Set callback for the #1721 finish-photo moment.
  413. Fires on the stage-22 (\"Filament unloading\") edge at end-of-print
  414. — the framing window where the toolhead is parked but the bed
  415. hasn't dropped yet. Falls back to firing at the FINISH-state
  416. transition for prints that skip stage 22 (cancel, external-spool-
  417. only, HMS halt, firmware variants). Payload includes the
  418. ``trigger`` key (``\"stage_22\"`` or ``\"finish_state\"``) and
  419. ``timelapse_was_active`` so the photo path can choose between
  420. live-camera capture and timelapse last-frame extraction."""
  421. self._on_finish_photo_moment = callback
  422. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  423. """Set callback for status change events."""
  424. self._on_status_change = callback
  425. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  426. """Set callback for AMS data change events."""
  427. self._on_ams_change = callback
  428. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  429. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  430. self._on_layer_change = callback
  431. def set_bed_temp_update_callback(self, callback: Callable[[int, float], None]):
  432. """Set callback for bed temperature updates. Receives (printer_id, bed_temp)."""
  433. self._on_bed_temp_update = callback
  434. def set_drying_complete_callback(self, callback: Callable[[int, int], None]):
  435. """Set callback for AMS drying completion events (#1349).
  436. Receives ``(printer_id, ams_id)``. Fires once per falling edge of
  437. ``dry_time`` (>0 → 0) for each AMS unit.
  438. """
  439. self._on_drying_complete = callback
  440. def _schedule_async(self, coro):
  441. """Schedule an async coroutine from a sync context.
  442. Captures exceptions from the coroutine and logs them to prevent
  443. silent failures in callbacks.
  444. """
  445. if self._loop and self._loop.is_running():
  446. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  447. def handle_exception(f):
  448. try:
  449. # This will re-raise any exception from the coroutine
  450. f.result()
  451. except Exception as e:
  452. import logging
  453. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  454. future.add_done_callback(handle_exception)
  455. async def connect_printer(self, printer: Printer) -> bool:
  456. """Connect to a printer."""
  457. if printer.id in self._clients:
  458. self.disconnect_printer(printer.id)
  459. printer_id = printer.id
  460. def on_state_change(state: PrinterState):
  461. if self._on_status_change:
  462. self._schedule_async(self._on_status_change(printer_id, state))
  463. def on_print_start(data: dict):
  464. if self._on_print_start:
  465. self._schedule_async(self._on_print_start(printer_id, data))
  466. def on_print_complete(data: dict):
  467. if self._on_print_complete:
  468. self._schedule_async(self._on_print_complete(printer_id, data))
  469. def on_print_running_observed(data: dict):
  470. if self._on_print_running_observed:
  471. self._schedule_async(self._on_print_running_observed(printer_id, data))
  472. def on_finish_photo_moment(data: dict):
  473. if self._on_finish_photo_moment:
  474. self._schedule_async(self._on_finish_photo_moment(printer_id, data))
  475. def on_ams_change(ams_data: list):
  476. if self._on_ams_change:
  477. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  478. def on_layer_change(layer_num: int):
  479. if self._on_layer_change:
  480. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  481. def on_bed_temp_update(bed_temp: float):
  482. if self._on_bed_temp_update:
  483. self._schedule_async(self._on_bed_temp_update(printer_id, bed_temp))
  484. def on_drying_complete(ams_id: int):
  485. if self._on_drying_complete:
  486. self._schedule_async(self._on_drying_complete(printer_id, ams_id))
  487. client = BambuMQTTClient(
  488. ip_address=printer.ip_address,
  489. serial_number=printer.serial_number,
  490. access_code=printer.access_code,
  491. model=printer.model,
  492. on_state_change=on_state_change,
  493. on_print_start=on_print_start,
  494. on_print_complete=on_print_complete,
  495. on_ams_change=on_ams_change,
  496. on_layer_change=on_layer_change,
  497. on_bed_temp_update=on_bed_temp_update,
  498. on_drying_complete=on_drying_complete,
  499. on_print_running_observed=on_print_running_observed,
  500. on_finish_photo_moment=on_finish_photo_moment,
  501. )
  502. client.connect()
  503. self._clients[printer_id] = client
  504. self._models[printer_id] = printer.model # Cache model for feature detection
  505. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  506. # Wait a moment for connection
  507. await asyncio.sleep(1)
  508. return client.state.connected
  509. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  510. """Disconnect from a printer."""
  511. if printer_id in self._clients:
  512. self._clients[printer_id].disconnect(timeout=timeout)
  513. del self._clients[printer_id]
  514. self._models.pop(printer_id, None) # Clean up model cache
  515. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  516. def disconnect_all(self, timeout: float = 0):
  517. """Disconnect from all printers."""
  518. for printer_id in list(self._clients.keys()):
  519. self.disconnect_printer(printer_id, timeout=timeout)
  520. def get_status(self, printer_id: int) -> PrinterState | None:
  521. """Get the current status of a printer (checks for stale connections)."""
  522. if printer_id in self._clients:
  523. client = self._clients[printer_id]
  524. # Check staleness and update connected state if needed
  525. client.check_staleness()
  526. return client.state
  527. return None
  528. # Gcode states in which a job is loaded / in progress and cutting power
  529. # would ruin the print. PAUSE is included on purpose — a paused print is
  530. # still loaded on the bed. Used by the smart-plug auto-off guard (#1890) so
  531. # a re-print started from the touchscreen isn't killed mid-print.
  532. ACTIVE_PRINT_STATES = ("RUNNING", "PAUSE", "PREPARE", "SLICING")
  533. def is_print_active(self, printer_id: int) -> bool:
  534. """True when the printer currently has a print loaded / in progress.
  535. Returns False when disconnected or in any idle/terminal state
  536. (IDLE / FINISH / FAILED / unknown), so callers fail *open* only for
  537. the safe "nothing is printing" case. #1890.
  538. """
  539. state = self.get_status(printer_id)
  540. if not state or not state.connected:
  541. return False
  542. return state.state in self.ACTIVE_PRINT_STATES
  543. def get_model(self, printer_id: int) -> str | None:
  544. """Get the cached model for a printer."""
  545. return self._models.get(printer_id)
  546. def get_drying_targets(self, printer_id: int) -> dict[int, dict] | None:
  547. """Get cached active drying target params keyed by AMS id.
  548. Returned dict shape: ``{ams_id: {"filament": str, "temp": int}}``.
  549. Returns ``None`` when the printer is not connected. The cache is
  550. seeded by ``send_drying_command(mode=1)`` and cleared when drying
  551. stops or on the ``dry_time`` falling edge (handled inside
  552. ``BambuMQTTClient``).
  553. """
  554. client = self._clients.get(printer_id)
  555. return client._drying_targets if client else None
  556. def get_all_statuses(self) -> dict[int, PrinterState]:
  557. """Get status of all connected printers (checks for stale connections)."""
  558. result = {}
  559. for printer_id, client in self._clients.items():
  560. # Check staleness and update connected state if needed
  561. client.check_staleness()
  562. result[printer_id] = client.state
  563. return result
  564. def is_connected(self, printer_id: int) -> bool:
  565. """Check if a printer is connected (checks for stale connections)."""
  566. if printer_id in self._clients:
  567. client = self._clients[printer_id]
  568. # Check staleness and update connected state if needed
  569. return client.check_staleness()
  570. return False
  571. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  572. """Get the MQTT client for a printer."""
  573. return self._clients.get(printer_id)
  574. def mark_printer_offline(self, printer_id: int):
  575. """Mark a printer as offline and trigger status callback.
  576. This is used when we know the printer power was cut (e.g., smart plug turned off)
  577. to immediately update the UI without waiting for MQTT timeout.
  578. """
  579. import logging
  580. logger = logging.getLogger(__name__)
  581. if printer_id in self._clients:
  582. client = self._clients[printer_id]
  583. if client.state.connected:
  584. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  585. client.state.connected = False
  586. client.state.state = "unknown"
  587. # Trigger the status change callback to broadcast via WebSocket
  588. if self._on_status_change:
  589. self._schedule_async(self._on_status_change(printer_id, client.state))
  590. def start_print(
  591. self,
  592. printer_id: int,
  593. filename: str,
  594. plate_id: int = 1,
  595. ams_mapping: list[int] | None = None,
  596. bed_levelling: bool = True,
  597. flow_cali: bool = False,
  598. vibration_cali: bool = True,
  599. layer_inspect: bool = False,
  600. timelapse: bool = False,
  601. use_ams: bool = True,
  602. nozzle_offset_cali: bool = False,
  603. nozzle_mapping: str | None = None,
  604. ) -> bool:
  605. """Start a print on a connected printer.
  606. ``nozzle_mapping`` is an opaque JSON string captured from BambuStudio's
  607. project_file MQTT command (H2C rack-swap slicer pick preservation,
  608. #1780). It rides through to the MQTT client untouched; the dispatch
  609. builder there parses + injects it only on dual-nozzle models.
  610. """
  611. caller = traceback.extract_stack(limit=3)[0]
  612. logger.info(
  613. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  614. printer_id,
  615. filename,
  616. caller.filename.split("/")[-1],
  617. caller.lineno,
  618. caller.name,
  619. )
  620. if printer_id in self._clients:
  621. return self._clients[printer_id].start_print(
  622. filename,
  623. plate_id,
  624. ams_mapping=ams_mapping,
  625. timelapse=timelapse,
  626. bed_levelling=bed_levelling,
  627. flow_cali=flow_cali,
  628. vibration_cali=vibration_cali,
  629. layer_inspect=layer_inspect,
  630. use_ams=use_ams,
  631. nozzle_offset_cali=nozzle_offset_cali,
  632. nozzle_mapping=nozzle_mapping,
  633. )
  634. return False
  635. def stop_print(self, printer_id: int) -> bool:
  636. """Stop the current print on a connected printer."""
  637. if printer_id in self._clients:
  638. return self._clients[printer_id].stop_print()
  639. return False
  640. async def wait_for_cooldown(
  641. self,
  642. printer_id: int,
  643. target_temp: float = 50.0,
  644. timeout: int = 600,
  645. check_interval: int = 10,
  646. ) -> bool:
  647. """Wait for the nozzle to cool down to a safe temperature.
  648. Args:
  649. printer_id: The printer to monitor
  650. target_temp: Target temperature to wait for (default 50°C)
  651. timeout: Maximum seconds to wait (default 600s = 10 min)
  652. check_interval: Seconds between temperature checks (default 10s)
  653. Returns:
  654. True if cooled down, False if timeout or not connected
  655. """
  656. import logging
  657. logger = logging.getLogger(__name__)
  658. elapsed = 0
  659. while elapsed < timeout:
  660. state = self.get_status(printer_id)
  661. if not state or not state.connected:
  662. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  663. return False
  664. # Check nozzle temperature (and nozzle_2 for dual extruders)
  665. nozzle_temp = state.temperatures.get("nozzle", 0)
  666. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  667. max_temp = max(nozzle_temp, nozzle_2_temp)
  668. if max_temp <= target_temp:
  669. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  670. return True
  671. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  672. await asyncio.sleep(check_interval)
  673. elapsed += check_interval
  674. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  675. return False
  676. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  677. """Enable or disable MQTT logging for a printer."""
  678. if printer_id in self._clients:
  679. self._clients[printer_id].enable_logging(enabled)
  680. return True
  681. return False
  682. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  683. """Get MQTT logs for a printer."""
  684. if printer_id in self._clients:
  685. return self._clients[printer_id].get_logs()
  686. return []
  687. def clear_logs(self, printer_id: int) -> bool:
  688. """Clear MQTT logs for a printer."""
  689. if printer_id in self._clients:
  690. self._clients[printer_id].clear_logs()
  691. return True
  692. return False
  693. def is_logging_enabled(self, printer_id: int) -> bool:
  694. """Check if logging is enabled for a printer."""
  695. if printer_id in self._clients:
  696. return self._clients[printer_id].logging_enabled
  697. return False
  698. def send_drying_command(
  699. self,
  700. printer_id: int,
  701. ams_id: int,
  702. temp: int,
  703. duration: int,
  704. mode: int = 1,
  705. filament: str = "",
  706. rotate_tray: bool = False,
  707. ) -> bool:
  708. """Send AMS drying command to printer."""
  709. if printer_id not in self._clients:
  710. return False
  711. return self._clients[printer_id].send_drying_command(ams_id, temp, duration, mode, filament, rotate_tray)
  712. def request_status_update(self, printer_id: int) -> bool:
  713. """Request a full status update from the printer.
  714. This sends a 'pushall' command to get the latest data including nozzle info.
  715. """
  716. if printer_id in self._clients:
  717. return self._clients[printer_id].request_status_update()
  718. return False
  719. # Probe budget for test_connection (#1445). Was a fixed 2s sleep, which was
  720. # too short for P1S firmware whose broker / TLS handshake routinely takes
  721. # 3–5s to surface a CONNACK on a cold MQTT session. We now poll up to
  722. # PROBE_TIMEOUT_SECONDS and early-return the moment we see connected=True,
  723. # so happy-path connections still finish in ~1–2s and slow brokers get the
  724. # headroom they need instead of getting falsely rejected.
  725. PROBE_TIMEOUT_SECONDS = 8.0
  726. PROBE_POLL_INTERVAL_SECONDS = 0.2
  727. async def test_connection(
  728. self,
  729. ip_address: str,
  730. serial_number: str,
  731. access_code: str,
  732. ) -> dict:
  733. """Test connection to a printer without persisting.
  734. Polls for up to PROBE_TIMEOUT_SECONDS and tears the probe client down
  735. off-loop. The teardown matters: `client.disconnect()` ends in paho's
  736. `loop_stop()` which `join()`s the network thread — if the thread is
  737. still mid-TLS-handshake to a slow printer, that join blocks the
  738. asyncio event loop and every other HTTP request queues behind it. The
  739. original synchronous teardown produced the #1445 "Docker container
  740. hangs" symptom on P1S when called from POST /printers/.
  741. """
  742. client = BambuMQTTClient(
  743. ip_address=ip_address,
  744. serial_number=serial_number,
  745. access_code=access_code,
  746. )
  747. try:
  748. client.connect()
  749. deadline = asyncio.get_running_loop().time() + self.PROBE_TIMEOUT_SECONDS
  750. while not client.state.connected and asyncio.get_running_loop().time() < deadline:
  751. await asyncio.sleep(self.PROBE_POLL_INTERVAL_SECONDS)
  752. result = {
  753. "success": client.state.connected,
  754. "state": client.state.state if client.state.connected else None,
  755. "model": client.state.raw_data.get("device_model"),
  756. }
  757. finally:
  758. # Off-loop teardown — see docstring. paho's loop_stop() joins the
  759. # network thread which may still be in a slow TLS handshake.
  760. await asyncio.to_thread(client.disconnect)
  761. return result
  762. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  763. """
  764. Compute a human-readable status name based on printer state.
  765. Uses stg_cur when available, otherwise derives status from temperature data
  766. when the printer is heating before a print starts.
  767. Args:
  768. state: The printer state to analyze
  769. model: Optional printer model for model-specific workarounds
  770. """
  771. # Firmware bug: some models (A1, P1P, P1S) report stg_cur=0 when not printing.
  772. # stg_cur=0 maps to "Printing" in STAGE_NAMES, which incorrectly overrides the
  773. # real state (IDLE, FINISH, FAILED, etc.). Only trust stg_cur when the printer
  774. # is actually in an active print state (RUNNING or PAUSE).
  775. if state.state not in ("RUNNING", "PAUSE") and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  776. return None
  777. # If we have a valid calibration stage, use it
  778. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  779. # Valid stage numbers are 0-254
  780. if 0 <= state.stg_cur < 255:
  781. return get_stage_name(state.stg_cur)
  782. # If not in RUNNING state, no derived status needed
  783. if state.state != "RUNNING":
  784. return None
  785. # Check if we're in an early phase where temperatures are heating
  786. temps = state.temperatures or {}
  787. progress = state.progress or 0
  788. # Only derive heating status when progress is very low (< 2%)
  789. # This indicates we're in the preparation phase, not actually printing
  790. if progress >= 2:
  791. return None
  792. # Check bed temperature - if target is set and current is significantly below
  793. bed_temp = temps.get("bed", 0)
  794. bed_target = temps.get("bed_target", 0)
  795. # Check nozzle temperature
  796. nozzle_temp = temps.get("nozzle", 0)
  797. nozzle_target = temps.get("nozzle_target", 0)
  798. # Temperature thresholds: consider "heating" if more than 10°C below target
  799. TEMP_THRESHOLD = 10
  800. # Determine what's heating (prioritize bed since it takes longer)
  801. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  802. return "Heating heatbed"
  803. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  804. return "Heating nozzle"
  805. # If targets are set but we're close to them, we might be in final prep
  806. if bed_target > 30 or nozzle_target > 30:
  807. if progress == 0 and state.layer_num == 0:
  808. return "Preparing"
  809. return None
  810. _PLATE_ID_RE = re.compile(r"plate_(\d+)\.gcode")
  811. def parse_plate_id(gcode_file: str | None) -> int | None:
  812. """Extract the 1-indexed plate number from a Bambu gcode_file path.
  813. Returns None when the path is missing or has no `plate_N.gcode` segment.
  814. Shared by the REST status route and the WebSocket push path so both agree
  815. on the value sent to the frontend (#881 follow-up).
  816. """
  817. if not gcode_file:
  818. return None
  819. match = _PLATE_ID_RE.search(gcode_file)
  820. return int(match.group(1)) if match else None
  821. def resolve_plate_id(state) -> int | None:
  822. """Resolve the active plate number from a PrinterState.
  823. Some firmware versions (e.g. P1S 01.10.00.00, #1166) put only the .3mf
  824. filename in print.gcode_file, so parse_plate_id() returns None and the
  825. printer card falls back to plate 1 — wrong thumbnail. When Bambuddy
  826. dispatched the print itself we already know the right plate, so we prefer
  827. that over the gcode_file echo. The subtask check prevents stale values
  828. from a previous Bambuddy-dispatched print bleeding into a Studio-direct
  829. print on the same printer.
  830. """
  831. dispatched_plate = getattr(state, "dispatched_plate_id", None)
  832. dispatched_subtask = getattr(state, "dispatched_subtask", None)
  833. if (
  834. dispatched_plate is not None
  835. and dispatched_subtask is not None
  836. and state.subtask_name
  837. and dispatched_subtask == state.subtask_name
  838. ):
  839. return dispatched_plate
  840. return parse_plate_id(state.gcode_file)
  841. def printer_state_to_dict(
  842. state: PrinterState,
  843. printer_id: int | None = None,
  844. model: str | None = None,
  845. drying_targets: dict[int, dict] | None = None,
  846. ) -> dict:
  847. """Convert PrinterState to a JSON-serializable dict.
  848. Args:
  849. state: The printer state to convert
  850. printer_id: Optional printer ID for generating cover URLs
  851. model: Optional printer model for filtering unsupported features
  852. drying_targets: Optional per-AMS active-cycle params
  853. (``{ams_id: {"filament": str, "temp": int}}``) sourced from the
  854. BambuMQTTClient cache so the badge can display "PETG @ 65°C".
  855. """
  856. # Parse AMS data from raw_data
  857. ams_units = []
  858. vt_tray = []
  859. raw_data = state.raw_data or {}
  860. # Build K-profile lookup map: cali_idx -> k_value
  861. kprofile_map: dict[int, float] = {}
  862. for kp in state.kprofiles or []:
  863. if kp.slot_id is not None and kp.k_value:
  864. try:
  865. kprofile_map[kp.slot_id] = float(kp.k_value)
  866. except (ValueError, TypeError):
  867. pass # Skip K-profile entries with unparseable values
  868. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  869. for ams_data in raw_data["ams"]:
  870. trays = []
  871. for tray in ams_data.get("tray", []):
  872. tag_uid = tray.get("tag_uid")
  873. if tag_uid in ("", "0000000000000000"):
  874. tag_uid = None
  875. tray_uuid = tray.get("tray_uuid")
  876. if tray_uuid in ("", "00000000000000000000000000000000"):
  877. tray_uuid = None
  878. # Get K value: first try tray's k field, then lookup from K-profiles
  879. k_value = tray.get("k")
  880. cali_idx = tray.get("cali_idx")
  881. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  882. k_value = kprofile_map[cali_idx]
  883. # P1S / A1 Mini physically-empty-slot signal (#1322 follow-up by
  884. # @RosdasHH): for a truly empty slot the firmware sends only
  885. # {"id": N} — no state, no tray_type, no anything else. Treat
  886. # that as the firmware's "no spool" indicator (state=9) so the
  887. # assign-spool path in inventory.py can short-circuit a MQTT
  888. # publish the firmware would silently drop anyway. The
  889. # post-"Reset Slot" A1 Mini BMCU case sends a populated payload
  890. # (state=3, tray_type="") — different shape, doesn't match this
  891. # guard, still attempts the MQTT push per the #1322 fix.
  892. state_val = tray.get("state")
  893. if state_val is None and len(tray) == 1 and "id" in tray:
  894. state_val = 9
  895. trays.append(
  896. {
  897. "id": int(tray.get("id", 0)),
  898. "tray_color": tray.get("tray_color"),
  899. "tray_type": tray.get("tray_type"),
  900. "tray_sub_brands": tray.get("tray_sub_brands"),
  901. "tray_id_name": tray.get("tray_id_name"),
  902. "tray_info_idx": tray.get("tray_info_idx"),
  903. "remain": tray.get("remain", 0),
  904. "k": k_value,
  905. "cali_idx": cali_idx,
  906. "tag_uid": tag_uid,
  907. "tray_uuid": tray_uuid,
  908. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  909. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  910. "drying_temp": tray.get("drying_temp"),
  911. "drying_time": tray.get("drying_time"),
  912. "state": state_val,
  913. }
  914. )
  915. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  916. humidity_raw = ams_data.get("humidity_raw")
  917. humidity_idx = ams_data.get("humidity")
  918. humidity_value = None
  919. if humidity_raw is not None:
  920. try:
  921. humidity_value = int(humidity_raw)
  922. except (ValueError, TypeError):
  923. pass # Skip unparseable humidity; will try index fallback
  924. # Fall back to index if no raw value (index is 1-5, not percentage)
  925. if humidity_value is None and humidity_idx is not None:
  926. try:
  927. humidity_value = int(humidity_idx)
  928. except (ValueError, TypeError):
  929. pass # Skip unparseable humidity index; humidity remains None
  930. # AMS-HT has 1 tray, regular AMS has 4 trays
  931. is_ams_ht = len(trays) == 1
  932. # Active-cycle filament + target temperature for the badge.
  933. # Bambu does not echo the cycle's chosen filament/temp on the
  934. # per-tick AMS push, so prefer the cached target from the last
  935. # ``send_drying_command``. When we have no record (drying
  936. # started in a previous backend lifetime, or the cache was
  937. # never seeded), fall back to the first loaded tray's
  938. # tray_type + RFID-recommended drying_temp — the same heuristic
  939. # the popover already uses to seed defaults.
  940. ams_id_int = int(ams_data.get("id", 0))
  941. target = (drying_targets or {}).get(ams_id_int)
  942. dry_target_temp: int | None = None
  943. dry_filament: str | None = None
  944. if target:
  945. temp_val = target.get("temp")
  946. fil_val = target.get("filament") or ""
  947. if temp_val is not None:
  948. try:
  949. dry_target_temp = int(temp_val)
  950. except (TypeError, ValueError):
  951. dry_target_temp = None
  952. if fil_val:
  953. dry_filament = str(fil_val)
  954. if dry_target_temp is None or not dry_filament:
  955. for tray in trays:
  956. if tray.get("tray_type"):
  957. if not dry_filament:
  958. dry_filament = str(tray["tray_type"])
  959. if dry_target_temp is None and tray.get("drying_temp"):
  960. try:
  961. dry_target_temp = int(tray["drying_temp"])
  962. except (TypeError, ValueError):
  963. pass
  964. break
  965. ams_units.append(
  966. {
  967. "id": ams_id_int,
  968. "humidity": humidity_value,
  969. "temp": ams_data.get("temp"),
  970. "is_ams_ht": is_ams_ht,
  971. "tray": trays,
  972. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  973. "serial_number": str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  974. # Firmware version: populated by _handle_version_info from get_version
  975. "sw_ver": str(ams_data.get("sw_ver") or ""),
  976. # Drying: dry_time > 0 means drying is active (minutes remaining)
  977. "dry_time": int(ams_data.get("dry_time") or 0),
  978. # Drying status from info hex bits (0=Off, 1=Checking, 2=Drying, 3=Cooling, etc.)
  979. "dry_status": int(ams_data.get("dry_status") or 0),
  980. "dry_sub_status": int(ams_data.get("dry_sub_status") or 0),
  981. # Cannot-dry reasons from firmware (e.g. 1=InsufficientPower, 8=NeedPluginPower)
  982. "dry_sf_reason": list(ams_data.get("dry_sf_reason") or []),
  983. # Active-cycle filament name + target temperature
  984. "dry_target_temp": dry_target_temp,
  985. "dry_filament": dry_filament,
  986. # Module type: "ams", "n3f", "n3s" (from get_version)
  987. "module_type": str(ams_data.get("module_type") or ""),
  988. }
  989. )
  990. # Parse virtual tray (external spool) — now a list
  991. if "vt_tray" in raw_data:
  992. vt_tray_raw = raw_data["vt_tray"]
  993. # Defensive: MQTT sends vt_tray as a dict; normalize to list
  994. if isinstance(vt_tray_raw, dict):
  995. vt_tray_raw = [vt_tray_raw]
  996. elif not isinstance(vt_tray_raw, list):
  997. vt_tray_raw = []
  998. for vt_data in vt_tray_raw:
  999. vt_tag_uid = vt_data.get("tag_uid")
  1000. if vt_tag_uid in ("", "0000000000000000"):
  1001. vt_tag_uid = None
  1002. vt_tray_uuid = vt_data.get("tray_uuid")
  1003. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  1004. vt_tray_uuid = None
  1005. # Get K value for vt_tray
  1006. vt_k_value = vt_data.get("k")
  1007. vt_cali_idx = vt_data.get("cali_idx")
  1008. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  1009. vt_k_value = kprofile_map[vt_cali_idx]
  1010. tray_id = int(vt_data.get("id", 254))
  1011. vt_tray.append(
  1012. {
  1013. "id": tray_id,
  1014. "tray_color": vt_data.get("tray_color"),
  1015. "tray_type": vt_data.get("tray_type"),
  1016. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  1017. "tray_id_name": vt_data.get("tray_id_name"),
  1018. "tray_info_idx": vt_data.get("tray_info_idx"),
  1019. "remain": vt_data.get("remain", 0),
  1020. "k": vt_k_value,
  1021. "cali_idx": vt_cali_idx,
  1022. "tag_uid": vt_tag_uid,
  1023. "tray_uuid": vt_tray_uuid,
  1024. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  1025. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  1026. }
  1027. )
  1028. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  1029. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  1030. # Filter out chamber temp for models that don't have a real sensor
  1031. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  1032. temperatures = state.temperatures
  1033. if not supports_chamber_temp(model):
  1034. temperatures = {
  1035. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  1036. }
  1037. result = {
  1038. "connected": state.connected,
  1039. "state": state.state,
  1040. "current_print": state.current_print,
  1041. "subtask_name": state.subtask_name,
  1042. "gcode_file": state.gcode_file,
  1043. "progress": state.progress,
  1044. "remaining_time": state.remaining_time,
  1045. "layer_num": state.layer_num,
  1046. "total_layers": state.total_layers,
  1047. "temperatures": temperatures,
  1048. "hms_errors": [
  1049. {
  1050. "code": e.code,
  1051. "attr": e.attr,
  1052. "module": e.module,
  1053. "severity": e.severity,
  1054. "actions": e.actions,
  1055. "job_id": e.job_id,
  1056. "full_code": e.full_code,
  1057. }
  1058. for e in (state.hms_errors or [])
  1059. ],
  1060. # AMS data for filament colors
  1061. "ams": ams_units if ams_units else None,
  1062. "vt_tray": vt_tray,
  1063. # AMS status for filament change tracking
  1064. "ams_status_main": state.ams_status_main,
  1065. "ams_status_sub": state.ams_status_sub,
  1066. "tray_now": state.tray_now,
  1067. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  1068. "ams_extruder_map": ams_extruder_map,
  1069. # WiFi signal strength
  1070. "wifi_signal": state.wifi_signal,
  1071. "wired_network": state.wired_network,
  1072. "door_open": state.door_open,
  1073. # AMS Filament Backup state (auto-switch to second spool). Tri-state:
  1074. # True / False / None. None = unknown or unsupported (A1 family). UI
  1075. # uses this to drive the small status icon next to the AMS drying icon.
  1076. "ams_filament_backup": state.ams_filament_backup,
  1077. # Calibration stage tracking
  1078. "stg_cur": state.stg_cur,
  1079. "stg_cur_name": get_derived_status_name(state, model),
  1080. # Printable objects count for skip objects feature
  1081. "printable_objects_count": len(state.printable_objects),
  1082. # Fan speeds (0-100 percentage, None if not available)
  1083. "cooling_fan_speed": state.cooling_fan_speed,
  1084. "big_fan1_speed": state.big_fan1_speed,
  1085. "big_fan2_speed": state.big_fan2_speed,
  1086. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  1087. # Chamber light state
  1088. "chamber_light": state.chamber_light,
  1089. # Active extruder for dual-nozzle printers (0=right, 1=left)
  1090. "active_extruder": state.active_extruder,
  1091. # Print speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1092. "speed_level": state.speed_level,
  1093. # H2C nozzle rack (tool-changer dock positions)
  1094. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  1095. "nozzle_rack": [
  1096. {
  1097. "id": n.get("id", 0),
  1098. "nozzle_type": n.get("type", ""),
  1099. "nozzle_diameter": n.get("diameter", ""),
  1100. "wear": n.get("wear"),
  1101. "stat": n.get("stat"),
  1102. "max_temp": n.get("max_temp", 0),
  1103. "serial_number": n.get("serial_number", ""),
  1104. "filament_color": n.get("filament_color", ""),
  1105. "filament_id": n.get("filament_id", ""),
  1106. }
  1107. for n in (state.nozzle_rack or [])
  1108. ],
  1109. # AMS drying support
  1110. "supports_drying": supports_drying(model, state.firmware_version),
  1111. "supports_drying_while_printing": supports_drying_while_printing(model, state.firmware_version),
  1112. "drying_screen_only": drying_screen_only(model),
  1113. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  1114. # Pushed via WebSocket so the printer card picks up plate transitions within
  1115. # a multi-plate 3MF without waiting for the 30 s REST poll (#881 follow-up).
  1116. # current_archive_id is intentionally REST-only — it's stable for the life
  1117. # of a print and needs a DB lookup the WebSocket path shouldn't pay for.
  1118. "current_plate_id": resolve_plate_id(state),
  1119. # Plate-clear gate (#939). Lives on the PrinterManager rather than PrinterState,
  1120. # so surface it here — without this, WebSocket merges drop the flag and the
  1121. # "Clear Plate" button only appears when the 30 s REST fallback poll runs.
  1122. "awaiting_plate_clear": printer_manager.is_awaiting_plate_clear(printer_id) if printer_id else False,
  1123. }
  1124. # Add cover URL if there's an active print and printer_id is provided
  1125. # Include PAUSE state so skip objects modal can show cover
  1126. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  1127. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  1128. else:
  1129. result["cover_url"] = None
  1130. # Surface the display name + model so WS consumers (gcode viewer printer
  1131. # selector) can render proper labels on the initial snapshot without racing
  1132. # a separate /api/v1/printers fetch (#963 follow-up). PrinterInfo only
  1133. # carries name/serial_number; the model comes through via the `model` arg.
  1134. if printer_id:
  1135. _printer_info = printer_manager.get_printer(printer_id)
  1136. if _printer_info is not None:
  1137. result["name"] = _printer_info.name
  1138. if model:
  1139. result["model"] = model
  1140. return result
  1141. # Global printer manager instance
  1142. printer_manager = PrinterManager()
  1143. async def init_printer_connections(db: AsyncSession):
  1144. """Initialize connections to all active printers.
  1145. Connections are started concurrently. ``connect_printer()`` is non-blocking
  1146. apart from a fixed 1-second settle wait — ``BambuMQTTClient.connect()`` only
  1147. calls ``connect_async()`` + ``loop_start()``, so the handshake happens on a
  1148. background thread and the coroutine's only real cost is that ``sleep(1)``. A
  1149. serial loop therefore spent one whole second per printer inside the FastAPI
  1150. lifespan *before* the ASGI server begins serving: on a large farm that was
  1151. ~100s of dead air before port 8000 responded (issue #2572, reporter's
  1152. 93-printer farm). Gathering overlaps the settle waits so the whole step takes
  1153. ~1s regardless of fleet size. Exceptions are isolated per printer with
  1154. ``return_exceptions=True`` so one unreachable row can't abort the rest — or
  1155. startup itself, which the old serial loop's un-caught await would have done.
  1156. All columns ``connect_printer`` reads are eagerly loaded by the SELECT above
  1157. and touched synchronously before its trailing ``await``, so no concurrent
  1158. lazy-load is triggered on the shared session.
  1159. """
  1160. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1161. printers = result.scalars().all()
  1162. outcomes = await asyncio.gather(
  1163. *(printer_manager.connect_printer(printer) for printer in printers),
  1164. return_exceptions=True,
  1165. )
  1166. for printer, outcome in zip(printers, outcomes, strict=True):
  1167. if isinstance(outcome, Exception):
  1168. logger.warning(
  1169. "Failed to connect printer %s (%s) at startup: %s",
  1170. printer.id,
  1171. printer.name,
  1172. outcome,
  1173. )