main.py 66 KB

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