main.py 85 KB

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