main.py 149 KB

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