main.py 35 KB

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