main.py 166 KB

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