main.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  1. import asyncio
  2. import logging
  3. from contextlib import asynccontextmanager
  4. from datetime import UTC, datetime, timedelta
  5. from logging.handlers import RotatingFileHandler
  6. from fastapi import FastAPI
  7. # Import settings first for logging configuration
  8. from backend.app.core.config import APP_VERSION, settings as app_settings
  9. # Configure logging based on settings
  10. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  11. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  12. log_level = getattr(logging, log_level_str, logging.INFO)
  13. log_format = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
  14. # Create root logger
  15. root_logger = logging.getLogger()
  16. root_logger.setLevel(log_level)
  17. # Console handler - always enabled
  18. console_handler = logging.StreamHandler()
  19. console_handler.setLevel(log_level)
  20. console_handler.setFormatter(logging.Formatter(log_format))
  21. root_logger.addHandler(console_handler)
  22. # File handler - only in production or if explicitly enabled
  23. if app_settings.log_to_file:
  24. log_file = app_settings.log_dir / "bambuddy.log"
  25. file_handler = RotatingFileHandler(
  26. log_file,
  27. maxBytes=5 * 1024 * 1024, # 5MB
  28. backupCount=3,
  29. encoding="utf-8",
  30. )
  31. file_handler.setLevel(log_level)
  32. file_handler.setFormatter(logging.Formatter(log_format))
  33. root_logger.addHandler(file_handler)
  34. logging.info(f"Logging to file: {log_file}")
  35. # Reduce noise from third-party libraries in production
  36. if not app_settings.debug:
  37. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  38. logging.getLogger("httpcore").setLevel(logging.WARNING)
  39. logging.getLogger("httpx").setLevel(logging.WARNING)
  40. logging.info(f"Bambuddy starting - debug={app_settings.debug}, log_level={log_level_str}")
  41. from fastapi.responses import FileResponse
  42. from fastapi.staticfiles import StaticFiles
  43. from sqlalchemy import delete, or_, select
  44. from backend.app.api.routes import (
  45. ams_history,
  46. api_keys,
  47. archives,
  48. camera,
  49. cloud,
  50. discovery,
  51. external_links,
  52. filaments,
  53. firmware,
  54. kprofiles,
  55. maintenance,
  56. notification_templates,
  57. notifications,
  58. pending_uploads,
  59. print_queue,
  60. printers,
  61. projects,
  62. settings as settings_routes,
  63. smart_plugs,
  64. spoolman,
  65. support,
  66. system,
  67. updates,
  68. webhook,
  69. websocket,
  70. )
  71. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  72. from backend.app.api.routes.support import init_debug_logging
  73. from backend.app.core.database import async_session, init_db
  74. from backend.app.core.websocket import ws_manager
  75. from backend.app.models.smart_plug import SmartPlug
  76. from backend.app.services.archive import ArchiveService
  77. from backend.app.services.bambu_ftp import download_file_async, get_ftp_retry_settings, with_ftp_retry
  78. from backend.app.services.bambu_mqtt import PrinterState
  79. from backend.app.services.notification_service import notification_service
  80. from backend.app.services.print_scheduler import scheduler as print_scheduler
  81. from backend.app.services.printer_manager import (
  82. init_printer_connections,
  83. printer_manager,
  84. printer_state_to_dict,
  85. )
  86. from backend.app.services.smart_plug_manager import smart_plug_manager
  87. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  88. from backend.app.services.tasmota import tasmota_service
  89. from backend.app.services.telemetry import start_telemetry_loop
  90. # Track active prints: {(printer_id, filename): archive_id}
  91. _active_prints: dict[tuple[int, str], int] = {}
  92. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  93. # {(printer_id, filename): archive_id}
  94. _expected_prints: dict[tuple[int, str], int] = {}
  95. # Track starting energy for prints: {archive_id: starting_kwh}
  96. _print_energy_start: dict[int, float] = {}
  97. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  98. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  99. # Store with multiple filename variations to catch different naming patterns
  100. _expected_prints[(printer_id, filename)] = archive_id
  101. # Also store without .3mf extension if present
  102. if filename.endswith(".3mf"):
  103. base = filename[:-4]
  104. _expected_prints[(printer_id, base)] = archive_id
  105. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  106. logging.getLogger(__name__).info(
  107. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  108. )
  109. _last_status_broadcast: dict[int, str] = {}
  110. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  111. async def _report_spoolman_usage(printer_id: int, archive_id: int, logger):
  112. """Report filament usage to Spoolman after print completion.
  113. This finds the spool by RFID tag_uid from current AMS state and reports
  114. the filament_used_grams from the archive metadata.
  115. """
  116. async with async_session() as db:
  117. from backend.app.api.routes.settings import get_setting
  118. from backend.app.models.archive import PrintArchive
  119. # Check if Spoolman is enabled
  120. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  121. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  122. return
  123. # Get Spoolman URL
  124. spoolman_url = await get_setting(db, "spoolman_url")
  125. if not spoolman_url:
  126. return
  127. # Get or create Spoolman client
  128. client = await get_spoolman_client()
  129. if not client:
  130. client = await init_spoolman_client(spoolman_url)
  131. # Check if Spoolman is reachable
  132. if not await client.health_check():
  133. logger.warning("Spoolman not reachable for usage reporting")
  134. return
  135. # Get archive to find filament usage
  136. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  137. archive = result.scalar_one_or_none()
  138. if not archive or not archive.filament_used_grams:
  139. logger.debug(f"No filament usage data for archive {archive_id}")
  140. return
  141. filament_used = archive.filament_used_grams
  142. logger.info(f"[SPOOLMAN] Archive {archive_id} used {filament_used}g of filament")
  143. # Get current AMS state from printer to find the active spool
  144. state = printer_manager.get_status(printer_id)
  145. if not state or not state.raw_data:
  146. logger.debug("No printer state available for usage reporting")
  147. return
  148. ams_data = state.raw_data.get("ams")
  149. if not ams_data:
  150. logger.debug("No AMS data available for usage reporting")
  151. return
  152. # Find spools with RFID tags in Spoolman and report usage
  153. # For now, we report usage to the first spool found with a matching tag
  154. # TODO: In future, track which specific trays were used during the print
  155. spools_updated = 0
  156. for ams_unit in ams_data:
  157. trays = ams_unit.get("tray", [])
  158. for tray_data in trays:
  159. tag_uid = tray_data.get("tag_uid")
  160. if not tag_uid:
  161. continue
  162. # Find spool in Spoolman by tag
  163. spool = await client.find_spool_by_tag(tag_uid)
  164. if spool:
  165. # Report usage to Spoolman
  166. result = await client.use_spool(spool["id"], filament_used)
  167. if result:
  168. logger.info(
  169. f"[SPOOLMAN] Reported {filament_used}g usage to spool {spool['id']} (tag: {tag_uid})"
  170. )
  171. spools_updated += 1
  172. # Only report to one spool for single-material prints
  173. # Multi-material prints would need more sophisticated tracking
  174. return
  175. if spools_updated == 0:
  176. logger.debug(f"No matching Spoolman spools found for printer {printer_id}")
  177. async def on_printer_status_change(printer_id: int, state: PrinterState):
  178. """Handle printer status changes - broadcast via WebSocket."""
  179. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  180. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  181. temps = state.temperatures or {}
  182. nozzle_temp = round(temps.get("nozzle", 0))
  183. bed_temp = round(temps.get("bed", 0))
  184. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  185. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  186. # Auto-detect dual-nozzle printers from MQTT temperature data
  187. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  188. _nozzle_count_updated.add(printer_id)
  189. # Update nozzle_count in database
  190. async with async_session() as db:
  191. from backend.app.models.printer import Printer
  192. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  193. printer = result.scalar_one_or_none()
  194. if printer and printer.nozzle_count != 2:
  195. printer.nozzle_count = 2
  196. await db.commit()
  197. logging.getLogger(__name__).info(
  198. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  199. )
  200. # Include target temps for heating phase detection
  201. bed_target = round(temps.get("bed_target", 0))
  202. nozzle_target = round(temps.get("nozzle_target", 0))
  203. status_key = (
  204. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  205. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  206. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  207. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}"
  208. )
  209. if _last_status_broadcast.get(printer_id) == status_key:
  210. return # No change, skip broadcast
  211. _last_status_broadcast[printer_id] = status_key
  212. await ws_manager.send_printer_status(
  213. printer_id,
  214. printer_state_to_dict(state, printer_id),
  215. )
  216. async def on_ams_change(printer_id: int, ams_data: list):
  217. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  218. import logging
  219. logger = logging.getLogger(__name__)
  220. try:
  221. async with async_session() as db:
  222. from backend.app.api.routes.settings import get_setting
  223. from backend.app.models.printer import Printer
  224. # Check if Spoolman is enabled
  225. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  226. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  227. return
  228. # Check sync mode
  229. sync_mode = await get_setting(db, "spoolman_sync_mode")
  230. if sync_mode and sync_mode != "auto":
  231. return # Only sync on auto mode
  232. # Get Spoolman URL
  233. spoolman_url = await get_setting(db, "spoolman_url")
  234. if not spoolman_url:
  235. return
  236. # Get or create Spoolman client
  237. client = await get_spoolman_client()
  238. if not client:
  239. client = await init_spoolman_client(spoolman_url)
  240. # Check if Spoolman is reachable
  241. if not await client.health_check():
  242. logger.warning(f"Spoolman not reachable at {spoolman_url}")
  243. return
  244. # Get printer name for location
  245. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  246. printer = result.scalar_one_or_none()
  247. printer_name = printer.name if printer else f"Printer {printer_id}"
  248. # Sync each AMS tray
  249. synced = 0
  250. for ams_unit in ams_data:
  251. ams_id = int(ams_unit.get("id", 0))
  252. trays = ams_unit.get("tray", [])
  253. for tray_data in trays:
  254. tray = client.parse_ams_tray(ams_id, tray_data)
  255. if not tray:
  256. continue # Empty tray
  257. try:
  258. result = await client.sync_ams_tray(tray, printer_name)
  259. if result:
  260. synced += 1
  261. except Exception as e:
  262. logger.error(f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}")
  263. if synced > 0:
  264. logger.info(f"Auto-synced {synced} AMS trays to Spoolman for printer {printer_id}")
  265. except Exception as e:
  266. import logging
  267. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  268. async def _send_print_start_notification(
  269. printer_id: int,
  270. data: dict,
  271. archive_data: dict | None = None,
  272. logger=None,
  273. ):
  274. """Helper to send print start notification with optional archive data."""
  275. if logger is None:
  276. import logging
  277. logger = logging.getLogger(__name__)
  278. try:
  279. async with async_session() as db:
  280. from backend.app.models.printer import Printer
  281. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  282. printer = result.scalar_one_or_none()
  283. printer_name = printer.name if printer else f"Printer {printer_id}"
  284. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  285. except Exception as e:
  286. logger.warning(f"Notification on_print_start failed: {e}")
  287. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  288. """Extract printable objects from an archive's 3MF file and store in printer state."""
  289. try:
  290. from backend.app.services.archive import extract_printable_objects_from_3mf
  291. file_path = app_settings.base_dir / archive.file_path
  292. if file_path.exists() and str(file_path).endswith(".3mf"):
  293. with open(file_path, "rb") as f:
  294. threemf_data = f.read()
  295. # Extract with positions for UI overlay
  296. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  297. if printable_objects:
  298. client = printer_manager.get_client(printer_id)
  299. if client:
  300. client.state.printable_objects = printable_objects
  301. client.state.printable_objects_bbox_all = bbox_all
  302. client.state.skipped_objects = []
  303. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  304. except Exception as e:
  305. logger.debug(f"Failed to extract printable objects from archive: {e}")
  306. async def on_print_start(printer_id: int, data: dict):
  307. """Handle print start - archive the 3MF file immediately."""
  308. import logging
  309. logger = logging.getLogger(__name__)
  310. logger.info(f"[CALLBACK] on_print_start called for printer {printer_id}, data keys: {list(data.keys())}")
  311. await ws_manager.send_print_start(printer_id, data)
  312. # Track if notification was sent (to avoid sending twice)
  313. notification_sent = False
  314. # Smart plug automation: turn on plug when print starts
  315. try:
  316. async with async_session() as db:
  317. await smart_plug_manager.on_print_start(printer_id, db)
  318. except Exception as e:
  319. logger.warning(f"Smart plug on_print_start failed: {e}")
  320. async with async_session() as db:
  321. from backend.app.models.printer import Printer
  322. from backend.app.services.bambu_ftp import list_files_async
  323. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  324. printer = result.scalar_one_or_none()
  325. if not printer or not printer.auto_archive:
  326. # Send notification without archive data (auto-archive disabled)
  327. logger.info(
  328. f"[CALLBACK] Skipping archive - printer: {printer is not None}, auto_archive: {printer.auto_archive if printer else 'N/A'}"
  329. )
  330. if not notification_sent:
  331. await _send_print_start_notification(printer_id, data, logger=logger)
  332. return
  333. # Get the filename and subtask_name
  334. filename = data.get("filename", "")
  335. subtask_name = data.get("subtask_name", "")
  336. logger.info(f"[CALLBACK] Print start detected - filename: {filename}, subtask: {subtask_name}")
  337. if not filename and not subtask_name:
  338. # Send notification without archive data (no filename)
  339. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  340. if not notification_sent:
  341. await _send_print_start_notification(printer_id, data, logger=logger)
  342. return
  343. # Check if this is an expected print from reprint/scheduled
  344. # Build list of possible keys to check
  345. expected_keys = []
  346. if subtask_name:
  347. expected_keys.append((printer_id, subtask_name))
  348. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  349. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  350. if filename:
  351. fname = filename.split("/")[-1] if "/" in filename else filename
  352. expected_keys.append((printer_id, fname))
  353. # Strip extensions to match
  354. base = fname.replace(".gcode", "").replace(".3mf", "")
  355. expected_keys.append((printer_id, base))
  356. expected_keys.append((printer_id, f"{base}.3mf"))
  357. expected_archive_id = None
  358. for key in expected_keys:
  359. expected_archive_id = _expected_prints.pop(key, None)
  360. if expected_archive_id:
  361. # Clean up other possible keys for this print
  362. for other_key in expected_keys:
  363. _expected_prints.pop(other_key, None)
  364. break
  365. if expected_archive_id:
  366. # This is a reprint/scheduled print - use existing archive, don't create new one
  367. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  368. from backend.app.models.archive import PrintArchive
  369. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  370. archive = result.scalar_one_or_none()
  371. if archive:
  372. # Update archive status to printing
  373. archive.status = "printing"
  374. archive.started_at = datetime.now()
  375. await db.commit()
  376. # Track as active print
  377. _active_prints[(printer_id, archive.filename)] = archive.id
  378. if subtask_name:
  379. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  380. # Set up energy tracking
  381. try:
  382. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  383. plug = plug_result.scalar_one_or_none()
  384. logger.info(
  385. f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  386. )
  387. if plug:
  388. energy = await tasmota_service.get_energy(plug)
  389. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  390. if energy and energy.get("total") is not None:
  391. _print_energy_start[archive.id] = energy["total"]
  392. logger.info(
  393. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  394. )
  395. else:
  396. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  397. else:
  398. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  399. except Exception as e:
  400. logger.warning(f"Failed to record starting energy: {e}")
  401. await ws_manager.send_archive_updated(
  402. {
  403. "id": archive.id,
  404. "status": "printing",
  405. }
  406. )
  407. # Send notification with archive data (reprint/scheduled)
  408. if not notification_sent:
  409. archive_data = {"print_time_seconds": archive.print_time_seconds}
  410. await _send_print_start_notification(printer_id, data, archive_data, logger)
  411. # Extract printable objects from the archived 3MF file
  412. _load_objects_from_archive(archive, printer_id, logger)
  413. return # Skip creating a new archive
  414. # Check if there's already a "printing" archive for this printer/file
  415. # This prevents duplicates when backend restarts during an active print
  416. from backend.app.models.archive import PrintArchive
  417. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  418. existing = await db.execute(
  419. select(PrintArchive)
  420. .where(PrintArchive.printer_id == printer_id)
  421. .where(PrintArchive.status == "printing")
  422. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  423. .order_by(PrintArchive.created_at.desc())
  424. .limit(1)
  425. )
  426. existing_archive = existing.scalar_one_or_none()
  427. if existing_archive:
  428. # Check if archive is stale (older than 4 hours) - likely a failed/cancelled print
  429. # that didn't get properly updated
  430. archive_age = datetime.now(UTC) - existing_archive.created_at.replace(tzinfo=UTC)
  431. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  432. logger.warning(
  433. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  434. f"marking as cancelled and creating new archive"
  435. )
  436. existing_archive.status = "cancelled"
  437. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  438. await db.commit()
  439. # Fall through to create new archive (don't return)
  440. existing_archive = None # Clear so we don't use stale archive
  441. else:
  442. logger.info(
  443. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  444. )
  445. # Track this as the active print
  446. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  447. # Also set up energy tracking if not already tracked
  448. if existing_archive.id not in _print_energy_start:
  449. try:
  450. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  451. plug = plug_result.scalar_one_or_none()
  452. if plug:
  453. energy = await tasmota_service.get_energy(plug)
  454. if energy and energy.get("total") is not None:
  455. _print_energy_start[existing_archive.id] = energy["total"]
  456. logger.info(
  457. f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh"
  458. )
  459. except Exception as e:
  460. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  461. # Send notification with archive data (existing archive)
  462. if not notification_sent:
  463. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  464. await _send_print_start_notification(printer_id, data, archive_data, logger)
  465. # Extract printable objects from the archived 3MF file
  466. _load_objects_from_archive(existing_archive, printer_id, logger)
  467. return
  468. # Build list of possible 3MF filenames to try
  469. possible_names = []
  470. # Bambu printers typically store files as "Name.gcode.3mf"
  471. # The subtask_name is usually the best source for the filename
  472. if subtask_name:
  473. # Try common Bambu naming patterns
  474. possible_names.append(f"{subtask_name}.gcode.3mf")
  475. possible_names.append(f"{subtask_name}.3mf")
  476. # Try original filename with .3mf extension
  477. if filename:
  478. # Extract just the filename part, not the full path
  479. fname = filename.split("/")[-1] if "/" in filename else filename
  480. if fname.endswith(".3mf"):
  481. possible_names.append(fname)
  482. elif fname.endswith(".gcode"):
  483. base = fname.rsplit(".", 1)[0]
  484. possible_names.append(f"{base}.gcode.3mf")
  485. possible_names.append(f"{base}.3mf")
  486. else:
  487. possible_names.append(f"{fname}.gcode.3mf")
  488. possible_names.append(f"{fname}.3mf")
  489. # Remove duplicates while preserving order
  490. seen = set()
  491. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  492. logger.info(f"Trying filenames: {possible_names}")
  493. # Try to find and download the 3MF file
  494. temp_path = None
  495. downloaded_filename = None
  496. # Get FTP retry settings
  497. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  498. for try_filename in possible_names:
  499. if not try_filename.endswith(".3mf"):
  500. continue
  501. remote_paths = [
  502. f"/cache/{try_filename}",
  503. f"/model/{try_filename}",
  504. f"/{try_filename}",
  505. ]
  506. temp_path = app_settings.archive_dir / "temp" / try_filename
  507. temp_path.parent.mkdir(parents=True, exist_ok=True)
  508. for remote_path in remote_paths:
  509. logger.debug(f"Trying FTP download: {remote_path}")
  510. try:
  511. if ftp_retry_enabled:
  512. downloaded = await with_ftp_retry(
  513. download_file_async,
  514. printer.ip_address,
  515. printer.access_code,
  516. remote_path,
  517. temp_path,
  518. socket_timeout=ftp_timeout,
  519. printer_model=printer.model,
  520. max_retries=ftp_retry_count,
  521. retry_delay=ftp_retry_delay,
  522. operation_name=f"Download 3MF from {remote_path}",
  523. )
  524. else:
  525. downloaded = await download_file_async(
  526. printer.ip_address,
  527. printer.access_code,
  528. remote_path,
  529. temp_path,
  530. socket_timeout=ftp_timeout,
  531. printer_model=printer.model,
  532. )
  533. if downloaded:
  534. downloaded_filename = try_filename
  535. logger.info(f"Downloaded: {remote_path}")
  536. break
  537. except Exception as e:
  538. logger.debug(f"FTP download failed for {remote_path}: {e}")
  539. if downloaded_filename:
  540. break
  541. # If still not found, try listing /cache to find matching file
  542. if not downloaded_filename and (filename or subtask_name):
  543. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  544. logger.info(f"Direct FTP download failed, listing /cache to find '{search_term}'")
  545. try:
  546. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  547. threemf_files = [f.get("name") for f in cache_files if f.get("name", "").endswith(".3mf")]
  548. logger.info(
  549. f"Found {len(threemf_files)} 3MF files in /cache: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  550. )
  551. for f in cache_files:
  552. if f.get("is_directory"):
  553. continue
  554. fname = f.get("name", "")
  555. if fname.endswith(".3mf") and search_term in fname.lower():
  556. logger.info(f"Found matching file: {fname}")
  557. temp_path = app_settings.archive_dir / "temp" / fname
  558. temp_path.parent.mkdir(parents=True, exist_ok=True)
  559. if ftp_retry_enabled:
  560. downloaded = await with_ftp_retry(
  561. download_file_async,
  562. printer.ip_address,
  563. printer.access_code,
  564. f"/cache/{fname}",
  565. temp_path,
  566. max_retries=ftp_retry_count,
  567. retry_delay=ftp_retry_delay,
  568. operation_name=f"Download 3MF from /cache/{fname}",
  569. )
  570. else:
  571. downloaded = await download_file_async(
  572. printer.ip_address,
  573. printer.access_code,
  574. f"/cache/{fname}",
  575. temp_path,
  576. )
  577. if downloaded:
  578. downloaded_filename = fname
  579. logger.info(f"Found and downloaded from cache: {fname}")
  580. break
  581. except Exception as e:
  582. logger.warning(f"Failed to list cache: {e}")
  583. if not downloaded_filename or not temp_path:
  584. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  585. # Create a fallback archive without 3MF data so the print is still tracked
  586. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  587. try:
  588. from backend.app.models.archive import PrintArchive
  589. # Derive print name from subtask_name or filename
  590. print_name = subtask_name or filename
  591. if print_name:
  592. # Clean up the name (remove extensions, path parts)
  593. print_name = print_name.split("/")[-1]
  594. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  595. else:
  596. print_name = "Unknown Print"
  597. # Create minimal archive entry
  598. fallback_archive = PrintArchive(
  599. printer_id=printer_id,
  600. filename=filename or f"{print_name}.3mf",
  601. file_path="", # Empty - no 3MF file available
  602. file_size=0,
  603. print_name=print_name,
  604. status="printing",
  605. started_at=datetime.now(),
  606. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  607. )
  608. db.add(fallback_archive)
  609. await db.commit()
  610. await db.refresh(fallback_archive)
  611. logger.info(f"Created fallback archive {fallback_archive.id} for {print_name} (no 3MF available)")
  612. # Track as active print
  613. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  614. if filename:
  615. _active_prints[(printer_id, filename)] = fallback_archive.id
  616. if subtask_name:
  617. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  618. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  619. # Record starting energy if smart plug available
  620. try:
  621. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  622. plug = plug_result.scalar_one_or_none()
  623. if plug:
  624. energy = await tasmota_service.get_energy(plug)
  625. if energy and energy.get("total") is not None:
  626. _print_energy_start[fallback_archive.id] = energy["total"]
  627. logger.info(
  628. f"[ENERGY] Recorded starting energy for fallback archive {fallback_archive.id}: {energy['total']} kWh"
  629. )
  630. except Exception as e:
  631. logger.warning(f"Failed to record starting energy for fallback: {e}")
  632. # Send WebSocket notification
  633. await ws_manager.send_archive_created(
  634. {
  635. "id": fallback_archive.id,
  636. "printer_id": fallback_archive.printer_id,
  637. "filename": fallback_archive.filename,
  638. "print_name": fallback_archive.print_name,
  639. "status": fallback_archive.status,
  640. }
  641. )
  642. # Send notification without archive data (file not found)
  643. if not notification_sent:
  644. await _send_print_start_notification(printer_id, data, logger=logger)
  645. return
  646. except Exception as e:
  647. logger.error(f"Failed to create fallback archive: {e}")
  648. # Send notification without archive data (file not found)
  649. if not notification_sent:
  650. await _send_print_start_notification(printer_id, data, logger=logger)
  651. return
  652. try:
  653. # Archive the file with status "printing"
  654. service = ArchiveService(db)
  655. archive = await service.archive_print(
  656. printer_id=printer_id,
  657. source_file=temp_path,
  658. print_data={**data, "status": "printing"},
  659. )
  660. if archive:
  661. # Track this active print (use both original filename and downloaded filename)
  662. _active_prints[(printer_id, downloaded_filename)] = archive.id
  663. if filename and filename != downloaded_filename:
  664. _active_prints[(printer_id, filename)] = archive.id
  665. if subtask_name:
  666. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  667. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  668. # Record starting energy from smart plug if available
  669. try:
  670. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  671. plug = plug_result.scalar_one_or_none()
  672. logger.info(
  673. f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  674. )
  675. if plug:
  676. energy = await tasmota_service.get_energy(plug)
  677. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  678. if energy and energy.get("total") is not None:
  679. _print_energy_start[archive.id] = energy["total"]
  680. logger.info(
  681. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  682. )
  683. else:
  684. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  685. else:
  686. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  687. except Exception as e:
  688. logger.warning(f"Failed to record starting energy: {e}")
  689. await ws_manager.send_archive_created(
  690. {
  691. "id": archive.id,
  692. "printer_id": archive.printer_id,
  693. "filename": archive.filename,
  694. "print_name": archive.print_name,
  695. "status": archive.status,
  696. }
  697. )
  698. # Send notification with archive data (new archive created)
  699. if not notification_sent:
  700. archive_data = {"print_time_seconds": archive.print_time_seconds}
  701. await _send_print_start_notification(printer_id, data, archive_data, logger)
  702. notification_sent = True
  703. # Extract printable objects for skip object functionality
  704. try:
  705. from backend.app.services.archive import extract_printable_objects_from_3mf
  706. with open(temp_path, "rb") as f:
  707. threemf_data = f.read()
  708. # Extract with positions for UI overlay
  709. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  710. threemf_data, include_positions=True
  711. )
  712. if printable_objects:
  713. # Store objects in printer state
  714. client = printer_manager.get_client(printer_id)
  715. if client:
  716. client.state.printable_objects = printable_objects
  717. client.state.printable_objects_bbox_all = bbox_all
  718. client.state.skipped_objects = [] # Reset skipped objects for new print
  719. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  720. except Exception as e:
  721. logger.debug(f"Failed to extract printable objects: {e}")
  722. finally:
  723. if temp_path and temp_path.exists():
  724. temp_path.unlink()
  725. async def _scan_for_timelapse_with_retries(archive_id: int):
  726. """
  727. Scan for timelapse with retries.
  728. The printer encodes the timelapse quickly after print completion.
  729. We just need a short delay then grab the most recent file.
  730. Since we KNOW timelapse was active (from MQTT ipcam data), the most recent
  731. file in /timelapse is our target. Retries handle FTP connection issues.
  732. """
  733. import logging
  734. logger = logging.getLogger(__name__)
  735. # Short delays - printer usually finishes encoding within seconds
  736. retry_delays = [5, 10, 20]
  737. for attempt, delay in enumerate(retry_delays, 1):
  738. logger.info(
  739. f"[TIMELAPSE] Attempt {attempt}/{len(retry_delays)}: waiting {delay}s before scanning for archive {archive_id}"
  740. )
  741. await asyncio.sleep(delay)
  742. try:
  743. async with async_session() as db:
  744. from backend.app.models.printer import Printer
  745. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  746. # Get archive (ArchiveService from module-level import)
  747. service = ArchiveService(db)
  748. archive = await service.get_archive(archive_id)
  749. if not archive:
  750. logger.warning(f"[TIMELAPSE] Archive {archive_id} not found, stopping retries")
  751. return
  752. if archive.timelapse_path:
  753. logger.info(f"[TIMELAPSE] Archive {archive_id} already has timelapse attached, stopping retries")
  754. return
  755. if not archive.printer_id:
  756. logger.warning(f"[TIMELAPSE] Archive {archive_id} has no printer, stopping retries")
  757. return
  758. # Get printer
  759. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  760. printer = result.scalar_one_or_none()
  761. if not printer:
  762. logger.warning(f"[TIMELAPSE] Printer not found for archive {archive_id}, stopping retries")
  763. return
  764. # Scan timelapse directory on printer
  765. # H2D may store in different locations than X1C
  766. files = []
  767. found_path = None
  768. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  769. try:
  770. found_files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  771. if found_files:
  772. files = found_files
  773. found_path = timelapse_path
  774. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(files)} files in {timelapse_path}")
  775. break
  776. except Exception as e:
  777. logger.debug(f"[TIMELAPSE] Path {timelapse_path} failed: {e}")
  778. continue
  779. if not files:
  780. logger.info(f"[TIMELAPSE] Attempt {attempt}: No timelapse files found on printer, will retry")
  781. continue
  782. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  783. # Log ALL mp4 files found for debugging
  784. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(mp4_files)} MP4 files in {found_path}")
  785. for f in mp4_files[:5]: # Log first 5
  786. logger.info(f"[TIMELAPSE] - {f.get('name')}, mtime={f.get('mtime')}")
  787. if not mp4_files:
  788. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files found, will retry")
  789. continue
  790. # Sort by mtime descending to get most recent file
  791. mp4_files_with_mtime = [f for f in mp4_files if f.get("mtime")]
  792. if not mp4_files_with_mtime:
  793. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files with mtime found, will retry")
  794. continue
  795. mp4_files_with_mtime.sort(key=lambda x: x.get("mtime"), reverse=True)
  796. most_recent = mp4_files_with_mtime[0]
  797. file_name = most_recent.get("name")
  798. logger.info(f"[TIMELAPSE] Attempt {attempt}: Most recent file: {file_name}")
  799. # Since we KNOW timelapse was active (from MQTT), just grab the most recent file
  800. remote_path = most_recent.get("path") or f"/timelapse/{file_name}"
  801. logger.info(f"[TIMELAPSE] Downloading {file_name} for archive {archive_id}")
  802. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  803. if timelapse_data:
  804. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  805. if success:
  806. logger.info(f"[TIMELAPSE] Successfully attached timelapse to archive {archive_id}")
  807. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  808. return # Success!
  809. else:
  810. logger.warning(f"[TIMELAPSE] Failed to attach timelapse to archive {archive_id}")
  811. else:
  812. logger.warning(f"[TIMELAPSE] Attempt {attempt}: Failed to download, will retry")
  813. except Exception as e:
  814. logger.warning(f"[TIMELAPSE] Attempt {attempt} failed with error: {e}")
  815. logger.warning(f"[TIMELAPSE] All {len(retry_delays)} attempts exhausted for archive {archive_id}, giving up")
  816. async def on_print_complete(printer_id: int, data: dict):
  817. """Handle print completion - update the archive status."""
  818. import logging
  819. import time
  820. logger = logging.getLogger(__name__)
  821. start_time = time.time()
  822. def log_timing(section: str):
  823. elapsed = time.time() - start_time
  824. logger.info(f"[TIMING] {section}: {elapsed:.3f}s elapsed")
  825. logger.info(f"[CALLBACK] on_print_complete started for printer {printer_id}")
  826. try:
  827. ws_data = {
  828. "status": data.get("status"),
  829. "filename": data.get("filename"),
  830. "subtask_name": data.get("subtask_name"),
  831. "timelapse_was_active": data.get("timelapse_was_active"),
  832. }
  833. await ws_manager.send_print_complete(printer_id, ws_data)
  834. log_timing("WebSocket send_print_complete")
  835. except Exception as e:
  836. logger.warning(f"[CALLBACK] WebSocket send_print_complete failed: {e}")
  837. filename = data.get("filename", "")
  838. subtask_name = data.get("subtask_name", "")
  839. if not filename and not subtask_name:
  840. logger.warning("Print complete without filename or subtask_name")
  841. return
  842. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  843. # Build list of possible keys to try (matching how they were registered in on_print_start)
  844. possible_keys = []
  845. # Try subtask_name variations first (most reliable for matching)
  846. if subtask_name:
  847. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  848. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  849. possible_keys.append((printer_id, subtask_name))
  850. # Try filename variations
  851. if filename:
  852. # Extract just the filename if it's a path
  853. fname = filename.split("/")[-1] if "/" in filename else filename
  854. if fname.endswith(".3mf"):
  855. possible_keys.append((printer_id, fname))
  856. elif fname.endswith(".gcode"):
  857. base_name = fname.rsplit(".", 1)[0]
  858. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  859. possible_keys.append((printer_id, f"{base_name}.3mf"))
  860. possible_keys.append((printer_id, fname))
  861. else:
  862. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  863. possible_keys.append((printer_id, f"{fname}.3mf"))
  864. possible_keys.append((printer_id, fname))
  865. # Also try full path versions
  866. if filename.endswith(".3mf"):
  867. possible_keys.append((printer_id, filename))
  868. elif filename.endswith(".gcode"):
  869. base_name = filename.rsplit(".", 1)[0]
  870. possible_keys.append((printer_id, f"{base_name}.3mf"))
  871. possible_keys.append((printer_id, filename))
  872. else:
  873. possible_keys.append((printer_id, f"{filename}.3mf"))
  874. possible_keys.append((printer_id, filename))
  875. # Find the archive for this print
  876. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  877. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  878. archive_id = None
  879. for key in possible_keys:
  880. archive_id = _active_prints.pop(key, None)
  881. if archive_id:
  882. logger.info(f"Found archive {archive_id} with key {key}")
  883. # Also clean up any other keys pointing to this archive
  884. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  885. for k in keys_to_remove:
  886. _active_prints.pop(k, None)
  887. break
  888. if not archive_id:
  889. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  890. async with async_session() as db:
  891. from backend.app.models.archive import PrintArchive
  892. # Try matching by subtask_name (stored as print_name) first
  893. if subtask_name:
  894. result = await db.execute(
  895. select(PrintArchive)
  896. .where(PrintArchive.printer_id == printer_id)
  897. .where(PrintArchive.status == "printing")
  898. .where(
  899. or_(
  900. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  901. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  902. )
  903. )
  904. .order_by(PrintArchive.created_at.desc())
  905. .limit(1)
  906. )
  907. archive = result.scalar_one_or_none()
  908. if archive:
  909. archive_id = archive.id
  910. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  911. # Also try by filename
  912. if not archive_id and filename:
  913. result = await db.execute(
  914. select(PrintArchive)
  915. .where(PrintArchive.printer_id == printer_id)
  916. .where(PrintArchive.filename == filename)
  917. .where(PrintArchive.status == "printing")
  918. .order_by(PrintArchive.created_at.desc())
  919. .limit(1)
  920. )
  921. archive = result.scalar_one_or_none()
  922. if archive:
  923. archive_id = archive.id
  924. if not archive_id:
  925. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  926. return
  927. log_timing("Archive lookup")
  928. # Update archive status
  929. logger.info(f"[ARCHIVE] Updating archive {archive_id} status...")
  930. try:
  931. async with async_session() as db:
  932. service = ArchiveService(db)
  933. status = data.get("status", "completed")
  934. # Auto-detect failure reason
  935. failure_reason = None
  936. if status == "aborted":
  937. failure_reason = "User cancelled"
  938. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  939. elif status == "failed":
  940. # Try to determine failure reason from HMS errors
  941. hms_errors = data.get("hms_errors", [])
  942. if hms_errors:
  943. logger.info(f"[ARCHIVE] HMS errors at failure: {hms_errors}")
  944. # Map known HMS error modules to failure reasons
  945. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  946. for err in hms_errors:
  947. module = err.get("module", 0)
  948. if module == 0x07: # Filament module
  949. failure_reason = "Filament runout"
  950. break
  951. elif module == 0x0C: # Motion controller
  952. failure_reason = "Layer shift"
  953. break
  954. elif module == 0x05: # Nozzle/extruder
  955. failure_reason = "Clogged nozzle"
  956. break
  957. if failure_reason:
  958. logger.info(f"[ARCHIVE] Detected failure_reason from HMS: {failure_reason}")
  959. else:
  960. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  961. await service.update_archive_status(
  962. archive_id,
  963. status=status,
  964. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  965. failure_reason=failure_reason,
  966. )
  967. logger.info(f"[ARCHIVE] Archive {archive_id} status updated to {status}, failure_reason={failure_reason}")
  968. await ws_manager.send_archive_updated(
  969. {
  970. "id": archive_id,
  971. "status": status,
  972. }
  973. )
  974. logger.info(f"[ARCHIVE] WebSocket notification sent for archive {archive_id}")
  975. except Exception as e:
  976. logger.error(f"[ARCHIVE] Failed to update archive {archive_id} status: {e}", exc_info=True)
  977. # Continue with other operations even if archive update fails
  978. log_timing("Archive status update")
  979. # Report filament usage to Spoolman if print completed successfully
  980. if data.get("status") == "completed":
  981. try:
  982. await _report_spoolman_usage(printer_id, archive_id, logger)
  983. log_timing("Spoolman usage report")
  984. except Exception as e:
  985. logger.warning(f"Spoolman usage reporting failed: {e}")
  986. # Run slow operations as background tasks to avoid blocking the event loop
  987. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  988. starting_kwh = _print_energy_start.pop(archive_id, None)
  989. async def _background_energy_calculation():
  990. """Calculate and save energy usage in background."""
  991. try:
  992. logger.info(f"[ENERGY-BG] Starting energy calculation for archive {archive_id}")
  993. async with async_session() as db:
  994. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  995. plug = plug_result.scalar_one_or_none()
  996. if plug:
  997. energy = await tasmota_service.get_energy(plug)
  998. logger.info(f"[ENERGY-BG] Energy response: {energy}")
  999. energy_used = None
  1000. if starting_kwh is not None and energy and energy.get("total") is not None:
  1001. ending_kwh = energy["total"]
  1002. energy_used = round(ending_kwh - starting_kwh, 4)
  1003. logger.info(f"[ENERGY-BG] Per-print energy: {energy_used} kWh")
  1004. if energy_used is not None and energy_used >= 0:
  1005. from backend.app.api.routes.settings import get_setting
  1006. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  1007. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  1008. energy_cost = round(energy_used * cost_per_kwh, 2)
  1009. from backend.app.models.archive import PrintArchive
  1010. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1011. archive = result.scalar_one_or_none()
  1012. if archive:
  1013. archive.energy_kwh = energy_used
  1014. archive.energy_cost = energy_cost
  1015. await db.commit()
  1016. logger.info(f"[ENERGY-BG] Saved: {energy_used} kWh, cost={energy_cost}")
  1017. else:
  1018. logger.info(f"[ENERGY-BG] No smart plug for printer {printer_id}")
  1019. except Exception as e:
  1020. logger.warning(f"[ENERGY-BG] Failed: {e}")
  1021. async def _background_finish_photo():
  1022. """Capture finish photo in background."""
  1023. try:
  1024. logger.info(f"[PHOTO-BG] Starting finish photo capture for archive {archive_id}")
  1025. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1026. async with async_session() as db:
  1027. from backend.app.api.routes.settings import get_setting
  1028. capture_enabled = await get_setting(db, "capture_finish_photo")
  1029. if capture_enabled is None or capture_enabled.lower() == "true":
  1030. from backend.app.models.printer import Printer
  1031. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1032. printer = result.scalar_one_or_none()
  1033. if printer and archive_id:
  1034. from backend.app.models.archive import PrintArchive
  1035. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1036. archive = result.scalar_one_or_none()
  1037. if archive:
  1038. import uuid
  1039. from datetime import datetime
  1040. from pathlib import Path
  1041. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  1042. photo_filename = None
  1043. # Check if camera stream is active - use buffered frame to avoid freeze
  1044. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  1045. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1046. active_chamber_for_printer = [
  1047. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  1048. ]
  1049. buffered_frame = get_buffered_frame(printer_id)
  1050. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  1051. # Use frame from active stream
  1052. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  1053. photos_dir = archive_dir / "photos"
  1054. photos_dir.mkdir(parents=True, exist_ok=True)
  1055. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1056. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1057. photo_path = photos_dir / photo_filename
  1058. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  1059. logger.info(f"[PHOTO-BG] Saved buffered frame: {photo_filename}")
  1060. else:
  1061. # No active stream - capture new frame
  1062. from backend.app.services.camera import capture_finish_photo
  1063. photo_filename = await capture_finish_photo(
  1064. printer_id=printer_id,
  1065. ip_address=printer.ip_address,
  1066. access_code=printer.access_code,
  1067. model=printer.model,
  1068. archive_dir=archive_dir,
  1069. )
  1070. if photo_filename:
  1071. photos = archive.photos or []
  1072. photos.append(photo_filename)
  1073. archive.photos = photos
  1074. await db.commit()
  1075. logger.info(f"[PHOTO-BG] Saved: {photo_filename}")
  1076. except Exception as e:
  1077. logger.warning(f"[PHOTO-BG] Failed: {e}")
  1078. asyncio.create_task(_background_energy_calculation())
  1079. asyncio.create_task(_background_finish_photo()) # Skips if camera stream active
  1080. log_timing("Background tasks scheduled (energy, photo)")
  1081. # Also run smart plug, notifications, and maintenance as background tasks
  1082. print_status = data.get("status", "completed")
  1083. async def _background_smart_plug():
  1084. """Handle smart plug automation in background."""
  1085. try:
  1086. logger.info(f"[AUTO-OFF-BG] Starting smart plug automation for printer {printer_id}")
  1087. async with async_session() as db:
  1088. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  1089. logger.info("[AUTO-OFF-BG] Completed")
  1090. except Exception as e:
  1091. logger.warning(f"[AUTO-OFF-BG] Failed: {e}")
  1092. async def _background_notifications():
  1093. """Send print complete notifications in background."""
  1094. try:
  1095. logger.info(f"[NOTIFY-BG] Starting notifications for printer {printer_id}")
  1096. async with async_session() as db:
  1097. from backend.app.models.archive import PrintArchive
  1098. from backend.app.models.printer import Printer
  1099. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1100. printer = result.scalar_one_or_none()
  1101. printer_name = printer.name if printer else f"Printer {printer_id}"
  1102. archive_data = None
  1103. if archive_id:
  1104. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1105. archive = archive_result.scalar_one_or_none()
  1106. if archive:
  1107. archive_data = {
  1108. "print_time_seconds": archive.print_time_seconds,
  1109. "actual_filament_grams": archive.filament_used_grams,
  1110. "failure_reason": archive.failure_reason,
  1111. }
  1112. await notification_service.on_print_complete(
  1113. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  1114. )
  1115. logger.info("[NOTIFY-BG] Completed")
  1116. except Exception as e:
  1117. logger.warning(f"[NOTIFY-BG] Failed: {e}")
  1118. async def _background_maintenance_check():
  1119. """Check for maintenance due in background."""
  1120. if print_status != "completed":
  1121. return
  1122. try:
  1123. logger.info(f"[MAINT-BG] Starting maintenance check for printer {printer_id}")
  1124. async with async_session() as db:
  1125. from backend.app.models.printer import Printer
  1126. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1127. printer = result.scalar_one_or_none()
  1128. printer_name = printer.name if printer else f"Printer {printer_id}"
  1129. await ensure_default_types(db)
  1130. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  1131. items_needing_attention = [
  1132. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  1133. for item in overview.maintenance_items
  1134. if item.enabled and (item.is_due or item.is_warning)
  1135. ]
  1136. if items_needing_attention:
  1137. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  1138. logger.info(f"[MAINT-BG] Sent notification: {len(items_needing_attention)} items need attention")
  1139. else:
  1140. logger.info("[MAINT-BG] Completed (no items need attention)")
  1141. except Exception as e:
  1142. logger.warning(f"[MAINT-BG] Failed: {e}")
  1143. asyncio.create_task(_background_smart_plug())
  1144. asyncio.create_task(_background_notifications())
  1145. asyncio.create_task(_background_maintenance_check())
  1146. log_timing("All background tasks scheduled")
  1147. # Auto-scan for timelapse if recording was active during the print
  1148. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  1149. logger.info(f"[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive {archive_id}")
  1150. # Schedule timelapse scan as background task with retries
  1151. # The printer needs time to encode the video after print completion
  1152. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id))
  1153. log_timing("Timelapse scan scheduled")
  1154. # Update queue item if this was a scheduled print
  1155. try:
  1156. async with async_session() as db:
  1157. from backend.app.models.print_queue import PrintQueueItem
  1158. # Note: SmartPlug is already imported at module level (line 56)
  1159. # Do NOT import it here as it would shadow the module-level import
  1160. # and cause "cannot access local variable" errors earlier in this function
  1161. result = await db.execute(
  1162. select(PrintQueueItem)
  1163. .where(PrintQueueItem.printer_id == printer_id)
  1164. .where(PrintQueueItem.status == "printing")
  1165. )
  1166. queue_item = result.scalar_one_or_none()
  1167. if queue_item:
  1168. status = data.get("status", "completed")
  1169. queue_item.status = status
  1170. queue_item.completed_at = datetime.now()
  1171. await db.commit()
  1172. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  1173. # Handle auto_off_after - power off printer if requested (after cooldown)
  1174. if queue_item.auto_off_after:
  1175. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1176. plug = result.scalar_one_or_none()
  1177. if plug and plug.enabled:
  1178. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  1179. async def cooldown_and_poweroff(pid: int, plug_id: int):
  1180. # Wait for nozzle to cool down
  1181. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  1182. # Re-fetch plug in new session
  1183. async with async_session() as new_db:
  1184. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1185. p = result.scalar_one_or_none()
  1186. if p and p.enabled:
  1187. success = await tasmota_service.turn_off(p)
  1188. if success:
  1189. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  1190. else:
  1191. logger.warning(f"Failed to power off printer {pid} via smart plug")
  1192. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  1193. except Exception as e:
  1194. import logging
  1195. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  1196. log_timing("Queue item update")
  1197. logger.info(f"[CALLBACK] on_print_complete finished for printer {printer_id}, archive {archive_id}")
  1198. # AMS sensor history recording
  1199. _ams_history_task: asyncio.Task | None = None
  1200. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  1201. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  1202. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  1203. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  1204. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  1205. async def record_ams_history():
  1206. """Background task to record AMS humidity and temperature data."""
  1207. import logging
  1208. logger = logging.getLogger(__name__)
  1209. # Wait a short time for MQTT connections to establish on startup
  1210. await asyncio.sleep(10)
  1211. while True:
  1212. try:
  1213. from backend.app.models.ams_history import AMSSensorHistory
  1214. from backend.app.models.printer import Printer
  1215. from backend.app.models.settings import Settings
  1216. async with async_session() as db:
  1217. # Get all active printers
  1218. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1219. printers = result.scalars().all()
  1220. # Get alarm thresholds from settings
  1221. humidity_threshold = 60.0 # Default: fair threshold
  1222. temp_threshold = 35.0 # Default: fair threshold
  1223. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1224. setting = result.scalar_one_or_none()
  1225. if setting:
  1226. try:
  1227. humidity_threshold = float(setting.value)
  1228. except (ValueError, TypeError):
  1229. pass
  1230. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  1231. setting = result.scalar_one_or_none()
  1232. if setting:
  1233. try:
  1234. temp_threshold = float(setting.value)
  1235. except (ValueError, TypeError):
  1236. pass
  1237. recorded_count = 0
  1238. for printer in printers:
  1239. # Get current state from printer manager
  1240. state = printer_manager.get_status(printer.id)
  1241. if not state or not state.connected or not state.raw_data:
  1242. continue # Skip disconnected printers - don't use stale data
  1243. raw_data = state.raw_data
  1244. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  1245. continue
  1246. # Record data for each AMS unit
  1247. for ams_data in raw_data["ams"]:
  1248. ams_id = int(ams_data.get("id", 0))
  1249. # Get humidity (prefer humidity_raw)
  1250. humidity_raw = ams_data.get("humidity_raw")
  1251. humidity_idx = ams_data.get("humidity")
  1252. humidity = None
  1253. if humidity_raw is not None:
  1254. try:
  1255. humidity = float(humidity_raw)
  1256. except (ValueError, TypeError):
  1257. pass
  1258. if humidity is None and humidity_idx is not None:
  1259. try:
  1260. humidity = float(humidity_idx)
  1261. except (ValueError, TypeError):
  1262. pass
  1263. # Get temperature
  1264. temperature = None
  1265. temp_str = ams_data.get("temp")
  1266. if temp_str is not None:
  1267. try:
  1268. temperature = float(temp_str)
  1269. except (ValueError, TypeError):
  1270. pass
  1271. # Skip if no data
  1272. if humidity is None and temperature is None:
  1273. continue
  1274. # Record the data point
  1275. history = AMSSensorHistory(
  1276. printer_id=printer.id,
  1277. ams_id=ams_id,
  1278. humidity=humidity,
  1279. humidity_raw=float(humidity_raw) if humidity_raw else None,
  1280. temperature=temperature,
  1281. )
  1282. db.add(history)
  1283. recorded_count += 1
  1284. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  1285. is_ams_ht = ams_id >= 128
  1286. if is_ams_ht:
  1287. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  1288. else:
  1289. ams_label = f"AMS-{chr(65 + ams_id)}"
  1290. # Check humidity alarm (only if above threshold)
  1291. if humidity is not None and humidity > humidity_threshold:
  1292. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  1293. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1294. now = datetime.now()
  1295. if (
  1296. last_alarm is None
  1297. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1298. ):
  1299. _ams_alarm_cooldown[cooldown_key] = now
  1300. logger.info(
  1301. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  1302. )
  1303. try:
  1304. # Call different notification method based on AMS type
  1305. if is_ams_ht:
  1306. await notification_service.on_ams_ht_humidity_high(
  1307. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1308. )
  1309. else:
  1310. await notification_service.on_ams_humidity_high(
  1311. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1312. )
  1313. except Exception as e:
  1314. logger.warning(f"Failed to send humidity alarm: {e}")
  1315. # Check temperature alarm (only if above threshold)
  1316. if temperature is not None and temperature > temp_threshold:
  1317. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  1318. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1319. now = datetime.now()
  1320. if (
  1321. last_alarm is None
  1322. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1323. ):
  1324. _ams_alarm_cooldown[cooldown_key] = now
  1325. logger.info(
  1326. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  1327. )
  1328. try:
  1329. # Call different notification method based on AMS type
  1330. if is_ams_ht:
  1331. await notification_service.on_ams_ht_temperature_high(
  1332. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1333. )
  1334. else:
  1335. await notification_service.on_ams_temperature_high(
  1336. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1337. )
  1338. except Exception as e:
  1339. logger.warning(f"Failed to send temperature alarm: {e}")
  1340. await db.commit()
  1341. if recorded_count > 0:
  1342. logger.info(f"Recorded {recorded_count} AMS sensor history entries")
  1343. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  1344. global _ams_cleanup_counter
  1345. _ams_cleanup_counter += 1
  1346. if _ams_cleanup_counter >= 288:
  1347. _ams_cleanup_counter = 0
  1348. # Get retention days from settings
  1349. from backend.app.models.settings import Settings
  1350. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  1351. setting = result.scalar_one_or_none()
  1352. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  1353. cutoff = datetime.now() - timedelta(days=retention_days)
  1354. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  1355. await db.commit()
  1356. if result.rowcount > 0:
  1357. logger.info(
  1358. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  1359. )
  1360. # Wait until next recording interval
  1361. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  1362. except asyncio.CancelledError:
  1363. break
  1364. except Exception as e:
  1365. logger.warning(f"AMS history recording failed: {e}")
  1366. await asyncio.sleep(60) # Wait a bit before retrying
  1367. def start_ams_history_recording():
  1368. """Start the AMS history recording background task."""
  1369. global _ams_history_task
  1370. if _ams_history_task is None:
  1371. _ams_history_task = asyncio.create_task(record_ams_history())
  1372. logging.getLogger(__name__).info("AMS history recording started")
  1373. def stop_ams_history_recording():
  1374. """Stop the AMS history recording background task."""
  1375. global _ams_history_task
  1376. if _ams_history_task:
  1377. _ams_history_task.cancel()
  1378. _ams_history_task = None
  1379. logging.getLogger(__name__).info("AMS history recording stopped")
  1380. # Printer runtime tracking
  1381. _runtime_tracking_task: asyncio.Task | None = None
  1382. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  1383. async def track_printer_runtime():
  1384. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  1385. import logging
  1386. logger = logging.getLogger(__name__)
  1387. # Wait for MQTT connections to establish on startup
  1388. await asyncio.sleep(15)
  1389. while True:
  1390. try:
  1391. from backend.app.models.printer import Printer
  1392. async with async_session() as db:
  1393. # Get all active printers
  1394. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1395. printers = result.scalars().all()
  1396. now = datetime.now()
  1397. updated_count = 0
  1398. needs_commit = False
  1399. for printer in printers:
  1400. # Get current state from printer manager
  1401. state = printer_manager.get_status(printer.id)
  1402. if not state:
  1403. logger.debug(f"[{printer.name}] Runtime tracking: no state available")
  1404. continue
  1405. if not state.connected:
  1406. logger.debug(f"[{printer.name}] Runtime tracking: not connected")
  1407. continue
  1408. # Check if printer is in an active state (RUNNING or PAUSE)
  1409. if state.state in ("RUNNING", "PAUSE"):
  1410. # Calculate time since last update
  1411. if printer.last_runtime_update:
  1412. elapsed = (now - printer.last_runtime_update).total_seconds()
  1413. if elapsed > 0:
  1414. printer.runtime_seconds += int(elapsed)
  1415. updated_count += 1
  1416. needs_commit = True
  1417. logger.debug(
  1418. f"[{printer.name}] Runtime tracking: added {int(elapsed)}s, "
  1419. f"total={printer.runtime_seconds}s ({printer.runtime_seconds / 3600:.2f}h)"
  1420. )
  1421. else:
  1422. # First time seeing printer active - need to commit to save timestamp
  1423. needs_commit = True
  1424. logger.debug(f"[{printer.name}] Runtime tracking: first active detection")
  1425. printer.last_runtime_update = now
  1426. else:
  1427. # Printer is idle/offline - clear last_runtime_update
  1428. if printer.last_runtime_update is not None:
  1429. logger.debug(
  1430. f"[{printer.name}] Runtime tracking: state={state.state}, clearing last_runtime_update"
  1431. )
  1432. printer.last_runtime_update = None
  1433. needs_commit = True
  1434. if needs_commit:
  1435. await db.commit()
  1436. if updated_count > 0:
  1437. logger.debug(f"Updated runtime for {updated_count} printer(s)")
  1438. except asyncio.CancelledError:
  1439. logger.info("Runtime tracking cancelled")
  1440. break
  1441. except Exception as e:
  1442. logger.warning(f"Runtime tracking failed: {e}")
  1443. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  1444. def start_runtime_tracking():
  1445. """Start the printer runtime tracking background task."""
  1446. global _runtime_tracking_task
  1447. if _runtime_tracking_task is None:
  1448. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  1449. logging.getLogger(__name__).info("Printer runtime tracking started")
  1450. def stop_runtime_tracking():
  1451. """Stop the printer runtime tracking background task."""
  1452. global _runtime_tracking_task
  1453. if _runtime_tracking_task:
  1454. _runtime_tracking_task.cancel()
  1455. _runtime_tracking_task = None
  1456. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  1457. @asynccontextmanager
  1458. async def lifespan(app: FastAPI):
  1459. # Startup
  1460. await init_db()
  1461. # Restore debug logging state from previous session
  1462. await init_debug_logging()
  1463. # Set up printer manager callbacks
  1464. loop = asyncio.get_event_loop()
  1465. printer_manager.set_event_loop(loop)
  1466. printer_manager.set_status_change_callback(on_printer_status_change)
  1467. printer_manager.set_print_start_callback(on_print_start)
  1468. printer_manager.set_print_complete_callback(on_print_complete)
  1469. printer_manager.set_ams_change_callback(on_ams_change)
  1470. # Connect to all active printers
  1471. async with async_session() as db:
  1472. await init_printer_connections(db)
  1473. # Auto-connect to Spoolman if enabled
  1474. async with async_session() as db:
  1475. from backend.app.api.routes.settings import get_setting
  1476. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1477. spoolman_url = await get_setting(db, "spoolman_url")
  1478. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1479. try:
  1480. client = await init_spoolman_client(spoolman_url)
  1481. if await client.health_check():
  1482. logging.info(f"Auto-connected to Spoolman at {spoolman_url}")
  1483. else:
  1484. logging.warning(f"Spoolman at {spoolman_url} is not reachable")
  1485. except Exception as e:
  1486. logging.warning(f"Failed to auto-connect to Spoolman: {e}")
  1487. # Start the print scheduler
  1488. asyncio.create_task(print_scheduler.run())
  1489. # Start the smart plug scheduler for time-based on/off
  1490. smart_plug_manager.start_scheduler()
  1491. # Resume any pending auto-offs that were interrupted by restart
  1492. await smart_plug_manager.resume_pending_auto_offs()
  1493. # Start the notification digest scheduler
  1494. notification_service.start_digest_scheduler()
  1495. # Start AMS history recording
  1496. start_ams_history_recording()
  1497. # Start printer runtime tracking
  1498. start_runtime_tracking()
  1499. # Start anonymous telemetry (opt-out via settings)
  1500. asyncio.create_task(start_telemetry_loop(async_session))
  1501. # Initialize virtual printer manager
  1502. from backend.app.services.virtual_printer import virtual_printer_manager
  1503. virtual_printer_manager.set_session_factory(async_session)
  1504. # Auto-start virtual printer if enabled
  1505. async with async_session() as db:
  1506. from backend.app.api.routes.settings import get_setting
  1507. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1508. if vp_enabled and vp_enabled.lower() == "true":
  1509. vp_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1510. vp_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  1511. vp_model = await get_setting(db, "virtual_printer_model") or ""
  1512. if vp_access_code:
  1513. try:
  1514. await virtual_printer_manager.configure(
  1515. enabled=True,
  1516. access_code=vp_access_code,
  1517. mode=vp_mode,
  1518. model=vp_model,
  1519. )
  1520. logging.info(f"Virtual printer started (model={vp_model or 'default'})")
  1521. except Exception as e:
  1522. logging.warning(f"Failed to start virtual printer: {e}")
  1523. yield
  1524. # Shutdown
  1525. print_scheduler.stop()
  1526. smart_plug_manager.stop_scheduler()
  1527. notification_service.stop_digest_scheduler()
  1528. stop_ams_history_recording()
  1529. stop_runtime_tracking()
  1530. printer_manager.disconnect_all()
  1531. await close_spoolman_client()
  1532. # Stop virtual printer if running
  1533. if virtual_printer_manager.is_enabled:
  1534. await virtual_printer_manager.configure(enabled=False)
  1535. app = FastAPI(
  1536. title=app_settings.app_name,
  1537. description="Archive and manage Bambu Lab 3MF files",
  1538. version=APP_VERSION,
  1539. lifespan=lifespan,
  1540. )
  1541. # API routes
  1542. app.include_router(printers.router, prefix=app_settings.api_prefix)
  1543. app.include_router(archives.router, prefix=app_settings.api_prefix)
  1544. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  1545. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  1546. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  1547. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  1548. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  1549. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  1550. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  1551. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  1552. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  1553. app.include_router(updates.router, prefix=app_settings.api_prefix)
  1554. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  1555. app.include_router(camera.router, prefix=app_settings.api_prefix)
  1556. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  1557. app.include_router(projects.router, prefix=app_settings.api_prefix)
  1558. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  1559. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  1560. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  1561. app.include_router(system.router, prefix=app_settings.api_prefix)
  1562. app.include_router(support.router, prefix=app_settings.api_prefix)
  1563. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  1564. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  1565. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  1566. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  1567. # Serve static files (React build)
  1568. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  1569. app.mount(
  1570. "/assets",
  1571. StaticFiles(directory=app_settings.static_dir / "assets"),
  1572. name="assets",
  1573. )
  1574. if (app_settings.static_dir / "img").exists():
  1575. app.mount(
  1576. "/img",
  1577. StaticFiles(directory=app_settings.static_dir / "img"),
  1578. name="img",
  1579. )
  1580. if (app_settings.static_dir / "icons").exists():
  1581. app.mount(
  1582. "/icons",
  1583. StaticFiles(directory=app_settings.static_dir / "icons"),
  1584. name="icons",
  1585. )
  1586. @app.get("/")
  1587. async def serve_frontend():
  1588. """Serve the React frontend."""
  1589. index_file = app_settings.static_dir / "index.html"
  1590. if index_file.exists():
  1591. return FileResponse(index_file)
  1592. return {
  1593. "message": "Bambuddy API",
  1594. "docs": "/docs",
  1595. "frontend": "Build and place React app in /static directory",
  1596. }
  1597. @app.get("/health")
  1598. async def health_check():
  1599. """Health check endpoint."""
  1600. return {"status": "healthy"}
  1601. @app.get("/manifest.json")
  1602. async def serve_manifest():
  1603. """Serve PWA manifest."""
  1604. manifest_file = app_settings.static_dir / "manifest.json"
  1605. if manifest_file.exists():
  1606. return FileResponse(manifest_file, media_type="application/manifest+json")
  1607. return {"error": "Manifest not found"}
  1608. @app.get("/sw.js")
  1609. async def serve_service_worker():
  1610. """Serve service worker."""
  1611. sw_file = app_settings.static_dir / "sw.js"
  1612. if sw_file.exists():
  1613. return FileResponse(sw_file, media_type="application/javascript")
  1614. return {"error": "Service worker not found"}
  1615. # Catch-all route for React Router (must be last)
  1616. @app.get("/{full_path:path}")
  1617. async def serve_spa(full_path: str):
  1618. """Serve React app for client-side routing."""
  1619. # Don't intercept API routes
  1620. if full_path.startswith("api/"):
  1621. return {"error": "Not found"}
  1622. index_file = app_settings.static_dir / "index.html"
  1623. if index_file.exists():
  1624. return FileResponse(index_file)
  1625. return {"error": "Frontend not built"}