main.py 173 KB

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