main.py 87 KB

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