main.py 101 KB

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