main.py 196 KB

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