main.py 149 KB

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