main.py 97 KB

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