main.py 171 KB

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