main.py 216 KB

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