main.py 167 KB

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