main.py 57 KB

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