main.py 82 KB

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