main.py 221 KB

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