main.py 165 KB

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