main.py 95 KB

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