main.py 213 KB

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