main.py 75 KB

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