main.py 165 KB

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