main.py 69 KB

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