main.py 191 KB

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