main.py 166 KB

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