main.py 172 KB

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