main.py 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302
  1. import asyncio
  2. import logging
  3. from contextlib import asynccontextmanager
  4. from datetime import datetime, timedelta, timezone
  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) # nosec B104
  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("Logging to file: %s", 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("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, 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. inventory,
  161. kprofiles,
  162. library,
  163. local_presets,
  164. maintenance,
  165. metrics,
  166. notification_templates,
  167. notifications,
  168. pending_uploads,
  169. print_queue,
  170. printers,
  171. projects,
  172. settings as settings_routes,
  173. smart_plugs,
  174. spoolman,
  175. support,
  176. system,
  177. updates,
  178. users,
  179. webhook,
  180. websocket,
  181. )
  182. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  183. from backend.app.api.routes.support import init_debug_logging
  184. from backend.app.core.database import async_session, init_db
  185. from backend.app.core.websocket import ws_manager
  186. from backend.app.models.smart_plug import SmartPlug
  187. from backend.app.services.archive import ArchiveService
  188. from backend.app.services.bambu_ftp import download_file_async, get_ftp_retry_settings, with_ftp_retry
  189. from backend.app.services.bambu_mqtt import PrinterState
  190. from backend.app.services.github_backup import github_backup_service
  191. from backend.app.services.homeassistant import homeassistant_service
  192. from backend.app.services.mqtt_relay import mqtt_relay
  193. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  194. from backend.app.services.notification_service import notification_service
  195. from backend.app.services.print_scheduler import scheduler as print_scheduler
  196. from backend.app.services.printer_manager import (
  197. init_printer_connections,
  198. printer_manager,
  199. printer_state_to_dict,
  200. )
  201. from backend.app.services.smart_plug_manager import smart_plug_manager
  202. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  203. from backend.app.services.spoolman_tracking import (
  204. cleanup_tracking as _cleanup_spoolman_tracking,
  205. report_usage as _report_spoolman_usage,
  206. store_print_data as _store_spoolman_print_data,
  207. )
  208. from backend.app.services.tasmota import tasmota_service
  209. # Track active prints: {(printer_id, filename): archive_id}
  210. _active_prints: dict[tuple[int, str], int] = {}
  211. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  212. # {(printer_id, filename): archive_id}
  213. _expected_prints: dict[tuple[int, str], int] = {}
  214. # Track starting energy for prints: {archive_id: starting_kwh}
  215. _print_energy_start: dict[int, float] = {}
  216. # Track reprints to add costs on completion: {archive_id}
  217. _reprint_archives: set[int] = set()
  218. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  219. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  220. _last_progress_milestone: dict[int, int] = {}
  221. # Track HMS errors that have been notified: {printer_id: set of error codes}
  222. # This prevents sending duplicate notifications for the same error
  223. _notified_hms_errors: dict[int, set[str]] = {}
  224. # Track timelapse file baselines at print start: {printer_id: set of MP4 filenames}
  225. # Used for snapshot-diff detection at print completion
  226. _timelapse_baselines: dict[int, set[str]] = {}
  227. async def _get_plug_energy(plug, db) -> dict | None:
  228. """Get energy from plug regardless of type (Tasmota, Home Assistant, or MQTT).
  229. For HA plugs, configures the service with current settings from DB.
  230. For MQTT plugs, returns data from the subscription service.
  231. """
  232. if plug.plug_type == "homeassistant":
  233. from backend.app.api.routes.settings import get_homeassistant_settings
  234. ha_settings = await get_homeassistant_settings(db)
  235. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  236. return await homeassistant_service.get_energy(plug)
  237. elif plug.plug_type == "mqtt":
  238. # MQTT plugs report "today" energy, not lifetime total
  239. # For per-print tracking, we use "today" as the counter (resets at midnight)
  240. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  241. if mqtt_data:
  242. return {
  243. "power": mqtt_data.power,
  244. "today": mqtt_data.energy,
  245. "total": mqtt_data.energy, # Use today as total for per-print calculations
  246. }
  247. return None
  248. else:
  249. return await tasmota_service.get_energy(plug)
  250. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  251. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  252. # Store with multiple filename variations to catch different naming patterns
  253. _expected_prints[(printer_id, filename)] = archive_id
  254. # Also store without .3mf extension if present
  255. if filename.endswith(".3mf"):
  256. base = filename[:-4]
  257. _expected_prints[(printer_id, base)] = archive_id
  258. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  259. logging.getLogger(__name__).info(
  260. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  261. )
  262. _last_status_broadcast: dict[int, str] = {}
  263. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  264. async def on_printer_status_change(printer_id: int, state: PrinterState):
  265. """Handle printer status changes - broadcast via WebSocket."""
  266. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  267. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  268. temps = state.temperatures or {}
  269. nozzle_temp = round(temps.get("nozzle", 0))
  270. bed_temp = round(temps.get("bed", 0))
  271. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  272. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  273. # Auto-detect dual-nozzle printers from MQTT temperature data
  274. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  275. _nozzle_count_updated.add(printer_id)
  276. # Update nozzle_count in database
  277. async with async_session() as db:
  278. from backend.app.models.printer import Printer
  279. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  280. printer = result.scalar_one_or_none()
  281. if printer and printer.nozzle_count != 2:
  282. printer.nozzle_count = 2
  283. await db.commit()
  284. logging.getLogger(__name__).info(
  285. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  286. )
  287. # Include target temps for heating phase detection
  288. bed_target = round(temps.get("bed_target", 0))
  289. nozzle_target = round(temps.get("nozzle_target", 0))
  290. status_key = (
  291. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  292. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  293. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  294. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  295. f"{state.chamber_light}:{state.active_extruder}"
  296. )
  297. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  298. try:
  299. printer_info = printer_manager.get_printer(printer_id)
  300. if printer_info:
  301. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  302. except Exception:
  303. pass # Don't fail status callback if MQTT fails
  304. if _last_status_broadcast.get(printer_id) == status_key:
  305. return # No change, skip WebSocket broadcast
  306. _last_status_broadcast[printer_id] = status_key
  307. # Check for progress milestone notifications (25%, 50%, 75%)
  308. progress = state.progress or 0
  309. is_printing = state.state in ("RUNNING", "PRINTING")
  310. if is_printing and progress > 0:
  311. # Determine which milestone we've reached
  312. current_milestone = 0
  313. if progress >= 75:
  314. current_milestone = 75
  315. elif progress >= 50:
  316. current_milestone = 50
  317. elif progress >= 25:
  318. current_milestone = 25
  319. last_milestone = _last_progress_milestone.get(printer_id, 0)
  320. # If we've crossed a new milestone, send notification
  321. if current_milestone > last_milestone:
  322. _last_progress_milestone[printer_id] = current_milestone
  323. try:
  324. async with async_session() as db:
  325. from backend.app.models.printer import Printer
  326. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  327. printer = result.scalar_one_or_none()
  328. printer_name = printer.name if printer else f"Printer {printer_id}"
  329. filename = state.subtask_name or state.gcode_file or "Unknown"
  330. # remaining_time is in minutes, convert to seconds for notification
  331. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  332. # Capture camera snapshot for notification image attachment
  333. image_data = await _capture_snapshot_for_notification(
  334. printer_id, printer, logging.getLogger(__name__)
  335. )
  336. await notification_service.on_print_progress(
  337. printer_id,
  338. printer_name,
  339. filename,
  340. current_milestone,
  341. db,
  342. remaining_time_seconds,
  343. image_data=image_data,
  344. )
  345. except Exception as e:
  346. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  347. elif progress < 5:
  348. # Reset milestone tracking when print restarts or new print begins
  349. _last_progress_milestone[printer_id] = 0
  350. # Check for new HMS errors and send notifications
  351. current_hms_errors = getattr(state, "hms_errors", []) or []
  352. if current_hms_errors:
  353. # Build set of current error codes (using attr for uniqueness)
  354. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  355. previously_notified = _notified_hms_errors.get(printer_id, set())
  356. # Find new errors that haven't been notified yet
  357. new_error_codes = current_error_codes - previously_notified
  358. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  359. _notified_hms_errors[printer_id] = current_error_codes
  360. if new_error_codes:
  361. # Get the actual new errors for the notification
  362. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  363. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  364. try:
  365. async with async_session() as db:
  366. from backend.app.models.printer import Printer
  367. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  368. printer = result.scalar_one_or_none()
  369. printer_name = printer.name if printer else f"Printer {printer_id}"
  370. # Format error details for notification
  371. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  372. module_names = {
  373. 0x03: "Print/Task",
  374. 0x05: "Nozzle/Extruder",
  375. 0x07: "AMS/Filament",
  376. 0x0C: "Motion Controller",
  377. 0x12: "Chamber",
  378. }
  379. from backend.app.services.hms_errors import get_error_description
  380. # Capture camera snapshot once for all error notifications
  381. error_image_data = await _capture_snapshot_for_notification(
  382. printer_id, printer, logging.getLogger(__name__)
  383. )
  384. for error in new_errors:
  385. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  386. # Build short code like "0700_8010"
  387. # Mask to 16 bits to handle printers that send larger values
  388. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  389. error_code_masked = error_code_int & 0xFFFF
  390. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  391. error_type = f"{module_name} Error"
  392. # Look up human-readable description
  393. description = get_error_description(short_code)
  394. error_detail = description if description else f"Error code: {short_code}"
  395. await notification_service.on_printer_error(
  396. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  397. )
  398. logging.getLogger(__name__).info(
  399. f"[HMS] Sent notification for {len(new_errors)} new error(s) on printer {printer_id}"
  400. )
  401. # Also publish to MQTT relay
  402. printer_info = printer_manager.get_printer(printer_id)
  403. if printer_info:
  404. errors_data = [
  405. {
  406. "code": e.code,
  407. "attr": e.attr,
  408. "module": e.module,
  409. "severity": e.severity,
  410. }
  411. for e in new_errors
  412. ]
  413. await mqtt_relay.on_printer_error(
  414. printer_id, printer_info.name, printer_info.serial_number, errors_data
  415. )
  416. except Exception as e:
  417. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  418. else:
  419. # No HMS errors - clear tracking so future errors get notified
  420. if printer_id in _notified_hms_errors:
  421. _notified_hms_errors.pop(printer_id, None)
  422. await ws_manager.send_printer_status(
  423. printer_id,
  424. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  425. )
  426. def _is_bambu_uuid(tray_uuid: str) -> bool:
  427. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  428. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  429. async def on_ams_change(printer_id: int, ams_data: list):
  430. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  431. logger = logging.getLogger(__name__)
  432. # MQTT relay - publish AMS change
  433. try:
  434. printer_info = printer_manager.get_printer(printer_id)
  435. if printer_info:
  436. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  437. except Exception:
  438. pass # Don't fail AMS callback if MQTT fails
  439. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  440. # This ensures frontend gets immediate updates when AMS slots are configured
  441. try:
  442. state = printer_manager.get_status(printer_id)
  443. if state:
  444. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  445. await ws_manager.send_printer_status(
  446. printer_id,
  447. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  448. )
  449. except Exception as e:
  450. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  451. # Auto-unlink spool assignments with stale fingerprints
  452. try:
  453. async with async_session() as db:
  454. from sqlalchemy.orm import selectinload
  455. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  456. from backend.app.models.spool_assignment import SpoolAssignment as SA
  457. result = await db.execute(select(SA).where(SA.printer_id == printer_id).options(selectinload(SA.spool)))
  458. stale = []
  459. for assignment in result.scalars().all():
  460. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  461. if not current_tray:
  462. logger.info(
  463. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  464. assignment.spool_id,
  465. assignment.ams_id,
  466. assignment.tray_id,
  467. )
  468. stale.append(assignment) # Slot empty
  469. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  470. # A Bambu Lab spool was inserted — always unlink manual assignments
  471. logger.info(
  472. "Auto-unlink: spool %d AMS%d-T%d — Bambu Lab spool detected (uuid=%s)",
  473. assignment.spool_id,
  474. assignment.ams_id,
  475. assignment.tray_id,
  476. current_tray.get("tray_uuid", ""),
  477. )
  478. stale.append(assignment)
  479. else:
  480. cur_color = current_tray.get("tray_color", "")
  481. cur_type = current_tray.get("tray_type", "")
  482. fp_color = assignment.fingerprint_color or ""
  483. fp_type = assignment.fingerprint_type or ""
  484. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  485. # Fingerprint mismatch — but check if tray now matches the
  486. # assigned spool (e.g. auto-configure changed the tray).
  487. spool = assignment.spool
  488. if spool:
  489. spool_color = (spool.rgba or "FFFFFFFF").upper()
  490. spool_type = (spool.material or "").upper()
  491. if cur_color.upper() == spool_color and cur_type.upper() == spool_type:
  492. # Tray was reconfigured to match the spool — update fingerprint
  493. logger.info(
  494. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  495. assignment.spool_id,
  496. assignment.ams_id,
  497. assignment.tray_id,
  498. )
  499. assignment.fingerprint_color = cur_color
  500. assignment.fingerprint_type = cur_type
  501. continue
  502. logger.info(
  503. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  504. assignment.spool_id,
  505. assignment.ams_id,
  506. assignment.tray_id,
  507. cur_color,
  508. cur_type,
  509. fp_color,
  510. fp_type,
  511. spool.rgba if spool else "?",
  512. spool.material if spool else "?",
  513. )
  514. stale.append(assignment) # Spool changed
  515. for a in stale:
  516. await db.delete(a)
  517. if stale:
  518. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  519. # Commit any changes (stale deletions and/or fingerprint updates)
  520. await db.commit()
  521. except Exception as e:
  522. logger.warning("Spool assignment cleanup failed: %s", e)
  523. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS)
  524. try:
  525. async with async_session() as db:
  526. from backend.app.api.routes.settings import get_setting
  527. from backend.app.models.spool_assignment import SpoolAssignment as SA
  528. from backend.app.services.spool_tag_matcher import (
  529. auto_assign_spool,
  530. create_spool_from_tray,
  531. get_spool_by_tag,
  532. is_bambu_tag,
  533. is_valid_tag,
  534. )
  535. _spoolman_on = await get_setting(db, "spoolman_enabled")
  536. if not _spoolman_on or _spoolman_on.lower() != "true":
  537. for ams_unit in ams_data:
  538. if not isinstance(ams_unit, dict):
  539. continue
  540. ams_id = int(ams_unit.get("id", 0))
  541. for tray in ams_unit.get("tray", []):
  542. if not isinstance(tray, dict):
  543. continue
  544. tray_id = int(tray.get("id", 0))
  545. tag_uid = tray.get("tag_uid", "")
  546. tray_uuid = tray.get("tray_uuid", "")
  547. tray_info_idx = tray.get("tray_info_idx", "")
  548. if not tray.get("tray_type"):
  549. continue # Empty slot
  550. # Check if assignment already exists for this slot
  551. existing = await db.execute(
  552. select(SA)
  553. .options(selectinload(SA.spool))
  554. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  555. )
  556. existing_assignment = existing.scalar_one_or_none()
  557. if existing_assignment:
  558. # Sync spool weight_used from AMS remain if valid
  559. remain_raw = tray.get("remain")
  560. if remain_raw is not None and existing_assignment.spool:
  561. try:
  562. remain_val = int(remain_raw)
  563. except (TypeError, ValueError):
  564. remain_val = -1
  565. if 0 <= remain_val <= 100:
  566. lw = existing_assignment.spool.label_weight or 1000
  567. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  568. if abs((existing_assignment.spool.weight_used or 0) - new_used) > 1:
  569. logger.info(
  570. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  571. existing_assignment.spool_id,
  572. existing_assignment.spool.weight_used,
  573. new_used,
  574. remain_val,
  575. )
  576. existing_assignment.spool.weight_used = new_used
  577. await db.commit()
  578. continue
  579. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  580. # BL spool with RFID tag: auto-match or auto-create
  581. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  582. if not spool:
  583. spool = await create_spool_from_tray(db, tray)
  584. await auto_assign_spool(
  585. printer_id,
  586. ams_id,
  587. tray_id,
  588. spool,
  589. printer_manager,
  590. db,
  591. )
  592. await db.commit()
  593. await ws_manager.broadcast(
  594. {
  595. "type": "spool_auto_assigned",
  596. "printer_id": printer_id,
  597. "ams_id": ams_id,
  598. "tray_id": tray_id,
  599. "spool_id": spool.id,
  600. }
  601. )
  602. logger.info(
  603. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  604. spool.id,
  605. printer_id,
  606. ams_id,
  607. tray_id,
  608. )
  609. elif is_valid_tag(tag_uid, tray_uuid):
  610. # Non-BL spool with some tag — let user choose
  611. await ws_manager.broadcast(
  612. {
  613. "type": "unknown_tag",
  614. "printer_id": printer_id,
  615. "ams_id": ams_id,
  616. "tray_id": tray_id,
  617. "tag_uid": tag_uid,
  618. "tray_uuid": tray_uuid,
  619. }
  620. )
  621. else:
  622. # No tag at all — let user choose from inventory
  623. await ws_manager.broadcast(
  624. {
  625. "type": "unknown_tag",
  626. "printer_id": printer_id,
  627. "ams_id": ams_id,
  628. "tray_id": tray_id,
  629. "tag_uid": "",
  630. "tray_uuid": "",
  631. }
  632. )
  633. except Exception as e:
  634. logger.warning("RFID spool auto-assign failed: %s", e)
  635. try:
  636. async with async_session() as db:
  637. from backend.app.api.routes.settings import get_setting
  638. from backend.app.models.printer import Printer
  639. # Check if Spoolman is enabled
  640. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  641. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  642. return
  643. # Check sync mode
  644. sync_mode = await get_setting(db, "spoolman_sync_mode")
  645. if sync_mode and sync_mode != "auto":
  646. return # Only sync on auto mode
  647. # Check if weight sync is disabled
  648. disable_weight_sync_str = await get_setting(db, "spoolman_disable_weight_sync")
  649. disable_weight_sync = disable_weight_sync_str and disable_weight_sync_str.lower() == "true"
  650. # Get Spoolman URL
  651. spoolman_url = await get_setting(db, "spoolman_url")
  652. if not spoolman_url:
  653. return
  654. # Get or create Spoolman client
  655. client = await get_spoolman_client()
  656. if not client:
  657. client = await init_spoolman_client(spoolman_url)
  658. # Check if Spoolman is reachable
  659. if not await client.health_check():
  660. logger.warning("Spoolman not reachable at %s", spoolman_url)
  661. return
  662. # Get printer name for location
  663. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  664. printer = result.scalar_one_or_none()
  665. printer_name = printer.name if printer else f"Printer {printer_id}"
  666. # OPTIMIZATION: Fetch all spools once before processing trays
  667. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  668. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  669. try:
  670. cached_spools = await client.get_spools()
  671. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  672. except Exception as e:
  673. logger.error(
  674. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  675. printer_id,
  676. e,
  677. )
  678. return
  679. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  680. from sqlalchemy.orm import selectinload
  681. from backend.app.models.spool_assignment import SpoolAssignment
  682. inventory_weights: dict[tuple[int, int], float] = {}
  683. try:
  684. assign_result = await db.execute(
  685. select(SpoolAssignment)
  686. .options(selectinload(SpoolAssignment.spool))
  687. .where(SpoolAssignment.printer_id == printer_id)
  688. )
  689. for assignment in assign_result.scalars().all():
  690. spool = assignment.spool
  691. if spool and spool.label_weight > 0:
  692. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  693. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  694. except Exception as e:
  695. logger.debug("Could not load inventory weights for printer %s: %s", printer_id, e)
  696. # Sync each AMS tray
  697. synced = 0
  698. for ams_unit in ams_data:
  699. ams_id = int(ams_unit.get("id", 0))
  700. trays = ams_unit.get("tray", [])
  701. for tray_data in trays:
  702. tray = client.parse_ams_tray(ams_id, tray_data)
  703. if not tray:
  704. continue # Empty tray
  705. try:
  706. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  707. result = await client.sync_ams_tray(
  708. tray,
  709. printer_name,
  710. disable_weight_sync=disable_weight_sync,
  711. cached_spools=cached_spools,
  712. inventory_remaining=inv_remaining,
  713. )
  714. if result:
  715. synced += 1
  716. # If a new spool was created, add it to the cache
  717. # so subsequent trays can find it if they reference the same tag
  718. if result.get("id"):
  719. # Check if this spool already exists in cache
  720. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  721. if not spool_exists:
  722. cached_spools.append(result)
  723. logger.debug(
  724. "[Printer %s] Added newly created spool %s to cache",
  725. printer_id,
  726. result["id"],
  727. )
  728. except Exception as e:
  729. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  730. if synced > 0:
  731. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  732. except Exception as e:
  733. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  734. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  735. """Capture a camera snapshot for notification image attachment.
  736. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  737. Uses: external camera > buffered frame > fresh capture.
  738. """
  739. if not printer:
  740. return None
  741. try:
  742. from backend.app.api.routes.settings import get_setting
  743. async with async_session() as db:
  744. capture_enabled = await get_setting(db, "capture_finish_photo")
  745. if capture_enabled is not None and capture_enabled.lower() != "true":
  746. return None
  747. # Try external camera first
  748. if printer.external_camera_enabled and printer.external_camera_url:
  749. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  750. from backend.app.services.external_camera import capture_frame
  751. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type or "mjpeg")
  752. if frame_data and len(frame_data) <= 2_500_000:
  753. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  754. return frame_data
  755. # Try buffered frame from active stream
  756. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  757. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  758. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  759. buffered_frame = get_buffered_frame(printer_id)
  760. if (active_for_printer or active_chamber) and buffered_frame:
  761. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  762. if len(buffered_frame) <= 2_500_000:
  763. return buffered_frame
  764. # Fresh capture from printer camera
  765. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  766. from backend.app.services.camera import capture_camera_frame_bytes
  767. frame_data = await capture_camera_frame_bytes(
  768. printer.ip_address, printer.access_code, printer.model, timeout=15
  769. )
  770. if frame_data and len(frame_data) <= 2_500_000:
  771. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  772. return frame_data
  773. except Exception as e:
  774. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  775. return None
  776. async def _send_print_start_notification(
  777. printer_id: int,
  778. data: dict,
  779. archive_data: dict | None = None,
  780. logger=None,
  781. ):
  782. """Helper to send print start notification with optional archive data."""
  783. if logger is None:
  784. logger = logging.getLogger(__name__)
  785. try:
  786. async with async_session() as db:
  787. from backend.app.models.printer import Printer
  788. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  789. printer = result.scalar_one_or_none()
  790. printer_name = printer.name if printer else f"Printer {printer_id}"
  791. # Capture camera snapshot for notification image attachment
  792. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  793. if image_data:
  794. if archive_data is None:
  795. archive_data = {}
  796. archive_data["image_data"] = image_data
  797. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  798. except Exception as e:
  799. logger.warning("Notification on_print_start failed: %s", e)
  800. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  801. """Extract printable objects from an archive's 3MF file and store in printer state."""
  802. try:
  803. from backend.app.services.archive import extract_printable_objects_from_3mf
  804. file_path = app_settings.base_dir / archive.file_path
  805. if file_path.exists() and str(file_path).endswith(".3mf"):
  806. with open(file_path, "rb") as f:
  807. threemf_data = f.read()
  808. # Extract with positions for UI overlay
  809. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  810. if printable_objects:
  811. client = printer_manager.get_client(printer_id)
  812. if client:
  813. client.state.printable_objects = printable_objects
  814. client.state.printable_objects_bbox_all = bbox_all
  815. client.state.skipped_objects = []
  816. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  817. except Exception as e:
  818. logger.debug("Failed to extract printable objects from archive: %s", e)
  819. async def on_print_start(printer_id: int, data: dict):
  820. """Handle print start - archive the 3MF file immediately."""
  821. logger = logging.getLogger(__name__)
  822. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  823. # Clear cached cover images so the new print's thumbnail is fetched fresh
  824. from backend.app.api.routes.printers import clear_cover_cache
  825. clear_cover_cache(printer_id)
  826. await ws_manager.send_print_start(printer_id, data)
  827. # MQTT relay - publish print start
  828. try:
  829. printer_info = printer_manager.get_printer(printer_id)
  830. if printer_info:
  831. await mqtt_relay.on_print_start(
  832. printer_id,
  833. printer_info.name,
  834. printer_info.serial_number,
  835. data.get("filename", ""),
  836. data.get("subtask_name", ""),
  837. )
  838. except Exception:
  839. pass # Don't fail print start callback if MQTT fails
  840. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  841. try:
  842. async with async_session() as db:
  843. from backend.app.api.routes.settings import get_setting
  844. _spoolman_on = await get_setting(db, "spoolman_enabled")
  845. if not _spoolman_on or _spoolman_on.lower() != "true":
  846. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  847. await usage_on_print_start(printer_id, data, printer_manager)
  848. except Exception as e:
  849. logger.warning("Usage tracker on_print_start failed: %s", e)
  850. # Track if notification was sent (to avoid sending twice)
  851. notification_sent = False
  852. # Smart plug automation: turn on plug when print starts
  853. try:
  854. async with async_session() as db:
  855. await smart_plug_manager.on_print_start(printer_id, db)
  856. except Exception as e:
  857. logger.warning("Smart plug on_print_start failed: %s", e)
  858. async with async_session() as db:
  859. from backend.app.models.printer import Printer
  860. from backend.app.services.bambu_ftp import list_files_async
  861. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  862. printer = result.scalar_one_or_none()
  863. # Plate detection check - pause if objects detected on build plate
  864. logger.info(
  865. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  866. )
  867. if printer and printer.plate_detection_enabled:
  868. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  869. try:
  870. from backend.app.services.plate_detection import check_plate_empty
  871. # Build ROI tuple from printer settings if available
  872. roi = None
  873. if all(
  874. [
  875. printer.plate_detection_roi_x is not None,
  876. printer.plate_detection_roi_y is not None,
  877. printer.plate_detection_roi_w is not None,
  878. printer.plate_detection_roi_h is not None,
  879. ]
  880. ):
  881. roi = (
  882. printer.plate_detection_roi_x,
  883. printer.plate_detection_roi_y,
  884. printer.plate_detection_roi_w,
  885. printer.plate_detection_roi_h,
  886. )
  887. # Auto-turn on chamber light if it's off for better detection
  888. light_was_off = False
  889. client = printer_manager.get_client(printer_id)
  890. if client and client.state:
  891. light_was_off = not client.state.chamber_light
  892. if light_was_off:
  893. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  894. client.set_chamber_light(True)
  895. # Wait for light to physically turn on and camera to adjust exposure
  896. await asyncio.sleep(2.5)
  897. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  898. plate_result = await check_plate_empty(
  899. printer_id=printer_id,
  900. ip_address=printer.ip_address,
  901. access_code=printer.access_code,
  902. model=printer.model,
  903. include_debug_image=False,
  904. external_camera_url=printer.external_camera_url,
  905. external_camera_type=printer.external_camera_type,
  906. use_external=printer.external_camera_enabled,
  907. roi=roi,
  908. )
  909. # Restore chamber light to original state
  910. if light_was_off and client:
  911. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  912. client.set_chamber_light(False)
  913. if not plate_result.needs_calibration and not plate_result.is_empty:
  914. # Objects detected - pause the print!
  915. logger.warning(
  916. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  917. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  918. )
  919. client = printer_manager.get_client(printer_id)
  920. if client:
  921. client.pause_print()
  922. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  923. # Send notification about plate not empty
  924. await ws_manager.broadcast(
  925. {
  926. "type": "plate_not_empty",
  927. "printer_id": printer_id,
  928. "printer_name": printer.name,
  929. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  930. }
  931. )
  932. # Also send push notification
  933. try:
  934. await notification_service.on_plate_not_empty(
  935. printer_id=printer_id,
  936. printer_name=printer.name,
  937. db=db,
  938. difference_percent=plate_result.difference_percent,
  939. )
  940. except Exception as notif_err:
  941. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  942. else:
  943. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  944. except Exception as plate_err:
  945. # Don't block print on plate detection errors
  946. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  947. if not printer or not printer.auto_archive:
  948. # Send notification without archive data (auto-archive disabled)
  949. logger.info(
  950. f"[CALLBACK] Skipping archive - printer: {printer is not None}, auto_archive: {printer.auto_archive if printer else 'N/A'}"
  951. )
  952. if not notification_sent:
  953. await _send_print_start_notification(printer_id, data, logger=logger)
  954. return
  955. # Get the filename and subtask_name
  956. filename = data.get("filename", "")
  957. subtask_name = data.get("subtask_name", "")
  958. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  959. # Skip calibration prints — internal printer files should not be archived
  960. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  961. if filename and filename.startswith("/usr/"):
  962. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  963. if not notification_sent:
  964. await _send_print_start_notification(printer_id, data, logger=logger)
  965. return
  966. if not filename and not subtask_name:
  967. # Send notification without archive data (no filename)
  968. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  969. if not notification_sent:
  970. await _send_print_start_notification(printer_id, data, logger=logger)
  971. return
  972. # Check if this is an expected print from reprint/scheduled
  973. # Build list of possible keys to check
  974. expected_keys = []
  975. if subtask_name:
  976. expected_keys.append((printer_id, subtask_name))
  977. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  978. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  979. if filename:
  980. fname = filename.split("/")[-1] if "/" in filename else filename
  981. expected_keys.append((printer_id, fname))
  982. # Strip extensions to match
  983. base = fname.replace(".gcode", "").replace(".3mf", "")
  984. expected_keys.append((printer_id, base))
  985. expected_keys.append((printer_id, f"{base}.3mf"))
  986. expected_archive_id = None
  987. for key in expected_keys:
  988. expected_archive_id = _expected_prints.pop(key, None)
  989. if expected_archive_id:
  990. # Clean up other possible keys for this print
  991. for other_key in expected_keys:
  992. _expected_prints.pop(other_key, None)
  993. break
  994. if expected_archive_id:
  995. # This is a reprint/scheduled print - use existing archive, don't create new one
  996. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  997. from backend.app.models.archive import PrintArchive
  998. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  999. archive = result.scalar_one_or_none()
  1000. if archive:
  1001. # Update archive status to printing
  1002. archive.status = "printing"
  1003. archive.started_at = datetime.now()
  1004. await db.commit()
  1005. # Track as active print
  1006. _active_prints[(printer_id, archive.filename)] = archive.id
  1007. if subtask_name:
  1008. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1009. # Mark as reprint so we add cost on completion
  1010. _reprint_archives.add(archive.id)
  1011. logger.info("Marked archive %s as reprint for cost addition on completion", archive.id)
  1012. # Set up energy tracking
  1013. try:
  1014. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1015. plug = plug_result.scalar_one_or_none()
  1016. logger.info(
  1017. f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  1018. )
  1019. if plug:
  1020. energy = await _get_plug_energy(plug, db)
  1021. logger.info("[ENERGY] Energy response from plug: %s", energy)
  1022. if energy and energy.get("total") is not None:
  1023. _print_energy_start[archive.id] = energy["total"]
  1024. logger.info(
  1025. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  1026. )
  1027. else:
  1028. logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  1029. else:
  1030. logger.info("[ENERGY] No smart plug found for printer %s", printer_id)
  1031. except Exception as e:
  1032. logger.warning("Failed to record starting energy: %s", e)
  1033. await ws_manager.send_archive_updated(
  1034. {
  1035. "id": archive.id,
  1036. "status": "printing",
  1037. }
  1038. )
  1039. # Send notification with archive data (reprint/scheduled)
  1040. if not notification_sent:
  1041. archive_data = {"print_time_seconds": archive.print_time_seconds}
  1042. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1043. # Extract printable objects from the archived 3MF file
  1044. _load_objects_from_archive(archive, printer_id, logger)
  1045. # Store Spoolman tracking data for per-filament usage reporting
  1046. try:
  1047. await _store_spoolman_print_data(printer_id, archive.id, archive.file_path, db, printer_manager)
  1048. except Exception as e:
  1049. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1050. return # Skip creating a new archive
  1051. # Check if there's already a "printing" archive for this printer/file
  1052. # This prevents duplicates when backend restarts during an active print
  1053. from backend.app.models.archive import PrintArchive
  1054. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  1055. existing = await db.execute(
  1056. select(PrintArchive)
  1057. .where(PrintArchive.printer_id == printer_id)
  1058. .where(PrintArchive.status == "printing")
  1059. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  1060. .order_by(PrintArchive.created_at.desc())
  1061. .limit(1)
  1062. )
  1063. existing_archive = existing.scalar_one_or_none()
  1064. if existing_archive:
  1065. # Check if archive is stale (older than 4 hours) - likely a failed/cancelled print
  1066. # that didn't get properly updated
  1067. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  1068. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  1069. logger.warning(
  1070. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  1071. f"marking as cancelled and creating new archive"
  1072. )
  1073. existing_archive.status = "cancelled"
  1074. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  1075. await db.commit()
  1076. # Fall through to create new archive (don't return)
  1077. _existing_archive = None # Clear so we don't use stale archive
  1078. else:
  1079. logger.info(
  1080. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  1081. )
  1082. # Track this as the active print
  1083. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1084. # Also set up energy tracking if not already tracked
  1085. if existing_archive.id not in _print_energy_start:
  1086. try:
  1087. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1088. plug = plug_result.scalar_one_or_none()
  1089. if plug:
  1090. energy = await _get_plug_energy(plug, db)
  1091. if energy and energy.get("total") is not None:
  1092. _print_energy_start[existing_archive.id] = energy["total"]
  1093. logger.info(
  1094. f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh"
  1095. )
  1096. except Exception as e:
  1097. logger.warning("Failed to record starting energy for existing archive: %s", e)
  1098. # Send notification with archive data (existing archive)
  1099. if not notification_sent:
  1100. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  1101. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1102. # Extract printable objects from the archived 3MF file
  1103. _load_objects_from_archive(existing_archive, printer_id, logger)
  1104. return
  1105. # Build list of possible 3MF filenames to try
  1106. possible_names = []
  1107. # Bambu printers typically store files as "Name.gcode.3mf"
  1108. # The subtask_name is usually the best source for the filename
  1109. if subtask_name:
  1110. # Try common Bambu naming patterns
  1111. possible_names.append(f"{subtask_name}.gcode.3mf")
  1112. possible_names.append(f"{subtask_name}.3mf")
  1113. # Try original filename with .3mf extension
  1114. if filename:
  1115. # Extract just the filename part, not the full path
  1116. fname = filename.split("/")[-1] if "/" in filename else filename
  1117. if fname.endswith(".3mf"):
  1118. possible_names.append(fname)
  1119. elif fname.endswith(".gcode"):
  1120. base = fname.rsplit(".", 1)[0]
  1121. possible_names.append(f"{base}.gcode.3mf")
  1122. possible_names.append(f"{base}.3mf")
  1123. else:
  1124. possible_names.append(f"{fname}.gcode.3mf")
  1125. possible_names.append(f"{fname}.3mf")
  1126. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1127. space_variants = []
  1128. for name in possible_names:
  1129. if " " in name:
  1130. space_variants.append(name.replace(" ", "_"))
  1131. possible_names.extend(space_variants)
  1132. # Remove duplicates while preserving order
  1133. seen = set()
  1134. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  1135. logger.info("Trying filenames: %s", possible_names)
  1136. # Try to find and download the 3MF file
  1137. temp_path = None
  1138. downloaded_filename = None
  1139. # Get FTP retry settings
  1140. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1141. for try_filename in possible_names:
  1142. if not try_filename.endswith(".3mf"):
  1143. continue
  1144. remote_paths = [
  1145. f"/cache/{try_filename}",
  1146. f"/model/{try_filename}",
  1147. f"/data/{try_filename}",
  1148. f"/data/Metadata/{try_filename}",
  1149. f"/{try_filename}",
  1150. ]
  1151. temp_path = app_settings.archive_dir / "temp" / try_filename
  1152. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1153. for remote_path in remote_paths:
  1154. logger.debug("Trying FTP download: %s", remote_path)
  1155. try:
  1156. if ftp_retry_enabled:
  1157. downloaded = await with_ftp_retry(
  1158. download_file_async,
  1159. printer.ip_address,
  1160. printer.access_code,
  1161. remote_path,
  1162. temp_path,
  1163. socket_timeout=ftp_timeout,
  1164. printer_model=printer.model,
  1165. max_retries=ftp_retry_count,
  1166. retry_delay=ftp_retry_delay,
  1167. operation_name=f"Download 3MF from {remote_path}",
  1168. )
  1169. else:
  1170. downloaded = await download_file_async(
  1171. printer.ip_address,
  1172. printer.access_code,
  1173. remote_path,
  1174. temp_path,
  1175. socket_timeout=ftp_timeout,
  1176. printer_model=printer.model,
  1177. )
  1178. if downloaded:
  1179. downloaded_filename = try_filename
  1180. logger.info("Downloaded: %s", remote_path)
  1181. break
  1182. except Exception as e:
  1183. logger.debug("FTP download failed for %s: %s", remote_path, e)
  1184. if downloaded_filename:
  1185. break
  1186. # If still not found, try listing directories to find matching file
  1187. # Different printer models use different directory structures
  1188. if not downloaded_filename and (filename or subtask_name):
  1189. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  1190. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  1191. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  1192. for search_dir in search_dirs:
  1193. if downloaded_filename:
  1194. break
  1195. try:
  1196. dir_files = await list_files_async(
  1197. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  1198. )
  1199. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  1200. if threemf_files:
  1201. logger.info(
  1202. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  1203. )
  1204. for f in dir_files:
  1205. if f.get("is_directory"):
  1206. continue
  1207. fname = f.get("name", "")
  1208. # Normalize both for comparison (spaces and underscores are equivalent)
  1209. fname_normalized = fname.lower().replace(" ", "_")
  1210. search_normalized = search_term.replace(" ", "_")
  1211. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  1212. logger.info("Found matching file in %s: %s", search_dir, fname)
  1213. temp_path = app_settings.archive_dir / "temp" / fname
  1214. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1215. if ftp_retry_enabled:
  1216. downloaded = await with_ftp_retry(
  1217. download_file_async,
  1218. printer.ip_address,
  1219. printer.access_code,
  1220. f"{search_dir}/{fname}",
  1221. temp_path,
  1222. socket_timeout=ftp_timeout,
  1223. printer_model=printer.model,
  1224. max_retries=ftp_retry_count,
  1225. retry_delay=ftp_retry_delay,
  1226. operation_name=f"Download 3MF from {search_dir}/{fname}",
  1227. )
  1228. else:
  1229. downloaded = await download_file_async(
  1230. printer.ip_address,
  1231. printer.access_code,
  1232. f"{search_dir}/{fname}",
  1233. temp_path,
  1234. socket_timeout=ftp_timeout,
  1235. printer_model=printer.model,
  1236. )
  1237. if downloaded:
  1238. downloaded_filename = fname
  1239. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  1240. break
  1241. except Exception as e:
  1242. logger.debug("Failed to list %s: %s", search_dir, e)
  1243. if not downloaded_filename or not temp_path:
  1244. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  1245. # Create a fallback archive without 3MF data so the print is still tracked
  1246. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  1247. try:
  1248. from backend.app.models.archive import PrintArchive
  1249. # Derive print name from subtask_name or filename
  1250. print_name = subtask_name or filename
  1251. if print_name:
  1252. # Clean up the name (remove extensions, path parts)
  1253. print_name = print_name.split("/")[-1]
  1254. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1255. else:
  1256. print_name = "Unknown Print"
  1257. # Create minimal archive entry
  1258. fallback_archive = PrintArchive(
  1259. printer_id=printer_id,
  1260. filename=filename or f"{print_name}.3mf",
  1261. file_path="", # Empty - no 3MF file available
  1262. file_size=0,
  1263. print_name=print_name,
  1264. status="printing",
  1265. started_at=datetime.now(),
  1266. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  1267. )
  1268. db.add(fallback_archive)
  1269. await db.commit()
  1270. await db.refresh(fallback_archive)
  1271. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  1272. # Start timelapse session if external camera is enabled
  1273. if printer.external_camera_enabled and printer.external_camera_url:
  1274. from backend.app.services.layer_timelapse import start_session
  1275. start_session(
  1276. printer_id,
  1277. fallback_archive.id,
  1278. printer.external_camera_url,
  1279. printer.external_camera_type or "mjpeg",
  1280. )
  1281. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, fallback_archive.id)
  1282. # Track as active print
  1283. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  1284. if filename:
  1285. _active_prints[(printer_id, filename)] = fallback_archive.id
  1286. if subtask_name:
  1287. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  1288. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  1289. # Record starting energy if smart plug available
  1290. try:
  1291. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1292. plug = plug_result.scalar_one_or_none()
  1293. if plug:
  1294. energy = await _get_plug_energy(plug, db)
  1295. if energy and energy.get("total") is not None:
  1296. _print_energy_start[fallback_archive.id] = energy["total"]
  1297. logger.info(
  1298. f"[ENERGY] Recorded starting energy for fallback archive {fallback_archive.id}: {energy['total']} kWh"
  1299. )
  1300. except Exception as e:
  1301. logger.warning("Failed to record starting energy for fallback: %s", e)
  1302. # Send WebSocket notification
  1303. await ws_manager.send_archive_created(
  1304. {
  1305. "id": fallback_archive.id,
  1306. "printer_id": fallback_archive.printer_id,
  1307. "filename": fallback_archive.filename,
  1308. "print_name": fallback_archive.print_name,
  1309. "status": fallback_archive.status,
  1310. }
  1311. )
  1312. # MQTT relay - publish archive created
  1313. try:
  1314. await mqtt_relay.on_archive_created(
  1315. archive_id=fallback_archive.id,
  1316. print_name=fallback_archive.print_name,
  1317. printer_name=printer.name,
  1318. status=fallback_archive.status,
  1319. )
  1320. except Exception:
  1321. pass # Don't fail if MQTT fails
  1322. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  1323. try:
  1324. await _store_spoolman_print_data(
  1325. printer_id, fallback_archive.id, fallback_archive.file_path, db, printer_manager
  1326. )
  1327. except Exception as e:
  1328. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  1329. # Send notification without archive data (file not found)
  1330. if not notification_sent:
  1331. await _send_print_start_notification(printer_id, data, logger=logger)
  1332. return
  1333. except Exception as e:
  1334. logger.error("Failed to create fallback archive: %s", e)
  1335. # Send notification without archive data (file not found)
  1336. if not notification_sent:
  1337. await _send_print_start_notification(printer_id, data, logger=logger)
  1338. return
  1339. try:
  1340. # Archive the file with status "printing"
  1341. service = ArchiveService(db)
  1342. archive = await service.archive_print(
  1343. printer_id=printer_id,
  1344. source_file=temp_path,
  1345. print_data={**data, "status": "printing"},
  1346. )
  1347. if archive:
  1348. # Track this active print (use both original filename and downloaded filename)
  1349. _active_prints[(printer_id, downloaded_filename)] = archive.id
  1350. if filename and filename != downloaded_filename:
  1351. _active_prints[(printer_id, filename)] = archive.id
  1352. if subtask_name:
  1353. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1354. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  1355. # Start timelapse session if external camera is enabled
  1356. if printer.external_camera_enabled and printer.external_camera_url:
  1357. from backend.app.services.layer_timelapse import start_session
  1358. start_session(
  1359. printer_id,
  1360. archive.id,
  1361. printer.external_camera_url,
  1362. printer.external_camera_type or "mjpeg",
  1363. )
  1364. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, archive.id)
  1365. # Record starting energy from smart plug if available
  1366. try:
  1367. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1368. plug = plug_result.scalar_one_or_none()
  1369. logger.info(
  1370. f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  1371. )
  1372. if plug:
  1373. energy = await _get_plug_energy(plug, db)
  1374. logger.info("[ENERGY] Auto-archive energy response: %s", energy)
  1375. if energy and energy.get("total") is not None:
  1376. _print_energy_start[archive.id] = energy["total"]
  1377. logger.info(
  1378. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  1379. )
  1380. else:
  1381. logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  1382. else:
  1383. logger.info("[ENERGY] No smart plug found for printer %s", printer_id)
  1384. except Exception as e:
  1385. logger.warning("Failed to record starting energy: %s", e)
  1386. await ws_manager.send_archive_created(
  1387. {
  1388. "id": archive.id,
  1389. "printer_id": archive.printer_id,
  1390. "filename": archive.filename,
  1391. "print_name": archive.print_name,
  1392. "status": archive.status,
  1393. }
  1394. )
  1395. # MQTT relay - publish archive created
  1396. try:
  1397. await mqtt_relay.on_archive_created(
  1398. archive_id=archive.id,
  1399. print_name=archive.print_name,
  1400. printer_name=printer.name,
  1401. status=archive.status,
  1402. )
  1403. except Exception:
  1404. pass # Don't fail if MQTT fails
  1405. # Send notification with archive data (new archive created)
  1406. if not notification_sent:
  1407. archive_data = {"print_time_seconds": archive.print_time_seconds}
  1408. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1409. # Extract printable objects for skip object functionality
  1410. try:
  1411. from backend.app.services.archive import extract_printable_objects_from_3mf
  1412. with open(temp_path, "rb") as f:
  1413. threemf_data = f.read()
  1414. # Extract with positions for UI overlay
  1415. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  1416. threemf_data, include_positions=True
  1417. )
  1418. if printable_objects:
  1419. # Store objects in printer state
  1420. client = printer_manager.get_client(printer_id)
  1421. if client:
  1422. client.state.printable_objects = printable_objects
  1423. client.state.printable_objects_bbox_all = bbox_all
  1424. client.state.skipped_objects = [] # Reset skipped objects for new print
  1425. logger.info(
  1426. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  1427. )
  1428. except Exception as e:
  1429. logger.debug("Failed to extract printable objects: %s", e)
  1430. # Store Spoolman tracking data for per-filament usage reporting
  1431. try:
  1432. await _store_spoolman_print_data(printer_id, archive.id, archive.file_path, db, printer_manager)
  1433. except Exception as e:
  1434. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1435. # Capture timelapse file baseline for snapshot-diff on completion
  1436. try:
  1437. baseline_files, _ = await _list_timelapse_mp4s(printer)
  1438. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  1439. logger.info(
  1440. "[TIMELAPSE] Baseline at print start: %s MP4 files for printer %s",
  1441. len(_timelapse_baselines[printer_id]),
  1442. printer_id,
  1443. )
  1444. except Exception as e:
  1445. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  1446. finally:
  1447. if temp_path and temp_path.exists():
  1448. temp_path.unlink()
  1449. async def _list_timelapse_mp4s(printer) -> tuple[list[dict], str | None]:
  1450. """List MP4 files from printer's timelapse directory.
  1451. Returns (mp4_files, found_path) where mp4_files is a list of file dicts
  1452. and found_path is the directory where they were found, or ([], None).
  1453. """
  1454. from backend.app.services.bambu_ftp import list_files_async
  1455. logger = logging.getLogger(__name__)
  1456. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1457. try:
  1458. found_files = await list_files_async(
  1459. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1460. )
  1461. if found_files:
  1462. mp4_files = [f for f in found_files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  1463. if mp4_files:
  1464. return mp4_files, timelapse_path
  1465. except Exception as e:
  1466. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  1467. continue
  1468. return [], None
  1469. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  1470. """
  1471. Scan for timelapse with retries using a snapshot-diff approach.
  1472. Instead of picking the "most recent by mtime" (unreliable when the printer
  1473. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  1474. waiting, then look for any NEW filename that appears after each delay.
  1475. If baseline_names is provided (captured at print start), it is used directly.
  1476. Otherwise falls back to taking a baseline at completion time (best-effort
  1477. for prints started before app restart).
  1478. Falls back to name-matching (print name contained in MP4 filename) if no
  1479. new file appears after all retries.
  1480. """
  1481. from pathlib import Path
  1482. logger = logging.getLogger(__name__)
  1483. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  1484. try:
  1485. async with async_session() as db:
  1486. from backend.app.models.printer import Printer
  1487. service = ArchiveService(db)
  1488. archive = await service.get_archive(archive_id)
  1489. if not archive:
  1490. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  1491. return
  1492. if archive.timelapse_path:
  1493. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  1494. return
  1495. if not archive.printer_id:
  1496. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  1497. return
  1498. if baseline_names is not None:
  1499. # Use pre-captured baseline from print start (no race condition)
  1500. logger.info(
  1501. "[TIMELAPSE] Using print-start baseline: %s existing MP4 files for archive %s",
  1502. len(baseline_names),
  1503. archive_id,
  1504. )
  1505. else:
  1506. # Fallback: take baseline now (e.g. app restarted mid-print)
  1507. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1508. printer = result.scalar_one_or_none()
  1509. if not printer:
  1510. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  1511. return
  1512. baseline_files, _ = await _list_timelapse_mp4s(printer)
  1513. baseline_names = {f.get("name", "") for f in baseline_files}
  1514. logger.info(
  1515. "[TIMELAPSE] Baseline snapshot (fallback): %s existing MP4 files for archive %s",
  1516. len(baseline_names),
  1517. archive_id,
  1518. )
  1519. # Derive base_name for name-matching fallback
  1520. base_name = Path(archive.filename).stem if archive.filename else ""
  1521. if base_name.endswith(".gcode"):
  1522. base_name = base_name[:-6]
  1523. except Exception as e:
  1524. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  1525. return
  1526. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  1527. retry_delays = [5, 10, 20, 30]
  1528. for attempt, delay in enumerate(retry_delays, 1):
  1529. logger.info(
  1530. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  1531. attempt,
  1532. len(retry_delays),
  1533. delay,
  1534. archive_id,
  1535. )
  1536. await asyncio.sleep(delay)
  1537. try:
  1538. async with async_session() as db:
  1539. from backend.app.models.printer import Printer
  1540. from backend.app.services.bambu_ftp import download_file_bytes_async
  1541. service = ArchiveService(db)
  1542. archive = await service.get_archive(archive_id)
  1543. if not archive:
  1544. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  1545. return
  1546. if archive.timelapse_path:
  1547. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  1548. return
  1549. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1550. printer = result.scalar_one_or_none()
  1551. if not printer:
  1552. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  1553. return
  1554. mp4_files, found_path = await _list_timelapse_mp4s(printer)
  1555. if not mp4_files:
  1556. logger.info("[TIMELAPSE] Attempt %s: No MP4 files found, will retry", attempt)
  1557. continue
  1558. logger.info("[TIMELAPSE] Attempt %s: Found %s MP4 files in %s", attempt, len(mp4_files), found_path)
  1559. for f in mp4_files[:5]:
  1560. logger.info("[TIMELAPSE] - %s", f.get("name"))
  1561. # Find files that are NEW (not in baseline snapshot)
  1562. new_files = [f for f in mp4_files if f.get("name", "") not in baseline_names]
  1563. if new_files:
  1564. # Pick the first new file (there should typically be exactly one)
  1565. target = new_files[0]
  1566. file_name = target.get("name")
  1567. remote_path = target.get("path") or f"/timelapse/{file_name}"
  1568. logger.info(
  1569. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  1570. attempt,
  1571. file_name,
  1572. archive_id,
  1573. )
  1574. timelapse_data = await download_file_bytes_async(
  1575. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  1576. )
  1577. if timelapse_data:
  1578. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  1579. if success:
  1580. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  1581. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  1582. return
  1583. else:
  1584. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  1585. else:
  1586. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  1587. else:
  1588. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  1589. except Exception as e:
  1590. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  1591. # --- Phase 3: Fallback — try name matching against all files ---
  1592. if base_name:
  1593. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  1594. try:
  1595. async with async_session() as db:
  1596. from backend.app.models.printer import Printer
  1597. from backend.app.services.bambu_ftp import download_file_bytes_async
  1598. service = ArchiveService(db)
  1599. archive = await service.get_archive(archive_id)
  1600. if not archive or archive.timelapse_path:
  1601. return
  1602. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1603. printer = result.scalar_one_or_none()
  1604. if not printer:
  1605. return
  1606. mp4_files, found_path = await _list_timelapse_mp4s(printer)
  1607. for f in mp4_files:
  1608. fname = f.get("name", "")
  1609. if base_name.lower() in fname.lower():
  1610. remote_path = f.get("path") or f"/timelapse/{fname}"
  1611. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  1612. timelapse_data = await download_file_bytes_async(
  1613. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  1614. )
  1615. if timelapse_data:
  1616. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  1617. if success:
  1618. logger.info(
  1619. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  1620. )
  1621. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  1622. return
  1623. break # Only try the first name match
  1624. except Exception as e:
  1625. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  1626. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  1627. async def on_print_complete(printer_id: int, data: dict):
  1628. """Handle print completion - update the archive status."""
  1629. import time
  1630. logger = logging.getLogger(__name__)
  1631. start_time = time.time()
  1632. def log_timing(section: str):
  1633. elapsed = time.time() - start_time
  1634. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  1635. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  1636. try:
  1637. ws_data = {
  1638. "status": data.get("status"),
  1639. "filename": data.get("filename"),
  1640. "subtask_name": data.get("subtask_name"),
  1641. "timelapse_was_active": data.get("timelapse_was_active"),
  1642. }
  1643. await ws_manager.send_print_complete(printer_id, ws_data)
  1644. log_timing("WebSocket send_print_complete")
  1645. except Exception as e:
  1646. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  1647. # Clear current print user tracking (Issue #206)
  1648. printer_manager.clear_current_print_user(printer_id)
  1649. # MQTT relay - publish print complete
  1650. try:
  1651. printer_info = printer_manager.get_printer(printer_id)
  1652. if printer_info:
  1653. await mqtt_relay.on_print_complete(
  1654. printer_id,
  1655. printer_info.name,
  1656. printer_info.serial_number,
  1657. data.get("filename", ""),
  1658. data.get("subtask_name", ""),
  1659. data.get("status", "completed"),
  1660. )
  1661. except Exception:
  1662. pass # Don't fail print complete callback if MQTT fails
  1663. filename = data.get("filename", "")
  1664. subtask_name = data.get("subtask_name", "")
  1665. if not filename and not subtask_name:
  1666. logger.warning("Print complete without filename or subtask_name")
  1667. return
  1668. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  1669. # Build list of possible keys to try (matching how they were registered in on_print_start)
  1670. possible_keys = []
  1671. # Try subtask_name variations first (most reliable for matching)
  1672. if subtask_name:
  1673. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  1674. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1675. possible_keys.append((printer_id, subtask_name))
  1676. # Try filename variations
  1677. if filename:
  1678. # Extract just the filename if it's a path
  1679. fname = filename.split("/")[-1] if "/" in filename else filename
  1680. if fname.endswith(".3mf"):
  1681. possible_keys.append((printer_id, fname))
  1682. elif fname.endswith(".gcode"):
  1683. base_name = fname.rsplit(".", 1)[0]
  1684. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  1685. possible_keys.append((printer_id, f"{base_name}.3mf"))
  1686. possible_keys.append((printer_id, fname))
  1687. else:
  1688. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  1689. possible_keys.append((printer_id, f"{fname}.3mf"))
  1690. possible_keys.append((printer_id, fname))
  1691. # Also try full path versions
  1692. if filename.endswith(".3mf"):
  1693. possible_keys.append((printer_id, filename))
  1694. elif filename.endswith(".gcode"):
  1695. base_name = filename.rsplit(".", 1)[0]
  1696. possible_keys.append((printer_id, f"{base_name}.3mf"))
  1697. possible_keys.append((printer_id, filename))
  1698. else:
  1699. possible_keys.append((printer_id, f"{filename}.3mf"))
  1700. possible_keys.append((printer_id, filename))
  1701. # Find the archive for this print
  1702. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  1703. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  1704. archive_id = None
  1705. for key in possible_keys:
  1706. archive_id = _active_prints.pop(key, None)
  1707. if archive_id:
  1708. logger.info("Found archive %s with key %s", archive_id, key)
  1709. # Also clean up any other keys pointing to this archive
  1710. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  1711. for k in keys_to_remove:
  1712. _active_prints.pop(k, None)
  1713. break
  1714. if not archive_id:
  1715. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  1716. async with async_session() as db:
  1717. from backend.app.models.archive import PrintArchive
  1718. # Try matching by subtask_name (stored as print_name) first
  1719. if subtask_name:
  1720. result = await db.execute(
  1721. select(PrintArchive)
  1722. .where(PrintArchive.printer_id == printer_id)
  1723. .where(PrintArchive.status == "printing")
  1724. .where(
  1725. or_(
  1726. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  1727. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  1728. )
  1729. )
  1730. .order_by(PrintArchive.created_at.desc())
  1731. .limit(1)
  1732. )
  1733. archive = result.scalar_one_or_none()
  1734. if archive:
  1735. archive_id = archive.id
  1736. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  1737. # Also try by filename
  1738. if not archive_id and filename:
  1739. result = await db.execute(
  1740. select(PrintArchive)
  1741. .where(PrintArchive.printer_id == printer_id)
  1742. .where(PrintArchive.filename == filename)
  1743. .where(PrintArchive.status == "printing")
  1744. .order_by(PrintArchive.created_at.desc())
  1745. .limit(1)
  1746. )
  1747. archive = result.scalar_one_or_none()
  1748. if archive:
  1749. archive_id = archive.id
  1750. if not archive_id:
  1751. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  1752. return
  1753. log_timing("Archive lookup")
  1754. # Update archive status
  1755. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  1756. try:
  1757. async with async_session() as db:
  1758. service = ArchiveService(db)
  1759. status = data.get("status", "completed")
  1760. # Auto-detect failure reason
  1761. failure_reason = None
  1762. if status == "aborted":
  1763. failure_reason = "User cancelled"
  1764. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  1765. elif status == "failed":
  1766. # Try to determine failure reason from HMS errors
  1767. hms_errors = data.get("hms_errors", [])
  1768. if hms_errors:
  1769. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  1770. # Map known HMS error modules to failure reasons
  1771. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  1772. for err in hms_errors:
  1773. module = err.get("module", 0)
  1774. if module == 0x07: # Filament module
  1775. failure_reason = "Filament runout"
  1776. break
  1777. elif module == 0x0C: # Motion controller
  1778. failure_reason = "Layer shift"
  1779. break
  1780. elif module == 0x05: # Nozzle/extruder
  1781. failure_reason = "Clogged nozzle"
  1782. break
  1783. if failure_reason:
  1784. logger.info("[ARCHIVE] Detected failure_reason from HMS: %s", failure_reason)
  1785. else:
  1786. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  1787. await service.update_archive_status(
  1788. archive_id,
  1789. status=status,
  1790. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  1791. failure_reason=failure_reason,
  1792. )
  1793. logger.info(
  1794. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  1795. )
  1796. # Add cost for reprints (first prints have cost set in archive_print())
  1797. if status == "completed" and archive_id in _reprint_archives:
  1798. _reprint_archives.discard(archive_id)
  1799. try:
  1800. await service.add_reprint_cost(archive_id)
  1801. logger.info("[ARCHIVE] Added reprint cost for archive %s", archive_id)
  1802. except Exception as e:
  1803. logger.warning("[ARCHIVE] Failed to add reprint cost for archive %s: %s", archive_id, e)
  1804. await ws_manager.send_archive_updated(
  1805. {
  1806. "id": archive_id,
  1807. "status": status,
  1808. }
  1809. )
  1810. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  1811. # MQTT relay - publish archive updated
  1812. try:
  1813. await mqtt_relay.on_archive_updated(
  1814. archive_id=archive_id,
  1815. print_name=filename or subtask_name,
  1816. status=status,
  1817. )
  1818. except Exception:
  1819. pass # Don't fail if MQTT fails
  1820. except Exception as e:
  1821. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  1822. # Continue with other operations even if archive update fails
  1823. log_timing("Archive status update")
  1824. # Track filament consumption from AMS remain% deltas (skip if Spoolman handles usage)
  1825. try:
  1826. async with async_session() as db:
  1827. from backend.app.api.routes.settings import get_setting
  1828. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1829. if not _spoolman_on or _spoolman_on.lower() != "true":
  1830. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  1831. async with async_session() as db:
  1832. usage_results = await usage_on_print_complete(
  1833. printer_id, data, printer_manager, db, archive_id=archive_id
  1834. )
  1835. if usage_results:
  1836. await ws_manager.broadcast(
  1837. {
  1838. "type": "spool_usage_logged",
  1839. "printer_id": printer_id,
  1840. "usage": usage_results,
  1841. }
  1842. )
  1843. log_timing("Usage tracker")
  1844. except Exception as e:
  1845. logger.warning("Usage tracker on_print_complete failed: %s", e)
  1846. # Report filament usage to Spoolman if print completed successfully
  1847. if data.get("status") == "completed":
  1848. try:
  1849. await _report_spoolman_usage(printer_id, archive_id)
  1850. log_timing("Spoolman usage report")
  1851. except Exception as e:
  1852. logger.warning("Spoolman usage reporting failed: %s", e)
  1853. else:
  1854. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  1855. try:
  1856. async with async_session() as db:
  1857. await _cleanup_spoolman_tracking(printer_id, archive_id, db)
  1858. except Exception as e:
  1859. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  1860. # Run slow operations as background tasks to avoid blocking the event loop
  1861. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  1862. starting_kwh = _print_energy_start.pop(archive_id, None)
  1863. async def _background_energy_calculation():
  1864. """Calculate and save energy usage in background."""
  1865. try:
  1866. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  1867. async with async_session() as db:
  1868. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1869. plug = plug_result.scalar_one_or_none()
  1870. if plug:
  1871. energy = await _get_plug_energy(plug, db)
  1872. logger.info("[ENERGY-BG] Energy response: %s", energy)
  1873. energy_used = None
  1874. if starting_kwh is not None and energy and energy.get("total") is not None:
  1875. ending_kwh = energy["total"]
  1876. energy_used = round(ending_kwh - starting_kwh, 4)
  1877. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  1878. if energy_used is not None and energy_used >= 0:
  1879. from backend.app.api.routes.settings import get_setting
  1880. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  1881. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  1882. energy_cost = round(energy_used * cost_per_kwh, 2)
  1883. from backend.app.models.archive import PrintArchive
  1884. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1885. archive = result.scalar_one_or_none()
  1886. if archive:
  1887. archive.energy_kwh = energy_used
  1888. archive.energy_cost = energy_cost
  1889. await db.commit()
  1890. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost)
  1891. else:
  1892. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  1893. except Exception as e:
  1894. logger.warning("[ENERGY-BG] Failed: %s", e)
  1895. async def _background_finish_photo() -> str | None:
  1896. """Capture finish photo in background. Returns photo filename if captured."""
  1897. try:
  1898. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  1899. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1900. async with async_session() as db:
  1901. from backend.app.api.routes.settings import get_setting
  1902. capture_enabled = await get_setting(db, "capture_finish_photo")
  1903. if capture_enabled is None or capture_enabled.lower() == "true":
  1904. from backend.app.models.printer import Printer
  1905. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1906. printer = result.scalar_one_or_none()
  1907. if printer and archive_id:
  1908. from backend.app.models.archive import PrintArchive
  1909. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1910. archive = result.scalar_one_or_none()
  1911. if archive:
  1912. import uuid
  1913. from datetime import datetime
  1914. from pathlib import Path
  1915. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  1916. photo_filename = None
  1917. # Check for external camera first
  1918. if printer.external_camera_enabled and printer.external_camera_url:
  1919. logger.info("[PHOTO-BG] Using external camera")
  1920. from backend.app.services.external_camera import capture_frame
  1921. frame_data = await capture_frame(
  1922. printer.external_camera_url, printer.external_camera_type or "mjpeg"
  1923. )
  1924. if frame_data:
  1925. photos_dir = archive_dir / "photos"
  1926. photos_dir.mkdir(parents=True, exist_ok=True)
  1927. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1928. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1929. photo_path = photos_dir / photo_filename
  1930. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  1931. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  1932. else:
  1933. # Check if camera stream is active - use buffered frame to avoid freeze
  1934. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  1935. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1936. active_chamber_for_printer = [
  1937. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  1938. ]
  1939. buffered_frame = get_buffered_frame(printer_id)
  1940. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  1941. # Use frame from active stream
  1942. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  1943. photos_dir = archive_dir / "photos"
  1944. photos_dir.mkdir(parents=True, exist_ok=True)
  1945. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1946. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1947. photo_path = photos_dir / photo_filename
  1948. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  1949. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  1950. else:
  1951. # No active stream - capture new frame
  1952. from backend.app.services.camera import capture_finish_photo
  1953. photo_filename = await capture_finish_photo(
  1954. printer_id=printer_id,
  1955. ip_address=printer.ip_address,
  1956. access_code=printer.access_code,
  1957. model=printer.model,
  1958. archive_dir=archive_dir,
  1959. )
  1960. if photo_filename:
  1961. photos = archive.photos or []
  1962. photos.append(photo_filename)
  1963. archive.photos = photos
  1964. await db.commit()
  1965. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  1966. return photo_filename
  1967. return None
  1968. except Exception as e:
  1969. logger.warning("[PHOTO-BG] Failed: %s", e)
  1970. return None
  1971. asyncio.create_task(_background_energy_calculation())
  1972. # Photo capture task - result will be used by notifications
  1973. photo_task = asyncio.create_task(_background_finish_photo())
  1974. log_timing("Background tasks scheduled (energy, photo)")
  1975. # Also run smart plug, notifications, and maintenance as background tasks
  1976. print_status = data.get("status", "completed")
  1977. async def _background_smart_plug():
  1978. """Handle smart plug automation in background."""
  1979. try:
  1980. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  1981. async with async_session() as db:
  1982. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  1983. logger.info("[AUTO-OFF-BG] Completed")
  1984. except Exception as e:
  1985. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  1986. async def _background_notifications(finish_photo_filename: str | None = None):
  1987. """Send print complete notifications in background."""
  1988. try:
  1989. logger.info(
  1990. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  1991. )
  1992. async with async_session() as db:
  1993. from backend.app.models.archive import PrintArchive
  1994. from backend.app.models.printer import Printer
  1995. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1996. printer = result.scalar_one_or_none()
  1997. printer_name = printer.name if printer else f"Printer {printer_id}"
  1998. archive_data = None
  1999. if archive_id:
  2000. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2001. archive = archive_result.scalar_one_or_none()
  2002. if archive:
  2003. archive_data = {
  2004. "print_time_seconds": archive.print_time_seconds,
  2005. "actual_filament_grams": archive.filament_used_grams,
  2006. "failure_reason": archive.failure_reason,
  2007. }
  2008. # Add finish photo URL and image bytes if available
  2009. if finish_photo_filename:
  2010. from backend.app.api.routes.settings import get_setting
  2011. external_url = await get_setting(db, "external_url")
  2012. if external_url:
  2013. external_url = external_url.rstrip("/")
  2014. archive_data["finish_photo_url"] = (
  2015. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2016. )
  2017. else:
  2018. # Fallback to relative URL (won't work for external services)
  2019. archive_data["finish_photo_url"] = (
  2020. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2021. )
  2022. # Read finish photo bytes for image attachment (e.g. Pushover)
  2023. try:
  2024. from pathlib import Path
  2025. photo_path = (
  2026. app_settings.base_dir
  2027. / Path(archive.file_path).parent
  2028. / "photos"
  2029. / finish_photo_filename
  2030. )
  2031. if photo_path.exists():
  2032. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2033. if len(photo_bytes) <= 2_500_000:
  2034. archive_data["image_data"] = photo_bytes
  2035. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2036. else:
  2037. logger.warning(
  2038. f"[NOTIFY-BG] Finish photo too large for attachment: "
  2039. f"{len(photo_bytes)} bytes"
  2040. )
  2041. except Exception as e:
  2042. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2043. await notification_service.on_print_complete(
  2044. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  2045. )
  2046. logger.info("[NOTIFY-BG] Completed")
  2047. except Exception as e:
  2048. logger.warning("[NOTIFY-BG] Failed: %s", e)
  2049. async def _background_maintenance_check():
  2050. """Check for maintenance due in background."""
  2051. if print_status != "completed":
  2052. return
  2053. try:
  2054. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  2055. async with async_session() as db:
  2056. from backend.app.models.printer import Printer
  2057. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2058. printer = result.scalar_one_or_none()
  2059. printer_name = printer.name if printer else f"Printer {printer_id}"
  2060. await ensure_default_types(db)
  2061. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  2062. items_needing_attention = [
  2063. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  2064. for item in overview.maintenance_items
  2065. if item.enabled and (item.is_due or item.is_warning)
  2066. ]
  2067. if items_needing_attention:
  2068. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  2069. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  2070. # MQTT relay - publish maintenance alerts
  2071. for item in items_needing_attention:
  2072. try:
  2073. await mqtt_relay.on_maintenance_alert(
  2074. printer_id=printer_id,
  2075. printer_name=printer_name,
  2076. maintenance_type=item["name"],
  2077. current_value=0, # Not easily available here
  2078. threshold=0, # Not easily available here
  2079. )
  2080. except Exception:
  2081. pass # Don't fail if MQTT fails
  2082. else:
  2083. logger.info("[MAINT-BG] Completed (no items need attention)")
  2084. except Exception as e:
  2085. logger.warning("[MAINT-BG] Failed: %s", e)
  2086. asyncio.create_task(_background_smart_plug())
  2087. asyncio.create_task(_background_maintenance_check())
  2088. # Notification task waits for photo capture to complete first
  2089. async def _photo_then_notify():
  2090. """Wait for photo capture, then send notification with photo URL."""
  2091. try:
  2092. finish_photo = await photo_task
  2093. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  2094. await _background_notifications(finish_photo)
  2095. except Exception as e:
  2096. logger.warning("[PHOTO-NOTIFY] Failed: %s", e)
  2097. # Still try to send notification without photo
  2098. await _background_notifications(None)
  2099. asyncio.create_task(_photo_then_notify())
  2100. # Stitch external camera layer timelapse if session was active
  2101. print_status = data.get("status", "completed")
  2102. async def _background_layer_timelapse():
  2103. """Stitch layer timelapse and attach to archive."""
  2104. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  2105. try:
  2106. if print_status == "completed":
  2107. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  2108. timelapse_path = await tl_complete(printer_id)
  2109. if timelapse_path and archive_id:
  2110. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  2111. async with async_session() as db:
  2112. service = ArchiveService(db)
  2113. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  2114. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  2115. # Clean up the temp file
  2116. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2117. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  2118. elif timelapse_path:
  2119. # Timelapse created but no archive - just clean up
  2120. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2121. else:
  2122. # Print failed or cancelled - cancel timelapse session
  2123. cancel_session(printer_id)
  2124. logger.info(
  2125. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  2126. )
  2127. except Exception as e:
  2128. logger.warning("[LAYER-TL] Failed: %s", e)
  2129. # Try to cancel session on error
  2130. try:
  2131. cancel_session(printer_id)
  2132. except Exception:
  2133. pass # Best-effort timelapse session cancellation on error
  2134. asyncio.create_task(_background_layer_timelapse())
  2135. log_timing("All background tasks scheduled")
  2136. # Auto-scan for timelapse if recording was active during the print
  2137. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  2138. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  2139. # Schedule timelapse scan as background task with retries
  2140. # The printer needs time to encode the video after print completion
  2141. baseline = _timelapse_baselines.pop(printer_id, None)
  2142. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id, baseline))
  2143. log_timing("Timelapse scan scheduled")
  2144. # Update queue item if this was a scheduled print
  2145. try:
  2146. async with async_session() as db:
  2147. from backend.app.models.print_queue import PrintQueueItem
  2148. # Note: SmartPlug is already imported at module level (line 56)
  2149. # Do NOT import it here as it would shadow the module-level import
  2150. # and cause "cannot access local variable" errors earlier in this function
  2151. result = await db.execute(
  2152. select(PrintQueueItem)
  2153. .where(PrintQueueItem.printer_id == printer_id)
  2154. .where(PrintQueueItem.status == "printing")
  2155. )
  2156. queue_item = result.scalar_one_or_none()
  2157. if queue_item:
  2158. status = data.get("status", "completed")
  2159. queue_item.status = status
  2160. queue_item.completed_at = datetime.now()
  2161. await db.commit()
  2162. logger.info("Updated queue item %s status to %s", queue_item.id, status)
  2163. # MQTT relay - publish queue job completed
  2164. try:
  2165. printer_info = printer_manager.get_printer(printer_id)
  2166. await mqtt_relay.on_queue_job_completed(
  2167. job_id=queue_item.id,
  2168. filename=filename or subtask_name,
  2169. printer_id=printer_id,
  2170. printer_name=printer_info.name if printer_info else "Unknown",
  2171. status=status,
  2172. )
  2173. except Exception:
  2174. pass # Don't fail if MQTT fails
  2175. # Check if queue is now empty and send notification
  2176. try:
  2177. from sqlalchemy import func
  2178. # Count remaining pending items
  2179. count_result = await db.execute(
  2180. select(func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  2181. )
  2182. pending_count = count_result.scalar() or 0
  2183. if pending_count == 0:
  2184. # Count how many completed today (rough approximation)
  2185. today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
  2186. completed_result = await db.execute(
  2187. select(func.count(PrintQueueItem.id)).where(
  2188. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  2189. PrintQueueItem.completed_at >= today_start,
  2190. )
  2191. )
  2192. completed_count = completed_result.scalar() or 1
  2193. await notification_service.on_queue_completed(
  2194. completed_count=completed_count,
  2195. db=db,
  2196. )
  2197. except Exception:
  2198. pass # Don't fail if notification fails
  2199. # Handle auto_off_after - power off printer if requested (after cooldown)
  2200. if queue_item.auto_off_after:
  2201. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2202. plug = result.scalar_one_or_none()
  2203. if plug and plug.enabled:
  2204. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  2205. async def cooldown_and_poweroff(pid: int, plug_id: int):
  2206. # Wait for nozzle to cool down
  2207. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  2208. # Re-fetch plug in new session
  2209. async with async_session() as new_db:
  2210. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  2211. p = result.scalar_one_or_none()
  2212. if p and p.enabled:
  2213. success = await tasmota_service.turn_off(p)
  2214. if success:
  2215. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  2216. else:
  2217. logger.warning("Failed to power off printer %s via smart plug", pid)
  2218. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  2219. except Exception as e:
  2220. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  2221. log_timing("Queue item update")
  2222. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  2223. # AMS sensor history recording
  2224. _ams_history_task: asyncio.Task | None = None
  2225. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  2226. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  2227. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  2228. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  2229. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  2230. async def record_ams_history():
  2231. """Background task to record AMS humidity and temperature data."""
  2232. logger = logging.getLogger(__name__)
  2233. # Wait a short time for MQTT connections to establish on startup
  2234. await asyncio.sleep(10)
  2235. while True:
  2236. try:
  2237. from backend.app.models.ams_history import AMSSensorHistory
  2238. from backend.app.models.printer import Printer
  2239. from backend.app.models.settings import Settings
  2240. async with async_session() as db:
  2241. # Get all active printers
  2242. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2243. printers = result.scalars().all()
  2244. # Get alarm thresholds from settings
  2245. humidity_threshold = 60.0 # Default: fair threshold
  2246. temp_threshold = 35.0 # Default: fair threshold
  2247. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  2248. setting = result.scalar_one_or_none()
  2249. if setting:
  2250. try:
  2251. humidity_threshold = float(setting.value)
  2252. except (ValueError, TypeError):
  2253. pass # Keep default threshold if stored value is invalid
  2254. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  2255. setting = result.scalar_one_or_none()
  2256. if setting:
  2257. try:
  2258. temp_threshold = float(setting.value)
  2259. except (ValueError, TypeError):
  2260. pass # Keep default threshold if stored value is invalid
  2261. recorded_count = 0
  2262. for printer in printers:
  2263. # Get current state from printer manager
  2264. state = printer_manager.get_status(printer.id)
  2265. if not state or not state.connected or not state.raw_data:
  2266. continue # Skip disconnected printers - don't use stale data
  2267. raw_data = state.raw_data
  2268. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  2269. continue
  2270. # Record data for each AMS unit
  2271. for ams_data in raw_data["ams"]:
  2272. ams_id = int(ams_data.get("id", 0))
  2273. # Get humidity (prefer humidity_raw)
  2274. humidity_raw = ams_data.get("humidity_raw")
  2275. humidity_idx = ams_data.get("humidity")
  2276. humidity = None
  2277. if humidity_raw is not None:
  2278. try:
  2279. humidity = float(humidity_raw)
  2280. except (ValueError, TypeError):
  2281. pass # Skip unparseable humidity; will try fallback
  2282. if humidity is None and humidity_idx is not None:
  2283. try:
  2284. humidity = float(humidity_idx)
  2285. except (ValueError, TypeError):
  2286. pass # Skip unparseable humidity index value
  2287. # Get temperature
  2288. temperature = None
  2289. temp_str = ams_data.get("temp")
  2290. if temp_str is not None:
  2291. try:
  2292. temperature = float(temp_str)
  2293. except (ValueError, TypeError):
  2294. pass # Skip unparseable temperature value
  2295. # Skip if no data
  2296. if humidity is None and temperature is None:
  2297. continue
  2298. # Record the data point
  2299. history = AMSSensorHistory(
  2300. printer_id=printer.id,
  2301. ams_id=ams_id,
  2302. humidity=humidity,
  2303. humidity_raw=float(humidity_raw) if humidity_raw else None,
  2304. temperature=temperature,
  2305. )
  2306. db.add(history)
  2307. recorded_count += 1
  2308. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  2309. is_ams_ht = ams_id >= 128
  2310. if is_ams_ht:
  2311. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  2312. else:
  2313. ams_label = f"AMS-{chr(65 + ams_id)}"
  2314. # Check humidity alarm (only if above threshold)
  2315. if humidity is not None and humidity > humidity_threshold:
  2316. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  2317. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  2318. now = datetime.now()
  2319. if (
  2320. last_alarm is None
  2321. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  2322. ):
  2323. _ams_alarm_cooldown[cooldown_key] = now
  2324. logger.info(
  2325. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  2326. )
  2327. try:
  2328. # Call different notification method based on AMS type
  2329. if is_ams_ht:
  2330. await notification_service.on_ams_ht_humidity_high(
  2331. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  2332. )
  2333. else:
  2334. await notification_service.on_ams_humidity_high(
  2335. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  2336. )
  2337. except Exception as e:
  2338. logger.warning("Failed to send humidity alarm: %s", e)
  2339. # Check temperature alarm (only if above threshold)
  2340. if temperature is not None and temperature > temp_threshold:
  2341. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  2342. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  2343. now = datetime.now()
  2344. if (
  2345. last_alarm is None
  2346. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  2347. ):
  2348. _ams_alarm_cooldown[cooldown_key] = now
  2349. logger.info(
  2350. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  2351. )
  2352. try:
  2353. # Call different notification method based on AMS type
  2354. if is_ams_ht:
  2355. await notification_service.on_ams_ht_temperature_high(
  2356. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  2357. )
  2358. else:
  2359. await notification_service.on_ams_temperature_high(
  2360. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  2361. )
  2362. except Exception as e:
  2363. logger.warning("Failed to send temperature alarm: %s", e)
  2364. await db.commit()
  2365. if recorded_count > 0:
  2366. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  2367. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  2368. global _ams_cleanup_counter
  2369. _ams_cleanup_counter += 1
  2370. if _ams_cleanup_counter >= 288:
  2371. _ams_cleanup_counter = 0
  2372. # Get retention days from settings
  2373. from backend.app.models.settings import Settings
  2374. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  2375. setting = result.scalar_one_or_none()
  2376. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  2377. cutoff = datetime.now() - timedelta(days=retention_days)
  2378. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  2379. await db.commit()
  2380. if result.rowcount > 0:
  2381. logger.info(
  2382. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  2383. )
  2384. # Wait until next recording interval
  2385. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  2386. except asyncio.CancelledError:
  2387. break
  2388. except Exception as e:
  2389. logger.warning("AMS history recording failed: %s", e)
  2390. await asyncio.sleep(60) # Wait a bit before retrying
  2391. def start_ams_history_recording():
  2392. """Start the AMS history recording background task."""
  2393. global _ams_history_task
  2394. if _ams_history_task is None:
  2395. _ams_history_task = asyncio.create_task(record_ams_history())
  2396. logging.getLogger(__name__).info("AMS history recording started")
  2397. def stop_ams_history_recording():
  2398. """Stop the AMS history recording background task."""
  2399. global _ams_history_task
  2400. if _ams_history_task:
  2401. _ams_history_task.cancel()
  2402. _ams_history_task = None
  2403. logging.getLogger(__name__).info("AMS history recording stopped")
  2404. # Printer runtime tracking
  2405. _runtime_tracking_task: asyncio.Task | None = None
  2406. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  2407. async def track_printer_runtime():
  2408. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  2409. logger = logging.getLogger(__name__)
  2410. # Wait for MQTT connections to establish on startup
  2411. await asyncio.sleep(15)
  2412. while True:
  2413. try:
  2414. from backend.app.models.printer import Printer
  2415. async with async_session() as db:
  2416. # Get all active printers
  2417. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2418. printers = result.scalars().all()
  2419. now = datetime.now()
  2420. updated_count = 0
  2421. needs_commit = False
  2422. for printer in printers:
  2423. # Get current state from printer manager
  2424. state = printer_manager.get_status(printer.id)
  2425. if not state:
  2426. logger.debug("[%s] Runtime tracking: no state available", printer.name)
  2427. continue
  2428. if not state.connected:
  2429. logger.debug("[%s] Runtime tracking: not connected", printer.name)
  2430. continue
  2431. # Check if printer is in an active state (RUNNING or PAUSE)
  2432. if state.state in ("RUNNING", "PAUSE"):
  2433. # Calculate time since last update
  2434. if printer.last_runtime_update:
  2435. elapsed = (now - printer.last_runtime_update).total_seconds()
  2436. if elapsed > 0:
  2437. printer.runtime_seconds += int(elapsed)
  2438. updated_count += 1
  2439. needs_commit = True
  2440. logger.debug(
  2441. f"[{printer.name}] Runtime tracking: added {int(elapsed)}s, "
  2442. f"total={printer.runtime_seconds}s ({printer.runtime_seconds / 3600:.2f}h)"
  2443. )
  2444. else:
  2445. # First time seeing printer active - need to commit to save timestamp
  2446. needs_commit = True
  2447. logger.debug("[%s] Runtime tracking: first active detection", printer.name)
  2448. printer.last_runtime_update = now
  2449. else:
  2450. # Printer is idle/offline - clear last_runtime_update
  2451. if printer.last_runtime_update is not None:
  2452. logger.debug(
  2453. f"[{printer.name}] Runtime tracking: state={state.state}, clearing last_runtime_update"
  2454. )
  2455. printer.last_runtime_update = None
  2456. needs_commit = True
  2457. if needs_commit:
  2458. await db.commit()
  2459. if updated_count > 0:
  2460. logger.debug("Updated runtime for %s printer(s)", updated_count)
  2461. except asyncio.CancelledError:
  2462. logger.info("Runtime tracking cancelled")
  2463. break
  2464. except Exception as e:
  2465. logger.warning("Runtime tracking failed: %s", e)
  2466. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  2467. def start_runtime_tracking():
  2468. """Start the printer runtime tracking background task."""
  2469. global _runtime_tracking_task
  2470. if _runtime_tracking_task is None:
  2471. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  2472. logging.getLogger(__name__).info("Printer runtime tracking started")
  2473. def stop_runtime_tracking():
  2474. """Stop the printer runtime tracking background task."""
  2475. global _runtime_tracking_task
  2476. if _runtime_tracking_task:
  2477. _runtime_tracking_task.cancel()
  2478. _runtime_tracking_task = None
  2479. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  2480. @asynccontextmanager
  2481. async def lifespan(app: FastAPI):
  2482. # Startup
  2483. await init_db()
  2484. # Restore debug logging state from previous session
  2485. await init_debug_logging()
  2486. # Set up printer manager callbacks
  2487. loop = asyncio.get_event_loop()
  2488. printer_manager.set_event_loop(loop)
  2489. printer_manager.set_status_change_callback(on_printer_status_change)
  2490. printer_manager.set_print_start_callback(on_print_start)
  2491. printer_manager.set_print_complete_callback(on_print_complete)
  2492. printer_manager.set_ams_change_callback(on_ams_change)
  2493. # Layer change callback for external camera timelapse
  2494. async def on_layer_change(printer_id: int, layer_num: int):
  2495. """Capture timelapse frame on layer change."""
  2496. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  2497. await tl_layer_change(printer_id, layer_num)
  2498. printer_manager.set_layer_change_callback(on_layer_change)
  2499. # Initialize MQTT relay from settings
  2500. async with async_session() as db:
  2501. from backend.app.api.routes.settings import get_setting
  2502. mqtt_settings = {
  2503. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  2504. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  2505. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  2506. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  2507. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  2508. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  2509. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  2510. }
  2511. await mqtt_relay.configure(mqtt_settings)
  2512. # Restore MQTT smart plug subscriptions
  2513. if mqtt_settings.get("mqtt_enabled"):
  2514. from backend.app.models.smart_plug import SmartPlug
  2515. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  2516. mqtt_plugs = result.scalars().all()
  2517. for plug in mqtt_plugs:
  2518. if plug.mqtt_topic:
  2519. mqtt_relay.smart_plug_service.subscribe(
  2520. plug_id=plug.id,
  2521. topic=plug.mqtt_topic,
  2522. power_path=plug.mqtt_power_path,
  2523. energy_path=plug.mqtt_energy_path,
  2524. state_path=plug.mqtt_state_path,
  2525. multiplier=plug.mqtt_multiplier or 1.0,
  2526. )
  2527. if mqtt_plugs:
  2528. logging.info("Restored %s MQTT smart plug subscriptions", len(mqtt_plugs))
  2529. # Connect to all active printers
  2530. async with async_session() as db:
  2531. await init_printer_connections(db)
  2532. # Auto-connect to Spoolman if enabled
  2533. async with async_session() as db:
  2534. from backend.app.api.routes.settings import get_setting
  2535. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2536. spoolman_url = await get_setting(db, "spoolman_url")
  2537. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  2538. try:
  2539. client = await init_spoolman_client(spoolman_url)
  2540. if await client.health_check():
  2541. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  2542. # Ensure the 'tag' extra field exists for RFID/UUID storage
  2543. await client.ensure_tag_extra_field()
  2544. else:
  2545. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  2546. except Exception as e:
  2547. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  2548. # Start the print scheduler
  2549. asyncio.create_task(print_scheduler.run())
  2550. # Start the smart plug scheduler for time-based on/off
  2551. smart_plug_manager.start_scheduler()
  2552. # Resume any pending auto-offs that were interrupted by restart
  2553. await smart_plug_manager.resume_pending_auto_offs()
  2554. # Start the notification digest scheduler
  2555. notification_service.start_digest_scheduler()
  2556. # Start the GitHub backup scheduler
  2557. await github_backup_service.start_scheduler()
  2558. # Start AMS history recording
  2559. start_ams_history_recording()
  2560. # Start printer runtime tracking
  2561. start_runtime_tracking()
  2562. # Initialize virtual printer manager
  2563. from backend.app.services.virtual_printer import virtual_printer_manager
  2564. virtual_printer_manager.set_session_factory(async_session)
  2565. # Auto-start virtual printer if enabled
  2566. async with async_session() as db:
  2567. from backend.app.api.routes.settings import get_setting
  2568. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  2569. if vp_enabled and vp_enabled.lower() == "true":
  2570. vp_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  2571. vp_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  2572. vp_model = await get_setting(db, "virtual_printer_model") or ""
  2573. vp_target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  2574. vp_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  2575. # Look up printer IP and serial if in proxy mode
  2576. vp_target_ip = ""
  2577. vp_target_serial = ""
  2578. if vp_mode == "proxy" and vp_target_printer_id:
  2579. from backend.app.models.printer import Printer
  2580. result = await db.execute(select(Printer).where(Printer.id == int(vp_target_printer_id)))
  2581. printer = result.scalar_one_or_none()
  2582. if printer:
  2583. vp_target_ip = printer.ip_address
  2584. vp_target_serial = printer.serial_number
  2585. # Proxy mode requires target IP, other modes require access code
  2586. can_start = (vp_mode == "proxy" and vp_target_ip) or (vp_mode != "proxy" and vp_access_code)
  2587. if can_start:
  2588. try:
  2589. await virtual_printer_manager.configure(
  2590. enabled=True,
  2591. access_code=vp_access_code,
  2592. mode=vp_mode,
  2593. model=vp_model,
  2594. target_printer_ip=vp_target_ip,
  2595. target_printer_serial=vp_target_serial,
  2596. remote_interface_ip=vp_remote_iface,
  2597. )
  2598. if vp_mode == "proxy":
  2599. logging.info("Virtual printer proxy started (target=%s)", vp_target_ip)
  2600. else:
  2601. logging.info("Virtual printer started (model=%s)", vp_model or "default")
  2602. except Exception as e:
  2603. logging.warning("Failed to start virtual printer: %s", e)
  2604. yield
  2605. # Shutdown
  2606. print_scheduler.stop()
  2607. smart_plug_manager.stop_scheduler()
  2608. notification_service.stop_digest_scheduler()
  2609. github_backup_service.stop_scheduler()
  2610. stop_ams_history_recording()
  2611. stop_runtime_tracking()
  2612. printer_manager.disconnect_all()
  2613. await close_spoolman_client()
  2614. # Stop virtual printer if running
  2615. if virtual_printer_manager.is_enabled:
  2616. await virtual_printer_manager.configure(enabled=False)
  2617. await mqtt_smart_plug_service.disconnect(timeout=2)
  2618. await mqtt_relay.disconnect(timeout=2)
  2619. app = FastAPI(
  2620. title=app_settings.app_name,
  2621. description="Archive and manage Bambu Lab 3MF files",
  2622. version=APP_VERSION,
  2623. lifespan=lifespan,
  2624. )
  2625. # =============================================================================
  2626. # Authentication Middleware - Secures ALL API routes by default
  2627. # =============================================================================
  2628. # Public routes that don't require authentication even when auth is enabled
  2629. PUBLIC_API_ROUTES = {
  2630. # Auth routes needed before/during login
  2631. "/api/v1/auth/status",
  2632. "/api/v1/auth/login",
  2633. "/api/v1/auth/setup", # Needed for initial setup and recovery
  2634. "/api/v1/auth/advanced-auth/status", # Advanced auth status needed for login page
  2635. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  2636. # Version check for updates (no sensitive data)
  2637. "/api/v1/updates/version",
  2638. # Metrics endpoint handles its own prometheus_token authentication
  2639. "/api/v1/metrics",
  2640. }
  2641. # Route prefixes that are public (for routes with dynamic segments)
  2642. PUBLIC_API_PREFIXES = [
  2643. # WebSocket connections handle their own auth
  2644. "/api/v1/ws",
  2645. ]
  2646. # Route patterns that are public (read-only display data)
  2647. # These are checked with "in path" - needed because browsers load images/videos
  2648. # via <img src> and <video src> which don't include Authorization headers
  2649. PUBLIC_API_PATTERNS = [
  2650. # Thumbnails
  2651. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  2652. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  2653. # Images and media
  2654. "/photos/", # /archives/{id}/photos/{filename}
  2655. "/project-image/", # /archives/{id}/project-image/{path}
  2656. "/qrcode", # /archives/{id}/qrcode
  2657. "/timelapse", # /archives/{id}/timelapse (video)
  2658. "/cover", # /printers/{id}/cover
  2659. "/icon", # /external-links/{id}/icon
  2660. # Camera (streams loaded via <img> tag)
  2661. "/camera/stream", # /printers/{id}/camera/stream
  2662. "/camera/snapshot", # /printers/{id}/camera/snapshot
  2663. ]
  2664. @app.middleware("http")
  2665. async def auth_middleware(request, call_next):
  2666. """Enforce authentication on all API routes when auth is enabled.
  2667. This middleware provides defense-in-depth by checking auth at the API gateway level,
  2668. regardless of whether individual routes have auth dependencies.
  2669. """
  2670. from starlette.responses import JSONResponse
  2671. path = request.url.path
  2672. # Only apply to API routes
  2673. if not path.startswith("/api/"):
  2674. return await call_next(request)
  2675. # Allow public routes
  2676. if path in PUBLIC_API_ROUTES:
  2677. return await call_next(request)
  2678. # Allow public prefixes
  2679. for prefix in PUBLIC_API_PREFIXES:
  2680. if path.startswith(prefix):
  2681. return await call_next(request)
  2682. # Allow public patterns (read-only display data like thumbnails)
  2683. for pattern in PUBLIC_API_PATTERNS:
  2684. if pattern in path:
  2685. return await call_next(request)
  2686. # Check if auth is enabled
  2687. try:
  2688. async with async_session() as db:
  2689. from backend.app.core.auth import is_auth_enabled
  2690. auth_enabled = await is_auth_enabled(db)
  2691. if not auth_enabled:
  2692. # Auth disabled, allow all requests
  2693. return await call_next(request)
  2694. except Exception:
  2695. # If we can't check auth status, allow request (fail open for DB issues)
  2696. return await call_next(request)
  2697. # Auth is enabled - require valid token
  2698. auth_header = request.headers.get("Authorization")
  2699. x_api_key = request.headers.get("X-API-Key")
  2700. # Check for API key auth first
  2701. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  2702. # API key authentication - let the request through to be validated by route handler
  2703. # API keys are validated per-route since they have different permission levels
  2704. return await call_next(request)
  2705. # Check for JWT auth
  2706. if not auth_header or not auth_header.startswith("Bearer "):
  2707. return JSONResponse(
  2708. status_code=401,
  2709. content={"detail": "Authentication required"},
  2710. headers={"WWW-Authenticate": "Bearer"},
  2711. )
  2712. # Validate JWT token
  2713. import jwt
  2714. try:
  2715. from backend.app.core.auth import ALGORITHM, SECRET_KEY
  2716. token = auth_header.replace("Bearer ", "")
  2717. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  2718. username = payload.get("sub")
  2719. if not username:
  2720. raise ValueError("No username in token")
  2721. # Verify user exists and is active
  2722. async with async_session() as db:
  2723. from backend.app.core.auth import get_user_by_username
  2724. user = await get_user_by_username(db, username)
  2725. if not user or not user.is_active:
  2726. return JSONResponse(
  2727. status_code=401,
  2728. content={"detail": "User not found or inactive"},
  2729. headers={"WWW-Authenticate": "Bearer"},
  2730. )
  2731. except jwt.ExpiredSignatureError:
  2732. return JSONResponse(
  2733. status_code=401,
  2734. content={"detail": "Token has expired"},
  2735. headers={"WWW-Authenticate": "Bearer"},
  2736. )
  2737. except (jwt.InvalidTokenError, ValueError, Exception):
  2738. return JSONResponse(
  2739. status_code=401,
  2740. content={"detail": "Invalid token"},
  2741. headers={"WWW-Authenticate": "Bearer"},
  2742. )
  2743. return await call_next(request)
  2744. # API routes
  2745. app.include_router(auth.router, prefix=app_settings.api_prefix)
  2746. app.include_router(users.router, prefix=app_settings.api_prefix)
  2747. app.include_router(groups.router, prefix=app_settings.api_prefix)
  2748. app.include_router(printers.router, prefix=app_settings.api_prefix)
  2749. app.include_router(archives.router, prefix=app_settings.api_prefix)
  2750. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  2751. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  2752. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  2753. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  2754. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  2755. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  2756. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  2757. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  2758. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  2759. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  2760. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  2761. app.include_router(updates.router, prefix=app_settings.api_prefix)
  2762. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  2763. app.include_router(camera.router, prefix=app_settings.api_prefix)
  2764. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  2765. app.include_router(projects.router, prefix=app_settings.api_prefix)
  2766. app.include_router(library.router, prefix=app_settings.api_prefix)
  2767. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  2768. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  2769. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  2770. app.include_router(system.router, prefix=app_settings.api_prefix)
  2771. app.include_router(support.router, prefix=app_settings.api_prefix)
  2772. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  2773. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  2774. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  2775. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  2776. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  2777. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  2778. # Serve static files (React build)
  2779. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  2780. app.mount(
  2781. "/assets",
  2782. StaticFiles(directory=app_settings.static_dir / "assets"),
  2783. name="assets",
  2784. )
  2785. if (app_settings.static_dir / "img").exists():
  2786. app.mount(
  2787. "/img",
  2788. StaticFiles(directory=app_settings.static_dir / "img"),
  2789. name="img",
  2790. )
  2791. if (app_settings.static_dir / "icons").exists():
  2792. app.mount(
  2793. "/icons",
  2794. StaticFiles(directory=app_settings.static_dir / "icons"),
  2795. name="icons",
  2796. )
  2797. @app.get("/")
  2798. async def serve_frontend():
  2799. """Serve the React frontend."""
  2800. index_file = app_settings.static_dir / "index.html"
  2801. if index_file.exists():
  2802. return FileResponse(index_file)
  2803. return {
  2804. "message": "Bambuddy API",
  2805. "docs": "/docs",
  2806. "frontend": "Build and place React app in /static directory",
  2807. }
  2808. @app.get("/health")
  2809. async def health_check():
  2810. """Health check endpoint."""
  2811. return {"status": "healthy"}
  2812. @app.get("/manifest.json")
  2813. async def serve_manifest():
  2814. """Serve PWA manifest."""
  2815. manifest_file = app_settings.static_dir / "manifest.json"
  2816. if manifest_file.exists():
  2817. return FileResponse(manifest_file, media_type="application/manifest+json")
  2818. return {"error": "Manifest not found"}
  2819. @app.get("/sw.js")
  2820. async def serve_service_worker():
  2821. """Serve service worker."""
  2822. sw_file = app_settings.static_dir / "sw.js"
  2823. if sw_file.exists():
  2824. return FileResponse(sw_file, media_type="application/javascript")
  2825. return {"error": "Service worker not found"}
  2826. # Catch-all route for React Router (must be last)
  2827. @app.get("/{full_path:path}")
  2828. async def serve_spa(full_path: str):
  2829. """Serve React app for client-side routing."""
  2830. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  2831. if full_path.startswith("api/"):
  2832. from fastapi import HTTPException
  2833. raise HTTPException(status_code=404, detail="Not found")
  2834. index_file = app_settings.static_dir / "index.html"
  2835. if index_file.exists():
  2836. return FileResponse(index_file)
  2837. return {"error": "Frontend not built"}