main.py 92 KB

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