main.py 192 KB

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