main.py 168 KB

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