main.py 149 KB

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