main.py 126 KB

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