printer_manager.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. import asyncio
  2. from collections.abc import Callable
  3. from sqlalchemy import select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from backend.app.models.printer import Printer
  6. from backend.app.services.bambu_mqtt import BambuMQTTClient, MQTTLogEntry, PrinterState, get_stage_name
  7. # Models that have a real chamber temperature sensor
  8. # Based on Home Assistant Bambu Lab integration
  9. # P1P/P1S and A1/A1Mini do NOT have chamber temp sensors
  10. # Includes both display names and internal codes from MQTT/SSDP
  11. CHAMBER_TEMP_SUPPORTED_MODELS = frozenset(
  12. [
  13. # Display names
  14. "X1",
  15. "X1C",
  16. "X1E", # X1 series
  17. "P2S", # P2 series
  18. "H2C",
  19. "H2D",
  20. "H2DPRO",
  21. "H2S", # H2 series
  22. # Internal codes (from MQTT/SSDP)
  23. "BL-P001", # X1/X1C
  24. "C13", # X1E
  25. "O1D", # H2D
  26. "O1C", # H2C
  27. "O1S", # H2S
  28. "O1E", # H2D Pro
  29. "N7", # P2S
  30. ]
  31. )
  32. # Models that may incorrectly report stg_cur=0 when idle (firmware bug)
  33. # Based on Home Assistant Bambu Lab integration observations
  34. # See: https://github.com/greghesp/ha-bambulab/blob/main/custom_components/bambu_lab/pybambu/models.py
  35. A1_MODELS = frozenset(
  36. [
  37. # Display names
  38. "A1",
  39. "A1 MINI",
  40. "A1-MINI",
  41. "A1MINI",
  42. # Internal codes (from MQTT/SSDP)
  43. "N1", # A1 Mini
  44. "N2S", # A1
  45. ]
  46. )
  47. def supports_chamber_temp(model: str | None) -> bool:
  48. """Check if a printer model has a real chamber temperature sensor.
  49. P1P, P1S, A1, and A1Mini do NOT have chamber temp sensors.
  50. The 'chamber_temper' value they report is meaningless.
  51. """
  52. if not model:
  53. return False
  54. # Normalize model name (uppercase, strip whitespace)
  55. model_upper = model.strip().upper()
  56. return model_upper in CHAMBER_TEMP_SUPPORTED_MODELS
  57. def has_stg_cur_idle_bug(model: str | None) -> bool:
  58. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  59. Some A1/A1 Mini firmware versions report stg_cur=0 (which maps to "Printing")
  60. even when the printer is idle. This is a known firmware bug that was observed
  61. in the Home Assistant Bambu Lab integration.
  62. """
  63. if not model:
  64. return False
  65. model_upper = model.strip().upper()
  66. return model_upper in A1_MODELS
  67. class PrinterInfo:
  68. """Basic printer info for callbacks."""
  69. def __init__(self, name: str, serial_number: str):
  70. self.name = name
  71. self.serial_number = serial_number
  72. class PrinterManager:
  73. """Manager for multiple printer connections."""
  74. def __init__(self):
  75. self._clients: dict[int, BambuMQTTClient] = {}
  76. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  77. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  78. self._on_print_start: Callable[[int, dict], None] | None = None
  79. self._on_print_complete: Callable[[int, dict], None] | None = None
  80. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  81. self._on_ams_change: Callable[[int, list], None] | None = None
  82. self._on_layer_change: Callable[[int, int], None] | None = None
  83. self._loop: asyncio.AbstractEventLoop | None = None
  84. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  85. """Get printer info by ID."""
  86. return self._printer_info.get(printer_id)
  87. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  88. """Set the event loop for async callbacks."""
  89. self._loop = loop
  90. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  91. """Set callback for print start events."""
  92. self._on_print_start = callback
  93. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  94. """Set callback for print completion events."""
  95. self._on_print_complete = callback
  96. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  97. """Set callback for status change events."""
  98. self._on_status_change = callback
  99. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  100. """Set callback for AMS data change events."""
  101. self._on_ams_change = callback
  102. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  103. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  104. self._on_layer_change = callback
  105. def _schedule_async(self, coro):
  106. """Schedule an async coroutine from a sync context.
  107. Captures exceptions from the coroutine and logs them to prevent
  108. silent failures in callbacks.
  109. """
  110. if self._loop and self._loop.is_running():
  111. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  112. def handle_exception(f):
  113. try:
  114. # This will re-raise any exception from the coroutine
  115. f.result()
  116. except Exception as e:
  117. import logging
  118. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  119. future.add_done_callback(handle_exception)
  120. async def connect_printer(self, printer: Printer) -> bool:
  121. """Connect to a printer."""
  122. if printer.id in self._clients:
  123. self.disconnect_printer(printer.id)
  124. printer_id = printer.id
  125. def on_state_change(state: PrinterState):
  126. if self._on_status_change:
  127. self._schedule_async(self._on_status_change(printer_id, state))
  128. def on_print_start(data: dict):
  129. if self._on_print_start:
  130. self._schedule_async(self._on_print_start(printer_id, data))
  131. def on_print_complete(data: dict):
  132. if self._on_print_complete:
  133. self._schedule_async(self._on_print_complete(printer_id, data))
  134. def on_ams_change(ams_data: list):
  135. if self._on_ams_change:
  136. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  137. def on_layer_change(layer_num: int):
  138. if self._on_layer_change:
  139. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  140. client = BambuMQTTClient(
  141. ip_address=printer.ip_address,
  142. serial_number=printer.serial_number,
  143. access_code=printer.access_code,
  144. on_state_change=on_state_change,
  145. on_print_start=on_print_start,
  146. on_print_complete=on_print_complete,
  147. on_ams_change=on_ams_change,
  148. on_layer_change=on_layer_change,
  149. )
  150. client.connect()
  151. self._clients[printer_id] = client
  152. self._models[printer_id] = printer.model # Cache model for feature detection
  153. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  154. # Wait a moment for connection
  155. await asyncio.sleep(1)
  156. return client.state.connected
  157. def disconnect_printer(self, printer_id: int):
  158. """Disconnect from a printer."""
  159. if printer_id in self._clients:
  160. self._clients[printer_id].disconnect()
  161. del self._clients[printer_id]
  162. self._models.pop(printer_id, None) # Clean up model cache
  163. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  164. def disconnect_all(self):
  165. """Disconnect from all printers."""
  166. for printer_id in list(self._clients.keys()):
  167. self.disconnect_printer(printer_id)
  168. def get_status(self, printer_id: int) -> PrinterState | None:
  169. """Get the current status of a printer (checks for stale connections)."""
  170. if printer_id in self._clients:
  171. client = self._clients[printer_id]
  172. # Check staleness and update connected state if needed
  173. client.check_staleness()
  174. return client.state
  175. return None
  176. def get_model(self, printer_id: int) -> str | None:
  177. """Get the cached model for a printer."""
  178. return self._models.get(printer_id)
  179. def get_all_statuses(self) -> dict[int, PrinterState]:
  180. """Get status of all connected printers (checks for stale connections)."""
  181. result = {}
  182. for printer_id, client in self._clients.items():
  183. # Check staleness and update connected state if needed
  184. client.check_staleness()
  185. result[printer_id] = client.state
  186. return result
  187. def is_connected(self, printer_id: int) -> bool:
  188. """Check if a printer is connected (checks for stale connections)."""
  189. if printer_id in self._clients:
  190. client = self._clients[printer_id]
  191. # Check staleness and update connected state if needed
  192. return client.check_staleness()
  193. return False
  194. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  195. """Get the MQTT client for a printer."""
  196. return self._clients.get(printer_id)
  197. def mark_printer_offline(self, printer_id: int):
  198. """Mark a printer as offline and trigger status callback.
  199. This is used when we know the printer power was cut (e.g., smart plug turned off)
  200. to immediately update the UI without waiting for MQTT timeout.
  201. """
  202. import logging
  203. logger = logging.getLogger(__name__)
  204. if printer_id in self._clients:
  205. client = self._clients[printer_id]
  206. if client.state.connected:
  207. logger.info(f"Marking printer {printer_id} as offline (smart plug power off)")
  208. client.state.connected = False
  209. client.state.state = "unknown"
  210. # Trigger the status change callback to broadcast via WebSocket
  211. if self._on_status_change:
  212. self._schedule_async(self._on_status_change(printer_id, client.state))
  213. def start_print(
  214. self,
  215. printer_id: int,
  216. filename: str,
  217. plate_id: int = 1,
  218. ams_mapping: list[int] | None = None,
  219. bed_levelling: bool = True,
  220. flow_cali: bool = False,
  221. vibration_cali: bool = True,
  222. layer_inspect: bool = False,
  223. timelapse: bool = False,
  224. use_ams: bool = True,
  225. ) -> bool:
  226. """Start a print on a connected printer."""
  227. if printer_id in self._clients:
  228. return self._clients[printer_id].start_print(
  229. filename,
  230. plate_id,
  231. ams_mapping=ams_mapping,
  232. timelapse=timelapse,
  233. bed_levelling=bed_levelling,
  234. flow_cali=flow_cali,
  235. vibration_cali=vibration_cali,
  236. layer_inspect=layer_inspect,
  237. use_ams=use_ams,
  238. )
  239. return False
  240. def stop_print(self, printer_id: int) -> bool:
  241. """Stop the current print on a connected printer."""
  242. if printer_id in self._clients:
  243. return self._clients[printer_id].stop_print()
  244. return False
  245. async def wait_for_cooldown(
  246. self,
  247. printer_id: int,
  248. target_temp: float = 50.0,
  249. timeout: int = 600,
  250. check_interval: int = 10,
  251. ) -> bool:
  252. """Wait for the nozzle to cool down to a safe temperature.
  253. Args:
  254. printer_id: The printer to monitor
  255. target_temp: Target temperature to wait for (default 50°C)
  256. timeout: Maximum seconds to wait (default 600s = 10 min)
  257. check_interval: Seconds between temperature checks (default 10s)
  258. Returns:
  259. True if cooled down, False if timeout or not connected
  260. """
  261. import logging
  262. logger = logging.getLogger(__name__)
  263. elapsed = 0
  264. while elapsed < timeout:
  265. state = self.get_status(printer_id)
  266. if not state or not state.connected:
  267. logger.warning(f"Printer {printer_id} disconnected during cooldown wait")
  268. return False
  269. # Check nozzle temperature (and nozzle_2 for dual extruders)
  270. nozzle_temp = state.temperatures.get("nozzle", 0)
  271. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  272. max_temp = max(nozzle_temp, nozzle_2_temp)
  273. if max_temp <= target_temp:
  274. logger.info(f"Printer {printer_id} cooled down to {max_temp}°C")
  275. return True
  276. logger.debug(f"Printer {printer_id} nozzle at {max_temp}°C, waiting for {target_temp}°C...")
  277. await asyncio.sleep(check_interval)
  278. elapsed += check_interval
  279. logger.warning(f"Printer {printer_id} cooldown timeout after {timeout}s")
  280. return False
  281. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  282. """Enable or disable MQTT logging for a printer."""
  283. if printer_id in self._clients:
  284. self._clients[printer_id].enable_logging(enabled)
  285. return True
  286. return False
  287. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  288. """Get MQTT logs for a printer."""
  289. if printer_id in self._clients:
  290. return self._clients[printer_id].get_logs()
  291. return []
  292. def clear_logs(self, printer_id: int) -> bool:
  293. """Clear MQTT logs for a printer."""
  294. if printer_id in self._clients:
  295. self._clients[printer_id].clear_logs()
  296. return True
  297. return False
  298. def is_logging_enabled(self, printer_id: int) -> bool:
  299. """Check if logging is enabled for a printer."""
  300. if printer_id in self._clients:
  301. return self._clients[printer_id].logging_enabled
  302. return False
  303. def request_status_update(self, printer_id: int) -> bool:
  304. """Request a full status update from the printer.
  305. This sends a 'pushall' command to get the latest data including nozzle info.
  306. """
  307. if printer_id in self._clients:
  308. return self._clients[printer_id].request_status_update()
  309. return False
  310. async def test_connection(
  311. self,
  312. ip_address: str,
  313. serial_number: str,
  314. access_code: str,
  315. ) -> dict:
  316. """Test connection to a printer without persisting."""
  317. client = BambuMQTTClient(
  318. ip_address=ip_address,
  319. serial_number=serial_number,
  320. access_code=access_code,
  321. )
  322. try:
  323. client.connect()
  324. await asyncio.sleep(2)
  325. result = {
  326. "success": client.state.connected,
  327. "state": client.state.state if client.state.connected else None,
  328. "model": client.state.raw_data.get("device_model"),
  329. }
  330. finally:
  331. client.disconnect()
  332. return result
  333. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  334. """
  335. Compute a human-readable status name based on printer state.
  336. Uses stg_cur when available, otherwise derives status from temperature data
  337. when the printer is heating before a print starts.
  338. Args:
  339. state: The printer state to analyze
  340. model: Optional printer model for model-specific workarounds
  341. """
  342. # A1/A1 Mini firmware bug: some versions report stg_cur=0 when idle
  343. # Only correct this specific case (IDLE + stg_cur=0) for affected models
  344. if state.state == "IDLE" and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  345. return None
  346. # If we have a valid calibration stage, use it
  347. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  348. # Valid stage numbers are 0-254
  349. if 0 <= state.stg_cur < 255:
  350. return get_stage_name(state.stg_cur)
  351. # If not in RUNNING state, no derived status needed
  352. if state.state != "RUNNING":
  353. return None
  354. # Check if we're in an early phase where temperatures are heating
  355. temps = state.temperatures or {}
  356. progress = state.progress or 0
  357. # Only derive heating status when progress is very low (< 2%)
  358. # This indicates we're in the preparation phase, not actually printing
  359. if progress >= 2:
  360. return None
  361. # Check bed temperature - if target is set and current is significantly below
  362. bed_temp = temps.get("bed", 0)
  363. bed_target = temps.get("bed_target", 0)
  364. # Check nozzle temperature
  365. nozzle_temp = temps.get("nozzle", 0)
  366. nozzle_target = temps.get("nozzle_target", 0)
  367. # Temperature thresholds: consider "heating" if more than 10°C below target
  368. TEMP_THRESHOLD = 10
  369. # Determine what's heating (prioritize bed since it takes longer)
  370. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  371. return "Heating heatbed"
  372. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  373. return "Heating nozzle"
  374. # If targets are set but we're close to them, we might be in final prep
  375. if bed_target > 30 or nozzle_target > 30:
  376. if progress == 0 and state.layer_num == 0:
  377. return "Preparing"
  378. return None
  379. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None, model: str | None = None) -> dict:
  380. """Convert PrinterState to a JSON-serializable dict.
  381. Args:
  382. state: The printer state to convert
  383. printer_id: Optional printer ID for generating cover URLs
  384. model: Optional printer model for filtering unsupported features
  385. """
  386. # Parse AMS data from raw_data
  387. ams_units = []
  388. vt_tray = None
  389. raw_data = state.raw_data or {}
  390. # Build K-profile lookup map: cali_idx -> k_value
  391. kprofile_map: dict[int, float] = {}
  392. for kp in state.kprofiles or []:
  393. if kp.slot_id is not None and kp.k_value:
  394. try:
  395. kprofile_map[kp.slot_id] = float(kp.k_value)
  396. except (ValueError, TypeError):
  397. pass
  398. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  399. for ams_data in raw_data["ams"]:
  400. trays = []
  401. for tray in ams_data.get("tray", []):
  402. tag_uid = tray.get("tag_uid")
  403. if tag_uid in ("", "0000000000000000"):
  404. tag_uid = None
  405. tray_uuid = tray.get("tray_uuid")
  406. if tray_uuid in ("", "00000000000000000000000000000000"):
  407. tray_uuid = None
  408. # Get K value: first try tray's k field, then lookup from K-profiles
  409. k_value = tray.get("k")
  410. cali_idx = tray.get("cali_idx")
  411. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  412. k_value = kprofile_map[cali_idx]
  413. trays.append(
  414. {
  415. "id": tray.get("id", 0),
  416. "tray_color": tray.get("tray_color"),
  417. "tray_type": tray.get("tray_type"),
  418. "tray_sub_brands": tray.get("tray_sub_brands"),
  419. "tray_id_name": tray.get("tray_id_name"),
  420. "tray_info_idx": tray.get("tray_info_idx"),
  421. "remain": tray.get("remain", 0),
  422. "k": k_value,
  423. "cali_idx": cali_idx,
  424. "tag_uid": tag_uid,
  425. "tray_uuid": tray_uuid,
  426. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  427. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  428. }
  429. )
  430. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  431. humidity_raw = ams_data.get("humidity_raw")
  432. humidity_idx = ams_data.get("humidity")
  433. humidity_value = None
  434. if humidity_raw is not None:
  435. try:
  436. humidity_value = int(humidity_raw)
  437. except (ValueError, TypeError):
  438. pass
  439. # Fall back to index if no raw value (index is 1-5, not percentage)
  440. if humidity_value is None and humidity_idx is not None:
  441. try:
  442. humidity_value = int(humidity_idx)
  443. except (ValueError, TypeError):
  444. pass
  445. # AMS-HT has 1 tray, regular AMS has 4 trays
  446. is_ams_ht = len(trays) == 1
  447. ams_units.append(
  448. {
  449. "id": ams_data.get("id", 0),
  450. "humidity": humidity_value,
  451. "temp": ams_data.get("temp"),
  452. "is_ams_ht": is_ams_ht,
  453. "tray": trays,
  454. }
  455. )
  456. # Parse virtual tray (external spool)
  457. if "vt_tray" in raw_data:
  458. vt_data = raw_data["vt_tray"]
  459. vt_tag_uid = vt_data.get("tag_uid")
  460. if vt_tag_uid in ("", "0000000000000000"):
  461. vt_tag_uid = None
  462. vt_tray_uuid = vt_data.get("tray_uuid")
  463. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  464. vt_tray_uuid = None
  465. # Get K value for vt_tray
  466. vt_k_value = vt_data.get("k")
  467. vt_cali_idx = vt_data.get("cali_idx")
  468. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  469. vt_k_value = kprofile_map[vt_cali_idx]
  470. vt_tray = {
  471. "id": 254,
  472. "tray_color": vt_data.get("tray_color"),
  473. "tray_type": vt_data.get("tray_type"),
  474. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  475. "tray_id_name": vt_data.get("tray_id_name"),
  476. "tray_info_idx": vt_data.get("tray_info_idx"),
  477. "remain": vt_data.get("remain", 0),
  478. "k": vt_k_value,
  479. "cali_idx": vt_cali_idx,
  480. "tag_uid": vt_tag_uid,
  481. "tray_uuid": vt_tray_uuid,
  482. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  483. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  484. }
  485. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  486. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  487. # Filter out chamber temp for models that don't have a real sensor
  488. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  489. temperatures = state.temperatures
  490. if not supports_chamber_temp(model):
  491. temperatures = {
  492. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  493. }
  494. result = {
  495. "connected": state.connected,
  496. "state": state.state,
  497. "current_print": state.current_print,
  498. "subtask_name": state.subtask_name,
  499. "gcode_file": state.gcode_file,
  500. "progress": state.progress,
  501. "remaining_time": state.remaining_time,
  502. "layer_num": state.layer_num,
  503. "total_layers": state.total_layers,
  504. "temperatures": temperatures,
  505. "hms_errors": [
  506. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  507. for e in (state.hms_errors or [])
  508. ],
  509. # AMS data for filament colors
  510. "ams": ams_units if ams_units else None,
  511. "vt_tray": vt_tray,
  512. # AMS status for filament change tracking
  513. "ams_status_main": state.ams_status_main,
  514. "ams_status_sub": state.ams_status_sub,
  515. "tray_now": state.tray_now,
  516. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  517. "ams_extruder_map": ams_extruder_map,
  518. # WiFi signal strength
  519. "wifi_signal": state.wifi_signal,
  520. # Calibration stage tracking
  521. "stg_cur": state.stg_cur,
  522. "stg_cur_name": get_derived_status_name(state, model),
  523. # Printable objects count for skip objects feature
  524. "printable_objects_count": len(state.printable_objects),
  525. # Fan speeds (0-100 percentage, None if not available)
  526. "cooling_fan_speed": state.cooling_fan_speed,
  527. "big_fan1_speed": state.big_fan1_speed,
  528. "big_fan2_speed": state.big_fan2_speed,
  529. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  530. # Chamber light state
  531. "chamber_light": state.chamber_light,
  532. # Active extruder for dual-nozzle printers (0=right, 1=left)
  533. "active_extruder": state.active_extruder,
  534. }
  535. # Add cover URL if there's an active print and printer_id is provided
  536. # Include PAUSE/PAUSED states so skip objects modal can show cover
  537. if printer_id and state.state in ("RUNNING", "PAUSE", "PAUSED") and state.gcode_file:
  538. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  539. else:
  540. result["cover_url"] = None
  541. return result
  542. # Global printer manager instance
  543. printer_manager = PrinterManager()
  544. async def init_printer_connections(db: AsyncSession):
  545. """Initialize connections to all active printers."""
  546. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  547. printers = result.scalars().all()
  548. for printer in printers:
  549. await printer_manager.connect_printer(printer)