main.py 194 KB

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