main.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. import asyncio
  2. import logging
  3. import os
  4. from datetime import datetime, timedelta
  5. from contextlib import asynccontextmanager
  6. from pathlib import Path
  7. from logging.handlers import RotatingFileHandler
  8. from fastapi import FastAPI
  9. # Import settings first for logging configuration
  10. from backend.app.core.config import settings as app_settings, APP_VERSION
  11. # Configure logging based on settings
  12. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  13. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  14. log_level = getattr(logging, log_level_str, logging.INFO)
  15. log_format = '%(asctime)s %(levelname)s [%(name)s] %(message)s'
  16. # Create root logger
  17. root_logger = logging.getLogger()
  18. root_logger.setLevel(log_level)
  19. # Console handler - always enabled
  20. console_handler = logging.StreamHandler()
  21. console_handler.setLevel(log_level)
  22. console_handler.setFormatter(logging.Formatter(log_format))
  23. root_logger.addHandler(console_handler)
  24. # File handler - only in production or if explicitly enabled
  25. if app_settings.log_to_file:
  26. log_file = app_settings.log_dir / "bambuddy.log"
  27. file_handler = RotatingFileHandler(
  28. log_file,
  29. maxBytes=5*1024*1024, # 5MB
  30. backupCount=3,
  31. encoding='utf-8'
  32. )
  33. file_handler.setLevel(log_level)
  34. file_handler.setFormatter(logging.Formatter(log_format))
  35. root_logger.addHandler(file_handler)
  36. logging.info(f"Logging to file: {log_file}")
  37. # Reduce noise from third-party libraries in production
  38. if not app_settings.debug:
  39. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  40. logging.getLogger("httpcore").setLevel(logging.WARNING)
  41. logging.getLogger("httpx").setLevel(logging.WARNING)
  42. logging.info(f"Bambuddy starting - debug={app_settings.debug}, log_level={log_level_str}")
  43. from fastapi.staticfiles import StaticFiles
  44. from fastapi.responses import FileResponse
  45. from backend.app.core.database import init_db, async_session
  46. from sqlalchemy import select, or_, delete
  47. from backend.app.core.websocket import ws_manager
  48. from backend.app.api.routes import printers, archives, websocket, filaments, cloud, smart_plugs, print_queue, kprofiles, notifications, notification_templates, spoolman, updates, maintenance, camera, external_links, projects, api_keys, webhook, ams_history, system
  49. from backend.app.api.routes import settings as settings_routes
  50. from backend.app.services.notification_service import notification_service
  51. from backend.app.services.printer_manager import (
  52. printer_manager,
  53. printer_state_to_dict,
  54. init_printer_connections,
  55. )
  56. from backend.app.services.print_scheduler import scheduler as print_scheduler
  57. from backend.app.services.bambu_mqtt import PrinterState
  58. from backend.app.services.archive import ArchiveService
  59. from backend.app.services.bambu_ftp import download_file_async
  60. from backend.app.services.smart_plug_manager import smart_plug_manager
  61. from backend.app.services.tasmota import tasmota_service
  62. from backend.app.models.smart_plug import SmartPlug
  63. from backend.app.services.spoolman import get_spoolman_client, init_spoolman_client, close_spoolman_client
  64. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  65. from backend.app.services.telemetry import start_telemetry_loop
  66. # Track active prints: {(printer_id, filename): archive_id}
  67. _active_prints: dict[tuple[int, str], int] = {}
  68. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  69. # {(printer_id, filename): archive_id}
  70. _expected_prints: dict[tuple[int, str], int] = {}
  71. # Track starting energy for prints: {archive_id: starting_kwh}
  72. _print_energy_start: dict[int, float] = {}
  73. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  74. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  75. # Store with multiple filename variations to catch different naming patterns
  76. _expected_prints[(printer_id, filename)] = archive_id
  77. # Also store without .3mf extension if present
  78. if filename.endswith(".3mf"):
  79. base = filename[:-4]
  80. _expected_prints[(printer_id, base)] = archive_id
  81. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  82. logging.getLogger(__name__).info(
  83. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  84. )
  85. _last_status_broadcast: dict[int, str] = {}
  86. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  87. async def _report_spoolman_usage(printer_id: int, archive_id: int, logger):
  88. """Report filament usage to Spoolman after print completion.
  89. This finds the spool by RFID tag_uid from current AMS state and reports
  90. the filament_used_grams from the archive metadata.
  91. """
  92. async with async_session() as db:
  93. from backend.app.api.routes.settings import get_setting
  94. from backend.app.models.archive import PrintArchive
  95. # Check if Spoolman is enabled
  96. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  97. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  98. return
  99. # Get Spoolman URL
  100. spoolman_url = await get_setting(db, "spoolman_url")
  101. if not spoolman_url:
  102. return
  103. # Get or create Spoolman client
  104. client = await get_spoolman_client()
  105. if not client:
  106. client = await init_spoolman_client(spoolman_url)
  107. # Check if Spoolman is reachable
  108. if not await client.health_check():
  109. logger.warning(f"Spoolman not reachable for usage reporting")
  110. return
  111. # Get archive to find filament usage
  112. result = await db.execute(
  113. select(PrintArchive).where(PrintArchive.id == archive_id)
  114. )
  115. archive = result.scalar_one_or_none()
  116. if not archive or not archive.filament_used_grams:
  117. logger.debug(f"No filament usage data for archive {archive_id}")
  118. return
  119. filament_used = archive.filament_used_grams
  120. logger.info(f"[SPOOLMAN] Archive {archive_id} used {filament_used}g of filament")
  121. # Get current AMS state from printer to find the active spool
  122. state = printer_manager.get_status(printer_id)
  123. if not state or not state.raw_data:
  124. logger.debug(f"No printer state available for usage reporting")
  125. return
  126. ams_data = state.raw_data.get("ams")
  127. if not ams_data:
  128. logger.debug(f"No AMS data available for usage reporting")
  129. return
  130. # Find spools with RFID tags in Spoolman and report usage
  131. # For now, we report usage to the first spool found with a matching tag
  132. # TODO: In future, track which specific trays were used during the print
  133. spools_updated = 0
  134. for ams_unit in ams_data:
  135. ams_id = int(ams_unit.get("id", 0))
  136. trays = ams_unit.get("tray", [])
  137. for tray_data in trays:
  138. tag_uid = tray_data.get("tag_uid")
  139. if not tag_uid:
  140. continue
  141. # Find spool in Spoolman by tag
  142. spool = await client.find_spool_by_tag(tag_uid)
  143. if spool:
  144. # Report usage to Spoolman
  145. result = await client.use_spool(spool["id"], filament_used)
  146. if result:
  147. logger.info(
  148. f"[SPOOLMAN] Reported {filament_used}g usage to spool {spool['id']} "
  149. f"(tag: {tag_uid})"
  150. )
  151. spools_updated += 1
  152. # Only report to one spool for single-material prints
  153. # Multi-material prints would need more sophisticated tracking
  154. return
  155. if spools_updated == 0:
  156. logger.debug(f"No matching Spoolman spools found for printer {printer_id}")
  157. async def on_printer_status_change(printer_id: int, state: PrinterState):
  158. """Handle printer status changes - broadcast via WebSocket."""
  159. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  160. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  161. temps = state.temperatures or {}
  162. nozzle_temp = round(temps.get("nozzle", 0))
  163. bed_temp = round(temps.get("bed", 0))
  164. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  165. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  166. # Auto-detect dual-nozzle printers from MQTT temperature data
  167. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  168. _nozzle_count_updated.add(printer_id)
  169. # Update nozzle_count in database
  170. async with async_session() as db:
  171. from backend.app.models.printer import Printer
  172. result = await db.execute(
  173. select(Printer).where(Printer.id == printer_id)
  174. )
  175. printer = result.scalar_one_or_none()
  176. if printer and printer.nozzle_count != 2:
  177. printer.nozzle_count = 2
  178. await db.commit()
  179. logging.getLogger(__name__).info(
  180. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  181. )
  182. status_key = (
  183. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  184. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}"
  185. )
  186. if _last_status_broadcast.get(printer_id) == status_key:
  187. return # No change, skip broadcast
  188. _last_status_broadcast[printer_id] = status_key
  189. await ws_manager.send_printer_status(
  190. printer_id,
  191. printer_state_to_dict(state, printer_id),
  192. )
  193. async def on_ams_change(printer_id: int, ams_data: list):
  194. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  195. import logging
  196. logger = logging.getLogger(__name__)
  197. try:
  198. async with async_session() as db:
  199. from backend.app.api.routes.settings import get_setting
  200. from backend.app.models.printer import Printer
  201. # Check if Spoolman is enabled
  202. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  203. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  204. return
  205. # Check sync mode
  206. sync_mode = await get_setting(db, "spoolman_sync_mode")
  207. if sync_mode and sync_mode != "auto":
  208. return # Only sync on auto mode
  209. # Get Spoolman URL
  210. spoolman_url = await get_setting(db, "spoolman_url")
  211. if not spoolman_url:
  212. return
  213. # Get or create Spoolman client
  214. client = await get_spoolman_client()
  215. if not client:
  216. client = await init_spoolman_client(spoolman_url)
  217. # Check if Spoolman is reachable
  218. if not await client.health_check():
  219. logger.warning(f"Spoolman not reachable at {spoolman_url}")
  220. return
  221. # Get printer name for location
  222. result = await db.execute(
  223. select(Printer).where(Printer.id == printer_id)
  224. )
  225. printer = result.scalar_one_or_none()
  226. printer_name = printer.name if printer else f"Printer {printer_id}"
  227. # Sync each AMS tray
  228. synced = 0
  229. for ams_unit in ams_data:
  230. ams_id = int(ams_unit.get("id", 0))
  231. trays = ams_unit.get("tray", [])
  232. for tray_data in trays:
  233. tray = client.parse_ams_tray(ams_id, tray_data)
  234. if not tray:
  235. continue # Empty tray
  236. try:
  237. result = await client.sync_ams_tray(tray, printer_name)
  238. if result:
  239. synced += 1
  240. except Exception as e:
  241. logger.error(f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}")
  242. if synced > 0:
  243. logger.info(f"Auto-synced {synced} AMS trays to Spoolman for printer {printer_id}")
  244. except Exception as e:
  245. import logging
  246. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  247. async def on_print_start(printer_id: int, data: dict):
  248. """Handle print start - archive the 3MF file immediately."""
  249. import logging
  250. logger = logging.getLogger(__name__)
  251. await ws_manager.send_print_start(printer_id, data)
  252. # Send print start notifications FIRST (before any early returns)
  253. try:
  254. async with async_session() as db:
  255. from backend.app.models.printer import Printer
  256. result = await db.execute(
  257. select(Printer).where(Printer.id == printer_id)
  258. )
  259. printer = result.scalar_one_or_none()
  260. printer_name = printer.name if printer else f"Printer {printer_id}"
  261. await notification_service.on_print_start(printer_id, printer_name, data, db)
  262. except Exception as e:
  263. logger.warning(f"Notification on_print_start failed: {e}")
  264. # Smart plug automation: turn on plug when print starts
  265. try:
  266. async with async_session() as db:
  267. await smart_plug_manager.on_print_start(printer_id, db)
  268. except Exception as e:
  269. logger.warning(f"Smart plug on_print_start failed: {e}")
  270. async with async_session() as db:
  271. from backend.app.models.printer import Printer
  272. from backend.app.services.bambu_ftp import list_files_async
  273. result = await db.execute(
  274. select(Printer).where(Printer.id == printer_id)
  275. )
  276. printer = result.scalar_one_or_none()
  277. if not printer or not printer.auto_archive:
  278. return
  279. # Get the filename and subtask_name
  280. filename = data.get("filename", "")
  281. subtask_name = data.get("subtask_name", "")
  282. logger.info(f"Print start detected - filename: {filename}, subtask: {subtask_name}")
  283. if not filename and not subtask_name:
  284. return
  285. # Check if this is an expected print from reprint/scheduled
  286. # Build list of possible keys to check
  287. expected_keys = []
  288. if subtask_name:
  289. expected_keys.append((printer_id, subtask_name))
  290. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  291. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  292. if filename:
  293. fname = filename.split("/")[-1] if "/" in filename else filename
  294. expected_keys.append((printer_id, fname))
  295. # Strip extensions to match
  296. base = fname.replace(".gcode", "").replace(".3mf", "")
  297. expected_keys.append((printer_id, base))
  298. expected_keys.append((printer_id, f"{base}.3mf"))
  299. expected_archive_id = None
  300. for key in expected_keys:
  301. expected_archive_id = _expected_prints.pop(key, None)
  302. if expected_archive_id:
  303. # Clean up other possible keys for this print
  304. for other_key in expected_keys:
  305. _expected_prints.pop(other_key, None)
  306. break
  307. if expected_archive_id:
  308. # This is a reprint/scheduled print - use existing archive, don't create new one
  309. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  310. from backend.app.models.archive import PrintArchive
  311. from datetime import datetime
  312. result = await db.execute(
  313. select(PrintArchive).where(PrintArchive.id == expected_archive_id)
  314. )
  315. archive = result.scalar_one_or_none()
  316. if archive:
  317. # Update archive status to printing
  318. archive.status = "printing"
  319. archive.started_at = datetime.now()
  320. await db.commit()
  321. # Track as active print
  322. _active_prints[(printer_id, archive.filename)] = archive.id
  323. if subtask_name:
  324. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  325. # Set up energy tracking
  326. try:
  327. plug_result = await db.execute(
  328. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  329. )
  330. plug = plug_result.scalar_one_or_none()
  331. logger.info(f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}")
  332. if plug:
  333. energy = await tasmota_service.get_energy(plug)
  334. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  335. if energy and energy.get("total") is not None:
  336. _print_energy_start[archive.id] = energy["total"]
  337. logger.info(f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  338. else:
  339. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  340. else:
  341. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  342. except Exception as e:
  343. logger.warning(f"Failed to record starting energy: {e}")
  344. await ws_manager.send_archive_updated({
  345. "id": archive.id,
  346. "status": "printing",
  347. })
  348. return # Skip creating a new archive
  349. # Check if there's already a "printing" archive for this printer/file
  350. # This prevents duplicates when backend restarts during an active print
  351. from backend.app.models.archive import PrintArchive
  352. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  353. existing = await db.execute(
  354. select(PrintArchive)
  355. .where(PrintArchive.printer_id == printer_id)
  356. .where(PrintArchive.status == "printing")
  357. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  358. .order_by(PrintArchive.created_at.desc())
  359. .limit(1)
  360. )
  361. existing_archive = existing.scalar_one_or_none()
  362. if existing_archive:
  363. logger.info(f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}")
  364. # Track this as the active print
  365. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  366. # Also set up energy tracking if not already tracked
  367. if existing_archive.id not in _print_energy_start:
  368. try:
  369. plug_result = await db.execute(
  370. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  371. )
  372. plug = plug_result.scalar_one_or_none()
  373. if plug:
  374. energy = await tasmota_service.get_energy(plug)
  375. if energy and energy.get("total") is not None:
  376. _print_energy_start[existing_archive.id] = energy["total"]
  377. logger.info(f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh")
  378. except Exception as e:
  379. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  380. return
  381. # Build list of possible 3MF filenames to try
  382. possible_names = []
  383. # Bambu printers typically store files as "Name.gcode.3mf"
  384. # The subtask_name is usually the best source for the filename
  385. if subtask_name:
  386. # Try common Bambu naming patterns
  387. possible_names.append(f"{subtask_name}.gcode.3mf")
  388. possible_names.append(f"{subtask_name}.3mf")
  389. # Try original filename with .3mf extension
  390. if filename:
  391. # Extract just the filename part, not the full path
  392. fname = filename.split("/")[-1] if "/" in filename else filename
  393. if fname.endswith(".3mf"):
  394. possible_names.append(fname)
  395. elif fname.endswith(".gcode"):
  396. base = fname.rsplit(".", 1)[0]
  397. possible_names.append(f"{base}.gcode.3mf")
  398. possible_names.append(f"{base}.3mf")
  399. else:
  400. possible_names.append(f"{fname}.gcode.3mf")
  401. possible_names.append(f"{fname}.3mf")
  402. # Remove duplicates while preserving order
  403. seen = set()
  404. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  405. logger.info(f"Trying filenames: {possible_names}")
  406. # Try to find and download the 3MF file
  407. temp_path = None
  408. downloaded_filename = None
  409. for try_filename in possible_names:
  410. if not try_filename.endswith(".3mf"):
  411. continue
  412. remote_paths = [
  413. f"/cache/{try_filename}",
  414. f"/model/{try_filename}",
  415. f"/{try_filename}",
  416. ]
  417. temp_path = app_settings.archive_dir / "temp" / try_filename
  418. temp_path.parent.mkdir(parents=True, exist_ok=True)
  419. for remote_path in remote_paths:
  420. logger.debug(f"Trying FTP download: {remote_path}")
  421. try:
  422. if await download_file_async(
  423. printer.ip_address,
  424. printer.access_code,
  425. remote_path,
  426. temp_path,
  427. ):
  428. downloaded_filename = try_filename
  429. logger.info(f"Downloaded: {remote_path}")
  430. break
  431. except Exception as e:
  432. logger.debug(f"FTP download failed for {remote_path}: {e}")
  433. if downloaded_filename:
  434. break
  435. # If still not found, try listing /cache to find matching file
  436. if not downloaded_filename and (filename or subtask_name):
  437. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  438. try:
  439. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  440. for f in cache_files:
  441. if f.get("is_directory"):
  442. continue
  443. fname = f.get("name", "")
  444. if fname.endswith(".3mf") and search_term in fname.lower():
  445. temp_path = app_settings.archive_dir / "temp" / fname
  446. temp_path.parent.mkdir(parents=True, exist_ok=True)
  447. if await download_file_async(
  448. printer.ip_address,
  449. printer.access_code,
  450. f"/cache/{fname}",
  451. temp_path,
  452. ):
  453. downloaded_filename = fname
  454. logger.info(f"Found and downloaded from cache: {fname}")
  455. break
  456. except Exception as e:
  457. logger.warning(f"Failed to list cache: {e}")
  458. if not downloaded_filename or not temp_path:
  459. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  460. return
  461. try:
  462. # Archive the file with status "printing"
  463. service = ArchiveService(db)
  464. archive = await service.archive_print(
  465. printer_id=printer_id,
  466. source_file=temp_path,
  467. print_data={**data, "status": "printing"},
  468. )
  469. if archive:
  470. # Track this active print (use both original filename and downloaded filename)
  471. _active_prints[(printer_id, downloaded_filename)] = archive.id
  472. if filename and filename != downloaded_filename:
  473. _active_prints[(printer_id, filename)] = archive.id
  474. if subtask_name:
  475. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  476. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  477. # Record starting energy from smart plug if available
  478. try:
  479. plug_result = await db.execute(
  480. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  481. )
  482. plug = plug_result.scalar_one_or_none()
  483. logger.info(f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}")
  484. if plug:
  485. energy = await tasmota_service.get_energy(plug)
  486. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  487. if energy and energy.get("total") is not None:
  488. _print_energy_start[archive.id] = energy["total"]
  489. logger.info(f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  490. else:
  491. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  492. else:
  493. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  494. except Exception as e:
  495. logger.warning(f"Failed to record starting energy: {e}")
  496. await ws_manager.send_archive_created({
  497. "id": archive.id,
  498. "printer_id": archive.printer_id,
  499. "filename": archive.filename,
  500. "print_name": archive.print_name,
  501. "status": archive.status,
  502. })
  503. finally:
  504. if temp_path and temp_path.exists():
  505. temp_path.unlink()
  506. async def on_print_complete(printer_id: int, data: dict):
  507. """Handle print completion - update the archive status."""
  508. import logging
  509. logger = logging.getLogger(__name__)
  510. await ws_manager.send_print_complete(printer_id, data)
  511. filename = data.get("filename", "")
  512. subtask_name = data.get("subtask_name", "")
  513. if not filename and not subtask_name:
  514. logger.warning(f"Print complete without filename or subtask_name")
  515. return
  516. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  517. # Build list of possible keys to try (matching how they were registered in on_print_start)
  518. possible_keys = []
  519. # Try subtask_name variations first (most reliable for matching)
  520. if subtask_name:
  521. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  522. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  523. possible_keys.append((printer_id, subtask_name))
  524. # Try filename variations
  525. if filename:
  526. # Extract just the filename if it's a path
  527. fname = filename.split("/")[-1] if "/" in filename else filename
  528. if fname.endswith(".3mf"):
  529. possible_keys.append((printer_id, fname))
  530. elif fname.endswith(".gcode"):
  531. base_name = fname.rsplit(".", 1)[0]
  532. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  533. possible_keys.append((printer_id, f"{base_name}.3mf"))
  534. possible_keys.append((printer_id, fname))
  535. else:
  536. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  537. possible_keys.append((printer_id, f"{fname}.3mf"))
  538. possible_keys.append((printer_id, fname))
  539. # Also try full path versions
  540. if filename.endswith(".3mf"):
  541. possible_keys.append((printer_id, filename))
  542. elif filename.endswith(".gcode"):
  543. base_name = filename.rsplit(".", 1)[0]
  544. possible_keys.append((printer_id, f"{base_name}.3mf"))
  545. possible_keys.append((printer_id, filename))
  546. else:
  547. possible_keys.append((printer_id, f"{filename}.3mf"))
  548. possible_keys.append((printer_id, filename))
  549. # Find the archive for this print
  550. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  551. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  552. archive_id = None
  553. for key in possible_keys:
  554. archive_id = _active_prints.pop(key, None)
  555. if archive_id:
  556. logger.info(f"Found archive {archive_id} with key {key}")
  557. # Also clean up any other keys pointing to this archive
  558. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  559. for k in keys_to_remove:
  560. _active_prints.pop(k, None)
  561. break
  562. if not archive_id:
  563. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  564. async with async_session() as db:
  565. from backend.app.models.archive import PrintArchive
  566. # Try matching by subtask_name (stored as print_name) first
  567. if subtask_name:
  568. result = await db.execute(
  569. select(PrintArchive)
  570. .where(PrintArchive.printer_id == printer_id)
  571. .where(PrintArchive.status == "printing")
  572. .where(or_(
  573. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  574. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  575. ))
  576. .order_by(PrintArchive.created_at.desc())
  577. .limit(1)
  578. )
  579. archive = result.scalar_one_or_none()
  580. if archive:
  581. archive_id = archive.id
  582. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  583. # Also try by filename
  584. if not archive_id and filename:
  585. result = await db.execute(
  586. select(PrintArchive)
  587. .where(PrintArchive.printer_id == printer_id)
  588. .where(PrintArchive.filename == filename)
  589. .where(PrintArchive.status == "printing")
  590. .order_by(PrintArchive.created_at.desc())
  591. .limit(1)
  592. )
  593. archive = result.scalar_one_or_none()
  594. if archive:
  595. archive_id = archive.id
  596. if not archive_id:
  597. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  598. return
  599. # Update archive status
  600. async with async_session() as db:
  601. service = ArchiveService(db)
  602. status = data.get("status", "completed")
  603. await service.update_archive_status(
  604. archive_id,
  605. status=status,
  606. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  607. )
  608. await ws_manager.send_archive_updated({
  609. "id": archive_id,
  610. "status": status,
  611. })
  612. # Report filament usage to Spoolman if print completed successfully
  613. if data.get("status") == "completed":
  614. try:
  615. await _report_spoolman_usage(printer_id, archive_id, logger)
  616. except Exception as e:
  617. logger.warning(f"Spoolman usage reporting failed: {e}")
  618. # Calculate energy used for this print (always per-print: end - start)
  619. try:
  620. starting_kwh = _print_energy_start.pop(archive_id, None)
  621. logger.info(f"[ENERGY] Print complete for archive {archive_id}, starting_kwh={starting_kwh}")
  622. async with async_session() as db:
  623. # Get smart plug for this printer (SmartPlug is imported at module level)
  624. plug_result = await db.execute(
  625. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  626. )
  627. plug = plug_result.scalar_one_or_none()
  628. if plug:
  629. energy = await tasmota_service.get_energy(plug)
  630. logger.info(f"[ENERGY] Print complete - energy response: {energy}")
  631. energy_used = None
  632. # Calculate per-print energy: end total - start total
  633. if starting_kwh is not None and energy and energy.get("total") is not None:
  634. ending_kwh = energy["total"]
  635. energy_used = round(ending_kwh - starting_kwh, 4)
  636. logger.info(f"[ENERGY] Per-print energy: ending={ending_kwh}, starting={starting_kwh}, used={energy_used}")
  637. elif starting_kwh is None:
  638. logger.info(f"[ENERGY] No starting energy recorded for this archive")
  639. else:
  640. logger.warning(f"[ENERGY] No 'total' in ending energy response")
  641. if energy_used is not None and energy_used >= 0:
  642. # Get energy cost per kWh from settings (default to 0.15)
  643. from backend.app.api.routes.settings import get_setting
  644. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  645. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  646. energy_cost = round(energy_used * cost_per_kwh, 2)
  647. # Update archive with energy data
  648. from backend.app.models.archive import PrintArchive
  649. result = await db.execute(
  650. select(PrintArchive).where(PrintArchive.id == archive_id)
  651. )
  652. archive = result.scalar_one_or_none()
  653. if archive:
  654. archive.energy_kwh = energy_used
  655. archive.energy_cost = energy_cost
  656. await db.commit()
  657. logger.info(f"[ENERGY] Saved to archive {archive_id}: {energy_used} kWh, cost={energy_cost}")
  658. else:
  659. logger.warning(f"[ENERGY] Archive {archive_id} not found when saving energy")
  660. else:
  661. logger.info(f"[ENERGY] No smart plug found for printer {printer_id} at print complete")
  662. except Exception as e:
  663. import logging
  664. logging.getLogger(__name__).warning(f"Failed to calculate energy: {e}")
  665. # Capture finish photo from printer camera
  666. logger.info(f"[PHOTO] Starting finish photo capture for archive {archive_id}")
  667. try:
  668. async with async_session() as db:
  669. # Check if finish photo capture is enabled
  670. from backend.app.api.routes.settings import get_setting
  671. capture_enabled = await get_setting(db, "capture_finish_photo")
  672. logger.info(f"[PHOTO] capture_finish_photo setting: {capture_enabled}")
  673. if capture_enabled is None or capture_enabled.lower() == "true":
  674. # Get printer details
  675. from backend.app.models.printer import Printer
  676. result = await db.execute(
  677. select(Printer).where(Printer.id == printer_id)
  678. )
  679. printer = result.scalar_one_or_none()
  680. if printer and archive_id:
  681. # Get archive to find its directory
  682. from backend.app.models.archive import PrintArchive
  683. result = await db.execute(
  684. select(PrintArchive).where(PrintArchive.id == archive_id)
  685. )
  686. archive = result.scalar_one_or_none()
  687. if archive:
  688. from backend.app.services.camera import capture_finish_photo
  689. from pathlib import Path
  690. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  691. photo_filename = await capture_finish_photo(
  692. printer_id=printer_id,
  693. ip_address=printer.ip_address,
  694. access_code=printer.access_code,
  695. model=printer.model,
  696. archive_dir=archive_dir,
  697. )
  698. if photo_filename:
  699. # Add photo to archive's photos list
  700. photos = archive.photos or []
  701. photos.append(photo_filename)
  702. archive.photos = photos
  703. await db.commit()
  704. logger.info(f"Added finish photo to archive {archive_id}: {photo_filename}")
  705. except Exception as e:
  706. import logging
  707. logging.getLogger(__name__).warning(f"Finish photo capture failed: {e}")
  708. # Smart plug automation: schedule turn off when print completes
  709. logger.info(f"[AUTO-OFF] Calling smart_plug_manager.on_print_complete for printer {printer_id}")
  710. try:
  711. async with async_session() as db:
  712. status = data.get("status", "completed")
  713. await smart_plug_manager.on_print_complete(printer_id, status, db)
  714. logger.info(f"[AUTO-OFF] smart_plug_manager.on_print_complete completed")
  715. except Exception as e:
  716. import logging
  717. logging.getLogger(__name__).warning(f"Smart plug on_print_complete failed: {e}")
  718. # Send print complete notifications
  719. try:
  720. async with async_session() as db:
  721. from backend.app.models.printer import Printer
  722. result = await db.execute(
  723. select(Printer).where(Printer.id == printer_id)
  724. )
  725. printer = result.scalar_one_or_none()
  726. printer_name = printer.name if printer else f"Printer {printer_id}"
  727. status = data.get("status", "completed")
  728. # on_print_complete handles all status types: completed, failed, aborted, stopped
  729. await notification_service.on_print_complete(
  730. printer_id, printer_name, status, data, db
  731. )
  732. except Exception as e:
  733. import logging
  734. logging.getLogger(__name__).warning(f"Notification on_print_complete failed: {e}")
  735. # Check for maintenance due and send notifications (only for completed prints)
  736. if data.get("status") == "completed":
  737. try:
  738. async with async_session() as db:
  739. from backend.app.models.printer import Printer
  740. # Get printer name
  741. result = await db.execute(
  742. select(Printer).where(Printer.id == printer_id)
  743. )
  744. printer = result.scalar_one_or_none()
  745. printer_name = printer.name if printer else f"Printer {printer_id}"
  746. # Get maintenance overview for this printer
  747. await ensure_default_types(db)
  748. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  749. # Check for any items that are due or have warnings
  750. items_needing_attention = [
  751. {
  752. "name": item.maintenance_type_name,
  753. "is_due": item.is_due,
  754. "is_warning": item.is_warning,
  755. }
  756. for item in overview.maintenance_items
  757. if item.enabled and (item.is_due or item.is_warning)
  758. ]
  759. if items_needing_attention:
  760. await notification_service.on_maintenance_due(
  761. printer_id, printer_name, items_needing_attention, db
  762. )
  763. logger.info(
  764. f"Sent maintenance notification for printer {printer_id}: "
  765. f"{len(items_needing_attention)} items need attention"
  766. )
  767. except Exception as e:
  768. import logging
  769. logging.getLogger(__name__).warning(f"Maintenance notification check failed: {e}")
  770. # Update queue item if this was a scheduled print
  771. try:
  772. async with async_session() as db:
  773. from backend.app.models.print_queue import PrintQueueItem
  774. # Note: SmartPlug is already imported at module level (line 56)
  775. # Do NOT import it here as it would shadow the module-level import
  776. # and cause "cannot access local variable" errors earlier in this function
  777. result = await db.execute(
  778. select(PrintQueueItem)
  779. .where(PrintQueueItem.printer_id == printer_id)
  780. .where(PrintQueueItem.status == "printing")
  781. )
  782. queue_item = result.scalar_one_or_none()
  783. if queue_item:
  784. status = data.get("status", "completed")
  785. queue_item.status = status
  786. queue_item.completed_at = datetime.now()
  787. await db.commit()
  788. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  789. # Handle auto_off_after - power off printer if requested (after cooldown)
  790. if queue_item.auto_off_after:
  791. result = await db.execute(
  792. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  793. )
  794. plug = result.scalar_one_or_none()
  795. if plug and plug.enabled:
  796. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  797. async def cooldown_and_poweroff(pid: int, plug_id: int):
  798. # Wait for nozzle to cool down
  799. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  800. # Re-fetch plug in new session
  801. async with async_session() as new_db:
  802. result = await new_db.execute(
  803. select(SmartPlug).where(SmartPlug.id == plug_id)
  804. )
  805. p = result.scalar_one_or_none()
  806. if p and p.enabled:
  807. success = await tasmota_service.turn_off(p)
  808. if success:
  809. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  810. else:
  811. logger.warning(f"Failed to power off printer {pid} via smart plug")
  812. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  813. except Exception as e:
  814. import logging
  815. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  816. # AMS sensor history recording
  817. _ams_history_task: asyncio.Task | None = None
  818. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  819. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  820. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  821. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  822. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  823. async def record_ams_history():
  824. """Background task to record AMS humidity and temperature data."""
  825. import logging
  826. logger = logging.getLogger(__name__)
  827. # Wait a short time for MQTT connections to establish on startup
  828. await asyncio.sleep(10)
  829. while True:
  830. try:
  831. from backend.app.models.ams_history import AMSSensorHistory
  832. from backend.app.models.printer import Printer
  833. from backend.app.models.settings import Settings
  834. async with async_session() as db:
  835. # Get all active printers
  836. result = await db.execute(
  837. select(Printer).where(Printer.is_active == True)
  838. )
  839. printers = result.scalars().all()
  840. # Get alarm thresholds from settings
  841. humidity_threshold = 60.0 # Default: fair threshold
  842. temp_threshold = 35.0 # Default: fair threshold
  843. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  844. setting = result.scalar_one_or_none()
  845. if setting:
  846. try:
  847. humidity_threshold = float(setting.value)
  848. except (ValueError, TypeError):
  849. pass
  850. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  851. setting = result.scalar_one_or_none()
  852. if setting:
  853. try:
  854. temp_threshold = float(setting.value)
  855. except (ValueError, TypeError):
  856. pass
  857. recorded_count = 0
  858. for printer in printers:
  859. # Get current state from printer manager
  860. state = printer_manager.get_status(printer.id)
  861. if not state or not state.raw_data:
  862. continue
  863. raw_data = state.raw_data
  864. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  865. continue
  866. # Record data for each AMS unit
  867. for ams_data in raw_data["ams"]:
  868. ams_id = int(ams_data.get("id", 0))
  869. # Get humidity (prefer humidity_raw)
  870. humidity_raw = ams_data.get("humidity_raw")
  871. humidity_idx = ams_data.get("humidity")
  872. humidity = None
  873. if humidity_raw is not None:
  874. try:
  875. humidity = float(humidity_raw)
  876. except (ValueError, TypeError):
  877. pass
  878. if humidity is None and humidity_idx is not None:
  879. try:
  880. humidity = float(humidity_idx)
  881. except (ValueError, TypeError):
  882. pass
  883. # Get temperature
  884. temperature = None
  885. temp_str = ams_data.get("temp")
  886. if temp_str is not None:
  887. try:
  888. temperature = float(temp_str)
  889. except (ValueError, TypeError):
  890. pass
  891. # Skip if no data
  892. if humidity is None and temperature is None:
  893. continue
  894. # Record the data point
  895. history = AMSSensorHistory(
  896. printer_id=printer.id,
  897. ams_id=ams_id,
  898. humidity=humidity,
  899. humidity_raw=float(humidity_raw) if humidity_raw else None,
  900. temperature=temperature,
  901. )
  902. db.add(history)
  903. recorded_count += 1
  904. # Generate AMS label (A, B, C, D or HT-A for AMS-Lite/Hub)
  905. if ams_id >= 128:
  906. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  907. else:
  908. ams_label = f"AMS-{chr(65 + ams_id)}"
  909. # Check humidity alarm (only if above threshold)
  910. if humidity is not None and humidity > humidity_threshold:
  911. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  912. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  913. now = datetime.now()
  914. if last_alarm is None or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60:
  915. _ams_alarm_cooldown[cooldown_key] = now
  916. logger.info(f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%")
  917. try:
  918. await notification_service.on_ams_humidity_high(
  919. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  920. )
  921. except Exception as e:
  922. logger.warning(f"Failed to send humidity alarm: {e}")
  923. # Check temperature alarm (only if above threshold)
  924. if temperature is not None and temperature > temp_threshold:
  925. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  926. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  927. now = datetime.now()
  928. if last_alarm is None or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60:
  929. _ams_alarm_cooldown[cooldown_key] = now
  930. logger.info(f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C")
  931. try:
  932. await notification_service.on_ams_temperature_high(
  933. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  934. )
  935. except Exception as e:
  936. logger.warning(f"Failed to send temperature alarm: {e}")
  937. await db.commit()
  938. if recorded_count > 0:
  939. logger.info(f"Recorded {recorded_count} AMS sensor history entries")
  940. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  941. global _ams_cleanup_counter
  942. _ams_cleanup_counter += 1
  943. if _ams_cleanup_counter >= 288:
  944. _ams_cleanup_counter = 0
  945. # Get retention days from settings
  946. from backend.app.models.settings import Settings
  947. result = await db.execute(
  948. select(Settings).where(Settings.key == "ams_history_retention_days")
  949. )
  950. setting = result.scalar_one_or_none()
  951. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  952. cutoff = datetime.now() - timedelta(days=retention_days)
  953. result = await db.execute(
  954. delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff)
  955. )
  956. await db.commit()
  957. if result.rowcount > 0:
  958. logger.info(f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)")
  959. # Wait until next recording interval
  960. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  961. except asyncio.CancelledError:
  962. break
  963. except Exception as e:
  964. logger.warning(f"AMS history recording failed: {e}")
  965. await asyncio.sleep(60) # Wait a bit before retrying
  966. def start_ams_history_recording():
  967. """Start the AMS history recording background task."""
  968. global _ams_history_task
  969. if _ams_history_task is None:
  970. _ams_history_task = asyncio.create_task(record_ams_history())
  971. logging.getLogger(__name__).info("AMS history recording started")
  972. def stop_ams_history_recording():
  973. """Stop the AMS history recording background task."""
  974. global _ams_history_task
  975. if _ams_history_task:
  976. _ams_history_task.cancel()
  977. _ams_history_task = None
  978. logging.getLogger(__name__).info("AMS history recording stopped")
  979. @asynccontextmanager
  980. async def lifespan(app: FastAPI):
  981. # Startup
  982. await init_db()
  983. # Set up printer manager callbacks
  984. loop = asyncio.get_event_loop()
  985. printer_manager.set_event_loop(loop)
  986. printer_manager.set_status_change_callback(on_printer_status_change)
  987. printer_manager.set_print_start_callback(on_print_start)
  988. printer_manager.set_print_complete_callback(on_print_complete)
  989. printer_manager.set_ams_change_callback(on_ams_change)
  990. # Connect to all active printers
  991. async with async_session() as db:
  992. await init_printer_connections(db)
  993. # Auto-connect to Spoolman if enabled
  994. async with async_session() as db:
  995. from backend.app.api.routes.settings import get_setting
  996. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  997. spoolman_url = await get_setting(db, "spoolman_url")
  998. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  999. try:
  1000. client = await init_spoolman_client(spoolman_url)
  1001. if await client.health_check():
  1002. logging.info(f"Auto-connected to Spoolman at {spoolman_url}")
  1003. else:
  1004. logging.warning(f"Spoolman at {spoolman_url} is not reachable")
  1005. except Exception as e:
  1006. logging.warning(f"Failed to auto-connect to Spoolman: {e}")
  1007. # Start the print scheduler
  1008. asyncio.create_task(print_scheduler.run())
  1009. # Start the smart plug scheduler for time-based on/off
  1010. smart_plug_manager.start_scheduler()
  1011. # Resume any pending auto-offs that were interrupted by restart
  1012. await smart_plug_manager.resume_pending_auto_offs()
  1013. # Start the notification digest scheduler
  1014. notification_service.start_digest_scheduler()
  1015. # Start AMS history recording
  1016. start_ams_history_recording()
  1017. # Start anonymous telemetry (opt-out via settings)
  1018. asyncio.create_task(start_telemetry_loop(async_session))
  1019. yield
  1020. # Shutdown
  1021. print_scheduler.stop()
  1022. smart_plug_manager.stop_scheduler()
  1023. notification_service.stop_digest_scheduler()
  1024. stop_ams_history_recording()
  1025. printer_manager.disconnect_all()
  1026. await close_spoolman_client()
  1027. app = FastAPI(
  1028. title=app_settings.app_name,
  1029. description="Archive and manage Bambu Lab 3MF files",
  1030. version=APP_VERSION,
  1031. lifespan=lifespan,
  1032. )
  1033. # API routes
  1034. app.include_router(printers.router, prefix=app_settings.api_prefix)
  1035. app.include_router(archives.router, prefix=app_settings.api_prefix)
  1036. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  1037. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  1038. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  1039. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  1040. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  1041. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  1042. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  1043. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  1044. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  1045. app.include_router(updates.router, prefix=app_settings.api_prefix)
  1046. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  1047. app.include_router(camera.router, prefix=app_settings.api_prefix)
  1048. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  1049. app.include_router(projects.router, prefix=app_settings.api_prefix)
  1050. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  1051. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  1052. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  1053. app.include_router(system.router, prefix=app_settings.api_prefix)
  1054. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  1055. # Serve static files (React build)
  1056. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  1057. app.mount(
  1058. "/assets",
  1059. StaticFiles(directory=app_settings.static_dir / "assets"),
  1060. name="assets",
  1061. )
  1062. if (app_settings.static_dir / "img").exists():
  1063. app.mount(
  1064. "/img",
  1065. StaticFiles(directory=app_settings.static_dir / "img"),
  1066. name="img",
  1067. )
  1068. if (app_settings.static_dir / "icons").exists():
  1069. app.mount(
  1070. "/icons",
  1071. StaticFiles(directory=app_settings.static_dir / "icons"),
  1072. name="icons",
  1073. )
  1074. @app.get("/")
  1075. async def serve_frontend():
  1076. """Serve the React frontend."""
  1077. index_file = app_settings.static_dir / "index.html"
  1078. if index_file.exists():
  1079. return FileResponse(index_file)
  1080. return {
  1081. "message": "Bambuddy API",
  1082. "docs": "/docs",
  1083. "frontend": "Build and place React app in /static directory",
  1084. }
  1085. @app.get("/health")
  1086. async def health_check():
  1087. """Health check endpoint."""
  1088. return {"status": "healthy"}
  1089. @app.get("/manifest.json")
  1090. async def serve_manifest():
  1091. """Serve PWA manifest."""
  1092. manifest_file = app_settings.static_dir / "manifest.json"
  1093. if manifest_file.exists():
  1094. return FileResponse(manifest_file, media_type="application/manifest+json")
  1095. return {"error": "Manifest not found"}
  1096. @app.get("/sw.js")
  1097. async def serve_service_worker():
  1098. """Serve service worker."""
  1099. sw_file = app_settings.static_dir / "sw.js"
  1100. if sw_file.exists():
  1101. return FileResponse(sw_file, media_type="application/javascript")
  1102. return {"error": "Service worker not found"}
  1103. # Catch-all route for React Router (must be last)
  1104. @app.get("/{full_path:path}")
  1105. async def serve_spa(full_path: str):
  1106. """Serve React app for client-side routing."""
  1107. # Don't intercept API routes
  1108. if full_path.startswith("api/"):
  1109. return {"error": "Not found"}
  1110. index_file = app_settings.static_dir / "index.html"
  1111. if index_file.exists():
  1112. return FileResponse(index_file)
  1113. return {"error": "Frontend not built"}