main.py 192 KB

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