main.py 149 KB

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