main.py 84 KB

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