main.py 43 KB

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