main.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import asyncio
  2. import logging
  3. import os
  4. from datetime import datetime
  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
  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 / "bambutrack.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"BambuTrack 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_
  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
  49. from backend.app.api.routes import settings as settings_routes
  50. from backend.app.services.printer_manager import (
  51. printer_manager,
  52. printer_state_to_dict,
  53. init_printer_connections,
  54. )
  55. from backend.app.services.print_scheduler import scheduler as print_scheduler
  56. from backend.app.services.bambu_mqtt import PrinterState
  57. from backend.app.services.archive import ArchiveService
  58. from backend.app.services.bambu_ftp import download_file_async
  59. from backend.app.services.smart_plug_manager import smart_plug_manager
  60. from backend.app.services.tasmota import tasmota_service
  61. from backend.app.models.smart_plug import SmartPlug
  62. # Track active prints: {(printer_id, filename): archive_id}
  63. _active_prints: dict[tuple[int, str], int] = {}
  64. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  65. # {(printer_id, filename): archive_id}
  66. _expected_prints: dict[tuple[int, str], int] = {}
  67. # Track starting energy for prints: {archive_id: starting_kwh}
  68. _print_energy_start: dict[int, float] = {}
  69. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  70. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  71. # Store with multiple filename variations to catch different naming patterns
  72. _expected_prints[(printer_id, filename)] = archive_id
  73. # Also store without .3mf extension if present
  74. if filename.endswith(".3mf"):
  75. base = filename[:-4]
  76. _expected_prints[(printer_id, base)] = archive_id
  77. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  78. logging.getLogger(__name__).info(
  79. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  80. )
  81. _last_status_broadcast: dict[int, str] = {}
  82. async def on_printer_status_change(printer_id: int, state: PrinterState):
  83. """Handle printer status changes - broadcast via WebSocket."""
  84. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  85. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  86. temps = state.temperatures or {}
  87. nozzle_temp = round(temps.get("nozzle", 0))
  88. bed_temp = round(temps.get("bed", 0))
  89. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  90. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  91. status_key = (
  92. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  93. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}"
  94. )
  95. if _last_status_broadcast.get(printer_id) == status_key:
  96. return # No change, skip broadcast
  97. _last_status_broadcast[printer_id] = status_key
  98. await ws_manager.send_printer_status(
  99. printer_id,
  100. printer_state_to_dict(state, printer_id),
  101. )
  102. async def on_print_start(printer_id: int, data: dict):
  103. """Handle print start - archive the 3MF file immediately."""
  104. import logging
  105. logger = logging.getLogger(__name__)
  106. await ws_manager.send_print_start(printer_id, data)
  107. async with async_session() as db:
  108. from backend.app.models.printer import Printer
  109. from backend.app.services.bambu_ftp import list_files_async
  110. result = await db.execute(
  111. select(Printer).where(Printer.id == printer_id)
  112. )
  113. printer = result.scalar_one_or_none()
  114. if not printer or not printer.auto_archive:
  115. return
  116. # Get the filename and subtask_name
  117. filename = data.get("filename", "")
  118. subtask_name = data.get("subtask_name", "")
  119. logger.info(f"Print start detected - filename: {filename}, subtask: {subtask_name}")
  120. if not filename and not subtask_name:
  121. return
  122. # Check if this is an expected print from reprint/scheduled
  123. # Build list of possible keys to check
  124. expected_keys = []
  125. if subtask_name:
  126. expected_keys.append((printer_id, subtask_name))
  127. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  128. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  129. if filename:
  130. fname = filename.split("/")[-1] if "/" in filename else filename
  131. expected_keys.append((printer_id, fname))
  132. # Strip extensions to match
  133. base = fname.replace(".gcode", "").replace(".3mf", "")
  134. expected_keys.append((printer_id, base))
  135. expected_keys.append((printer_id, f"{base}.3mf"))
  136. expected_archive_id = None
  137. for key in expected_keys:
  138. expected_archive_id = _expected_prints.pop(key, None)
  139. if expected_archive_id:
  140. # Clean up other possible keys for this print
  141. for other_key in expected_keys:
  142. _expected_prints.pop(other_key, None)
  143. break
  144. if expected_archive_id:
  145. # This is a reprint/scheduled print - use existing archive, don't create new one
  146. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  147. from backend.app.models.archive import PrintArchive
  148. from datetime import datetime
  149. result = await db.execute(
  150. select(PrintArchive).where(PrintArchive.id == expected_archive_id)
  151. )
  152. archive = result.scalar_one_or_none()
  153. if archive:
  154. # Update archive status to printing
  155. archive.status = "printing"
  156. archive.started_at = datetime.now()
  157. await db.commit()
  158. # Track as active print
  159. _active_prints[(printer_id, archive.filename)] = archive.id
  160. if subtask_name:
  161. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  162. # Set up energy tracking
  163. try:
  164. plug_result = await db.execute(
  165. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  166. )
  167. plug = plug_result.scalar_one_or_none()
  168. logger.info(f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}")
  169. if plug:
  170. energy = await tasmota_service.get_energy(plug)
  171. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  172. if energy and energy.get("total") is not None:
  173. _print_energy_start[archive.id] = energy["total"]
  174. logger.info(f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  175. else:
  176. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  177. else:
  178. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  179. except Exception as e:
  180. logger.warning(f"Failed to record starting energy: {e}")
  181. await ws_manager.send_archive_updated({
  182. "id": archive.id,
  183. "status": "printing",
  184. })
  185. # Smart plug automation for expected prints too
  186. try:
  187. await smart_plug_manager.on_print_start(printer_id, db)
  188. except Exception as e:
  189. logger.warning(f"Smart plug on_print_start failed: {e}")
  190. return # Skip creating a new archive
  191. # Check if there's already a "printing" archive for this printer/file
  192. # This prevents duplicates when backend restarts during an active print
  193. from backend.app.models.archive import PrintArchive
  194. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  195. existing = await db.execute(
  196. select(PrintArchive)
  197. .where(PrintArchive.printer_id == printer_id)
  198. .where(PrintArchive.status == "printing")
  199. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  200. .order_by(PrintArchive.created_at.desc())
  201. .limit(1)
  202. )
  203. existing_archive = existing.scalar_one_or_none()
  204. if existing_archive:
  205. logger.info(f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}")
  206. # Track this as the active print
  207. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  208. # Also set up energy tracking if not already tracked
  209. if existing_archive.id not in _print_energy_start:
  210. try:
  211. plug_result = await db.execute(
  212. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  213. )
  214. plug = plug_result.scalar_one_or_none()
  215. if plug:
  216. energy = await tasmota_service.get_energy(plug)
  217. if energy and energy.get("total") is not None:
  218. _print_energy_start[existing_archive.id] = energy["total"]
  219. logger.info(f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh")
  220. except Exception as e:
  221. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  222. return
  223. # Build list of possible 3MF filenames to try
  224. possible_names = []
  225. # Bambu printers typically store files as "Name.gcode.3mf"
  226. # The subtask_name is usually the best source for the filename
  227. if subtask_name:
  228. # Try common Bambu naming patterns
  229. possible_names.append(f"{subtask_name}.gcode.3mf")
  230. possible_names.append(f"{subtask_name}.3mf")
  231. # Try original filename with .3mf extension
  232. if filename:
  233. # Extract just the filename part, not the full path
  234. fname = filename.split("/")[-1] if "/" in filename else filename
  235. if fname.endswith(".3mf"):
  236. possible_names.append(fname)
  237. elif fname.endswith(".gcode"):
  238. base = fname.rsplit(".", 1)[0]
  239. possible_names.append(f"{base}.gcode.3mf")
  240. possible_names.append(f"{base}.3mf")
  241. else:
  242. possible_names.append(f"{fname}.gcode.3mf")
  243. possible_names.append(f"{fname}.3mf")
  244. # Remove duplicates while preserving order
  245. seen = set()
  246. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  247. logger.info(f"Trying filenames: {possible_names}")
  248. # Try to find and download the 3MF file
  249. temp_path = None
  250. downloaded_filename = None
  251. for try_filename in possible_names:
  252. if not try_filename.endswith(".3mf"):
  253. continue
  254. remote_paths = [
  255. f"/cache/{try_filename}",
  256. f"/model/{try_filename}",
  257. f"/{try_filename}",
  258. ]
  259. temp_path = app_settings.archive_dir / "temp" / try_filename
  260. temp_path.parent.mkdir(parents=True, exist_ok=True)
  261. for remote_path in remote_paths:
  262. logger.debug(f"Trying FTP download: {remote_path}")
  263. try:
  264. if await download_file_async(
  265. printer.ip_address,
  266. printer.access_code,
  267. remote_path,
  268. temp_path,
  269. ):
  270. downloaded_filename = try_filename
  271. logger.info(f"Downloaded: {remote_path}")
  272. break
  273. except Exception as e:
  274. logger.debug(f"FTP download failed for {remote_path}: {e}")
  275. if downloaded_filename:
  276. break
  277. # If still not found, try listing /cache to find matching file
  278. if not downloaded_filename and (filename or subtask_name):
  279. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  280. try:
  281. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  282. for f in cache_files:
  283. if f.get("is_directory"):
  284. continue
  285. fname = f.get("name", "")
  286. if fname.endswith(".3mf") and search_term in fname.lower():
  287. temp_path = app_settings.archive_dir / "temp" / fname
  288. temp_path.parent.mkdir(parents=True, exist_ok=True)
  289. if await download_file_async(
  290. printer.ip_address,
  291. printer.access_code,
  292. f"/cache/{fname}",
  293. temp_path,
  294. ):
  295. downloaded_filename = fname
  296. logger.info(f"Found and downloaded from cache: {fname}")
  297. break
  298. except Exception as e:
  299. logger.warning(f"Failed to list cache: {e}")
  300. if not downloaded_filename or not temp_path:
  301. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  302. return
  303. try:
  304. # Archive the file with status "printing"
  305. service = ArchiveService(db)
  306. archive = await service.archive_print(
  307. printer_id=printer_id,
  308. source_file=temp_path,
  309. print_data={**data, "status": "printing"},
  310. )
  311. if archive:
  312. # Track this active print (use both original filename and downloaded filename)
  313. _active_prints[(printer_id, downloaded_filename)] = archive.id
  314. if filename and filename != downloaded_filename:
  315. _active_prints[(printer_id, filename)] = archive.id
  316. if subtask_name:
  317. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  318. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  319. # Record starting energy from smart plug if available
  320. try:
  321. plug_result = await db.execute(
  322. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  323. )
  324. plug = plug_result.scalar_one_or_none()
  325. logger.info(f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}")
  326. if plug:
  327. energy = await tasmota_service.get_energy(plug)
  328. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  329. if energy and energy.get("total") is not None:
  330. _print_energy_start[archive.id] = energy["total"]
  331. logger.info(f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  332. else:
  333. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  334. else:
  335. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  336. except Exception as e:
  337. logger.warning(f"Failed to record starting energy: {e}")
  338. await ws_manager.send_archive_created({
  339. "id": archive.id,
  340. "printer_id": archive.printer_id,
  341. "filename": archive.filename,
  342. "print_name": archive.print_name,
  343. "status": archive.status,
  344. })
  345. finally:
  346. if temp_path and temp_path.exists():
  347. temp_path.unlink()
  348. # Smart plug automation: turn on plug when print starts
  349. try:
  350. async with async_session() as db:
  351. await smart_plug_manager.on_print_start(printer_id, db)
  352. except Exception as e:
  353. import logging
  354. logging.getLogger(__name__).warning(f"Smart plug on_print_start failed: {e}")
  355. async def on_print_complete(printer_id: int, data: dict):
  356. """Handle print completion - update the archive status."""
  357. import logging
  358. logger = logging.getLogger(__name__)
  359. await ws_manager.send_print_complete(printer_id, data)
  360. filename = data.get("filename", "")
  361. subtask_name = data.get("subtask_name", "")
  362. if not filename and not subtask_name:
  363. logger.warning(f"Print complete without filename or subtask_name")
  364. return
  365. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  366. # Build list of possible keys to try (matching how they were registered in on_print_start)
  367. possible_keys = []
  368. # Try subtask_name variations first (most reliable for matching)
  369. if subtask_name:
  370. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  371. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  372. possible_keys.append((printer_id, subtask_name))
  373. # Try filename variations
  374. if filename:
  375. # Extract just the filename if it's a path
  376. fname = filename.split("/")[-1] if "/" in filename else filename
  377. if fname.endswith(".3mf"):
  378. possible_keys.append((printer_id, fname))
  379. elif fname.endswith(".gcode"):
  380. base_name = fname.rsplit(".", 1)[0]
  381. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  382. possible_keys.append((printer_id, f"{base_name}.3mf"))
  383. possible_keys.append((printer_id, fname))
  384. else:
  385. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  386. possible_keys.append((printer_id, f"{fname}.3mf"))
  387. possible_keys.append((printer_id, fname))
  388. # Also try full path versions
  389. if filename.endswith(".3mf"):
  390. possible_keys.append((printer_id, filename))
  391. elif filename.endswith(".gcode"):
  392. base_name = filename.rsplit(".", 1)[0]
  393. possible_keys.append((printer_id, f"{base_name}.3mf"))
  394. possible_keys.append((printer_id, filename))
  395. else:
  396. possible_keys.append((printer_id, f"{filename}.3mf"))
  397. possible_keys.append((printer_id, filename))
  398. # Find the archive for this print
  399. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  400. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  401. archive_id = None
  402. for key in possible_keys:
  403. archive_id = _active_prints.pop(key, None)
  404. if archive_id:
  405. logger.info(f"Found archive {archive_id} with key {key}")
  406. # Also clean up any other keys pointing to this archive
  407. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  408. for k in keys_to_remove:
  409. _active_prints.pop(k, None)
  410. break
  411. if not archive_id:
  412. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  413. async with async_session() as db:
  414. from backend.app.models.archive import PrintArchive
  415. # Try matching by subtask_name (stored as print_name) first
  416. if subtask_name:
  417. result = await db.execute(
  418. select(PrintArchive)
  419. .where(PrintArchive.printer_id == printer_id)
  420. .where(PrintArchive.status == "printing")
  421. .where(or_(
  422. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  423. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  424. ))
  425. .order_by(PrintArchive.created_at.desc())
  426. .limit(1)
  427. )
  428. archive = result.scalar_one_or_none()
  429. if archive:
  430. archive_id = archive.id
  431. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  432. # Also try by filename
  433. if not archive_id and filename:
  434. result = await db.execute(
  435. select(PrintArchive)
  436. .where(PrintArchive.printer_id == printer_id)
  437. .where(PrintArchive.filename == filename)
  438. .where(PrintArchive.status == "printing")
  439. .order_by(PrintArchive.created_at.desc())
  440. .limit(1)
  441. )
  442. archive = result.scalar_one_or_none()
  443. if archive:
  444. archive_id = archive.id
  445. if not archive_id:
  446. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  447. return
  448. # Update archive status
  449. async with async_session() as db:
  450. service = ArchiveService(db)
  451. status = data.get("status", "completed")
  452. await service.update_archive_status(
  453. archive_id,
  454. status=status,
  455. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  456. )
  457. await ws_manager.send_archive_updated({
  458. "id": archive_id,
  459. "status": status,
  460. })
  461. # Calculate energy used for this print
  462. try:
  463. starting_kwh = _print_energy_start.pop(archive_id, None)
  464. logger.info(f"[ENERGY] Print complete for archive {archive_id}, starting_kwh={starting_kwh}, tracked_archives={list(_print_energy_start.keys())}")
  465. if starting_kwh is not None:
  466. async with async_session() as db:
  467. # Get smart plug for this printer (SmartPlug is imported at module level)
  468. plug_result = await db.execute(
  469. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  470. )
  471. plug = plug_result.scalar_one_or_none()
  472. if plug:
  473. energy = await tasmota_service.get_energy(plug)
  474. logger.info(f"[ENERGY] Print complete - ending energy response: {energy}")
  475. if energy and energy.get("total") is not None:
  476. ending_kwh = energy["total"]
  477. energy_used = round(ending_kwh - starting_kwh, 4)
  478. logger.info(f"[ENERGY] Calculated: ending={ending_kwh}, starting={starting_kwh}, used={energy_used}")
  479. # Get energy cost per kWh from settings (default to 0.15)
  480. from backend.app.api.routes.settings import get_setting
  481. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  482. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  483. energy_cost = round(energy_used * cost_per_kwh, 2)
  484. # Update archive with energy data
  485. from backend.app.models.archive import PrintArchive
  486. result = await db.execute(
  487. select(PrintArchive).where(PrintArchive.id == archive_id)
  488. )
  489. archive = result.scalar_one_or_none()
  490. if archive:
  491. archive.energy_kwh = energy_used
  492. archive.energy_cost = energy_cost
  493. await db.commit()
  494. logger.info(f"[ENERGY] Saved to archive {archive_id}: {energy_used} kWh, cost={energy_cost}")
  495. else:
  496. logger.warning(f"[ENERGY] Archive {archive_id} not found when saving energy")
  497. else:
  498. logger.warning(f"[ENERGY] No 'total' in ending energy response")
  499. else:
  500. logger.info(f"[ENERGY] No smart plug found for printer {printer_id} at print complete")
  501. except Exception as e:
  502. import logging
  503. logging.getLogger(__name__).warning(f"Failed to calculate energy: {e}")
  504. # Capture finish photo from printer camera
  505. logger.info(f"[PHOTO] Starting finish photo capture for archive {archive_id}")
  506. try:
  507. async with async_session() as db:
  508. # Check if finish photo capture is enabled
  509. from backend.app.api.routes.settings import get_setting
  510. capture_enabled = await get_setting(db, "capture_finish_photo")
  511. logger.info(f"[PHOTO] capture_finish_photo setting: {capture_enabled}")
  512. if capture_enabled is None or capture_enabled.lower() == "true":
  513. # Get printer details
  514. from backend.app.models.printer import Printer
  515. result = await db.execute(
  516. select(Printer).where(Printer.id == printer_id)
  517. )
  518. printer = result.scalar_one_or_none()
  519. if printer and archive_id:
  520. # Get archive to find its directory
  521. from backend.app.models.archive import PrintArchive
  522. result = await db.execute(
  523. select(PrintArchive).where(PrintArchive.id == archive_id)
  524. )
  525. archive = result.scalar_one_or_none()
  526. if archive:
  527. from backend.app.services.camera import capture_finish_photo
  528. from pathlib import Path
  529. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  530. photo_filename = await capture_finish_photo(
  531. printer_id=printer_id,
  532. ip_address=printer.ip_address,
  533. access_code=printer.access_code,
  534. model=printer.model,
  535. archive_dir=archive_dir,
  536. )
  537. if photo_filename:
  538. # Add photo to archive's photos list
  539. photos = archive.photos or []
  540. photos.append(photo_filename)
  541. archive.photos = photos
  542. await db.commit()
  543. logger.info(f"Added finish photo to archive {archive_id}: {photo_filename}")
  544. except Exception as e:
  545. import logging
  546. logging.getLogger(__name__).warning(f"Finish photo capture failed: {e}")
  547. # Smart plug automation: schedule turn off when print completes
  548. logger.info(f"[AUTO-OFF] Calling smart_plug_manager.on_print_complete for printer {printer_id}")
  549. try:
  550. async with async_session() as db:
  551. status = data.get("status", "completed")
  552. await smart_plug_manager.on_print_complete(printer_id, status, db)
  553. logger.info(f"[AUTO-OFF] smart_plug_manager.on_print_complete completed")
  554. except Exception as e:
  555. import logging
  556. logging.getLogger(__name__).warning(f"Smart plug on_print_complete failed: {e}")
  557. # Update queue item if this was a scheduled print
  558. try:
  559. async with async_session() as db:
  560. from backend.app.models.print_queue import PrintQueueItem
  561. # Note: SmartPlug is already imported at module level (line 56)
  562. # Do NOT import it here as it would shadow the module-level import
  563. # and cause "cannot access local variable" errors earlier in this function
  564. result = await db.execute(
  565. select(PrintQueueItem)
  566. .where(PrintQueueItem.printer_id == printer_id)
  567. .where(PrintQueueItem.status == "printing")
  568. )
  569. queue_item = result.scalar_one_or_none()
  570. if queue_item:
  571. status = data.get("status", "completed")
  572. queue_item.status = status
  573. queue_item.completed_at = datetime.now()
  574. await db.commit()
  575. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  576. # Handle auto_off_after - power off printer if requested (after cooldown)
  577. if queue_item.auto_off_after:
  578. result = await db.execute(
  579. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  580. )
  581. plug = result.scalar_one_or_none()
  582. if plug and plug.enabled:
  583. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  584. async def cooldown_and_poweroff(pid: int, plug_id: int):
  585. # Wait for nozzle to cool down
  586. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  587. # Re-fetch plug in new session
  588. async with async_session() as new_db:
  589. result = await new_db.execute(
  590. select(SmartPlug).where(SmartPlug.id == plug_id)
  591. )
  592. p = result.scalar_one_or_none()
  593. if p and p.enabled:
  594. success = await tasmota_service.turn_off(p)
  595. if success:
  596. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  597. else:
  598. logger.warning(f"Failed to power off printer {pid} via smart plug")
  599. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  600. except Exception as e:
  601. import logging
  602. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  603. @asynccontextmanager
  604. async def lifespan(app: FastAPI):
  605. # Startup
  606. await init_db()
  607. # Set up printer manager callbacks
  608. loop = asyncio.get_event_loop()
  609. printer_manager.set_event_loop(loop)
  610. printer_manager.set_status_change_callback(on_printer_status_change)
  611. printer_manager.set_print_start_callback(on_print_start)
  612. printer_manager.set_print_complete_callback(on_print_complete)
  613. # Connect to all active printers
  614. async with async_session() as db:
  615. await init_printer_connections(db)
  616. # Start the print scheduler
  617. asyncio.create_task(print_scheduler.run())
  618. yield
  619. # Shutdown
  620. print_scheduler.stop()
  621. printer_manager.disconnect_all()
  622. app = FastAPI(
  623. title=app_settings.app_name,
  624. description="Archive and manage Bambu Lab 3MF files",
  625. version="0.1.2",
  626. lifespan=lifespan,
  627. )
  628. # API routes
  629. app.include_router(printers.router, prefix=app_settings.api_prefix)
  630. app.include_router(archives.router, prefix=app_settings.api_prefix)
  631. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  632. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  633. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  634. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  635. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  636. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  637. # Serve static files (React build)
  638. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  639. app.mount(
  640. "/assets",
  641. StaticFiles(directory=app_settings.static_dir / "assets"),
  642. name="assets",
  643. )
  644. if (app_settings.static_dir / "img").exists():
  645. app.mount(
  646. "/img",
  647. StaticFiles(directory=app_settings.static_dir / "img"),
  648. name="img",
  649. )
  650. @app.get("/")
  651. async def serve_frontend():
  652. """Serve the React frontend."""
  653. index_file = app_settings.static_dir / "index.html"
  654. if index_file.exists():
  655. return FileResponse(index_file)
  656. return {
  657. "message": "BambuTrack API",
  658. "docs": "/docs",
  659. "frontend": "Build and place React app in /static directory",
  660. }
  661. @app.get("/health")
  662. async def health_check():
  663. """Health check endpoint."""
  664. return {"status": "healthy"}
  665. # Catch-all route for React Router (must be last)
  666. @app.get("/{full_path:path}")
  667. async def serve_spa(full_path: str):
  668. """Serve React app for client-side routing."""
  669. # Don't intercept API routes
  670. if full_path.startswith("api/"):
  671. return {"error": "Not found"}
  672. index_file = app_settings.static_dir / "index.html"
  673. if index_file.exists():
  674. return FileResponse(index_file)
  675. return {"error": "Frontend not built"}