main.py 108 KB

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