main.py 217 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693
  1. import asyncio
  2. import logging
  3. import mimetypes as _mimetypes
  4. import posixpath
  5. import time
  6. from contextlib import asynccontextmanager
  7. from datetime import datetime, timedelta, timezone
  8. from logging.handlers import RotatingFileHandler
  9. from fastapi import FastAPI
  10. from fastapi.responses import FileResponse
  11. from fastapi.staticfiles import StaticFiles
  12. from sqlalchemy import delete, or_, select, text
  13. from backend.app.api.routes import (
  14. ams_history,
  15. api_keys,
  16. archive_purge,
  17. archives,
  18. auth,
  19. background_dispatch as background_dispatch_routes,
  20. bug_report,
  21. camera,
  22. cloud,
  23. discovery,
  24. external_links,
  25. filaments,
  26. firmware,
  27. github_backup,
  28. groups,
  29. inventory,
  30. kprofiles,
  31. library,
  32. library_trash,
  33. local_backup,
  34. local_presets,
  35. maintenance,
  36. makerworld,
  37. metrics,
  38. mfa,
  39. notification_templates,
  40. notifications,
  41. obico,
  42. pending_uploads,
  43. print_log,
  44. print_queue,
  45. printers,
  46. projects,
  47. settings as settings_routes,
  48. smart_plugs,
  49. spoolbuddy,
  50. spoolman,
  51. support,
  52. system,
  53. updates,
  54. user_notifications,
  55. users,
  56. virtual_printers,
  57. webhook,
  58. websocket,
  59. )
  60. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  61. from backend.app.api.routes.support import init_debug_logging
  62. from backend.app.core.config import APP_VERSION, settings as app_settings
  63. from backend.app.core.database import async_session, engine, init_db
  64. from backend.app.core.websocket import ws_manager
  65. from backend.app.models.smart_plug import SmartPlug
  66. from backend.app.services.archive import ArchiveService
  67. from backend.app.services.archive_purge import archive_purge_service
  68. from backend.app.services.background_dispatch import background_dispatch
  69. from backend.app.services.bambu_ftp import (
  70. FileNotOnPrinterError,
  71. cache_3mf_download,
  72. clear_3mf_cache,
  73. download_file_async,
  74. get_cached_3mf,
  75. get_ftp_retry_settings,
  76. with_ftp_retry,
  77. )
  78. from backend.app.services.bambu_mqtt import PrinterState
  79. from backend.app.services.github_backup import github_backup_service
  80. from backend.app.services.homeassistant import homeassistant_service
  81. from backend.app.services.library_trash import library_trash_service
  82. from backend.app.services.local_backup import local_backup_service
  83. from backend.app.services.mqtt_relay import mqtt_relay
  84. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  85. from backend.app.services.notification_service import notification_service
  86. from backend.app.services.obico_detection import obico_detection_service
  87. from backend.app.services.print_scheduler import scheduler as print_scheduler
  88. from backend.app.services.printer_manager import (
  89. init_printer_connections,
  90. printer_manager,
  91. printer_state_to_dict,
  92. )
  93. from backend.app.services.smart_plug_manager import smart_plug_manager
  94. from backend.app.services.spool_assignment_notifications import (
  95. notify_missing_spool_assignments_on_print_start,
  96. )
  97. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  98. from backend.app.services.spoolman_tracking import (
  99. cleanup_tracking as _cleanup_spoolman_tracking,
  100. report_usage as _report_spoolman_usage,
  101. store_print_data as _store_spoolman_print_data,
  102. )
  103. from backend.app.services.tasmota import tasmota_service
  104. # =============================================================================
  105. # Dependency Check - runs before other imports to give helpful error messages
  106. # =============================================================================
  107. def _start_error_server(missing_packages: list):
  108. """Start a minimal HTTP server to display dependency errors in browser."""
  109. import os
  110. import signal
  111. from http.server import BaseHTTPRequestHandler, HTTPServer
  112. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  113. html = f"""<!DOCTYPE html>
  114. <html>
  115. <head>
  116. <title>Bambuddy - Setup Required</title>
  117. <style>
  118. body {{
  119. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  120. background: #0f172a; color: #e2e8f0;
  121. display: flex; justify-content: center; align-items: center;
  122. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  123. }}
  124. .container {{
  125. background: #1e293b; border-radius: 12px; padding: 40px;
  126. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  127. }}
  128. h1 {{ color: #f87171; margin-bottom: 10px; }}
  129. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  130. .packages {{
  131. background: #0f172a; border-radius: 8px; padding: 20px;
  132. margin: 20px 0; text-align: left;
  133. }}
  134. .packages ul {{ margin: 0; padding-left: 20px; }}
  135. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  136. .command {{
  137. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  138. margin: 15px 0; font-family: monospace; color: #4ade80;
  139. text-align: left; overflow-x: auto;
  140. }}
  141. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  142. </style>
  143. </head>
  144. <body>
  145. <div class="container">
  146. <h1>Setup Required</h1>
  147. <h2>Missing Python packages</h2>
  148. <div class="packages"><ul>{packages_html}</ul></div>
  149. <p>To fix, run this command on your server:</p>
  150. <div class="command">pip install -r requirements.txt</div>
  151. <p>Or if using a virtual environment:</p>
  152. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  153. <p class="note">After installing, restart Bambuddy:<br>
  154. <code>sudo systemctl restart bambuddy</code></p>
  155. </div>
  156. </body>
  157. </html>"""
  158. class ErrorHandler(BaseHTTPRequestHandler):
  159. def do_GET(self):
  160. self.send_response(503)
  161. self.send_header("Content-type", "text/html")
  162. self.end_headers()
  163. self.wfile.write(html.encode())
  164. def log_message(self, format, *args):
  165. print(f"[Error Server] {args[0]}")
  166. port = int(os.environ.get("PORT", 8000))
  167. print(f"\nStarting error server on http://0.0.0.0:{port}")
  168. print("Visit this URL in your browser to see the error details.\n")
  169. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  170. def shutdown(signum, frame):
  171. print("\nShutting down error server...")
  172. raise SystemExit(0)
  173. signal.signal(signal.SIGTERM, shutdown)
  174. signal.signal(signal.SIGINT, shutdown)
  175. server.serve_forever()
  176. def check_dependencies():
  177. """Check that all required packages are installed."""
  178. missing = []
  179. # Map of import name -> package name (for pip install)
  180. required = {
  181. "jwt": "PyJWT",
  182. "fastapi": "fastapi",
  183. "uvicorn": "uvicorn",
  184. "sqlalchemy": "sqlalchemy",
  185. "aiosqlite": "aiosqlite",
  186. "pydantic": "pydantic",
  187. "paho.mqtt": "paho-mqtt",
  188. }
  189. for module, package in required.items():
  190. try:
  191. __import__(module)
  192. except ImportError:
  193. missing.append(package)
  194. if missing:
  195. print("\n" + "=" * 60)
  196. print("ERROR: Missing required Python packages!")
  197. print("=" * 60)
  198. print(f"\nMissing packages: {', '.join(missing)}")
  199. print("\nTo fix, run:")
  200. print(" pip install -r requirements.txt")
  201. print("\nOr if using a virtual environment:")
  202. print(" ./venv/bin/pip install -r requirements.txt")
  203. print("=" * 60 + "\n")
  204. _start_error_server(missing)
  205. check_dependencies()
  206. # =============================================================================
  207. # Import settings first for logging configuration
  208. # Configure logging based on settings
  209. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  210. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  211. log_level = getattr(logging, log_level_str, logging.INFO)
  212. log_format = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
  213. # Create root logger
  214. root_logger = logging.getLogger()
  215. root_logger.setLevel(log_level)
  216. # Console handler - always enabled
  217. console_handler = logging.StreamHandler()
  218. console_handler.setLevel(log_level)
  219. console_handler.setFormatter(logging.Formatter(log_format))
  220. root_logger.addHandler(console_handler)
  221. # File handler - only in production or if explicitly enabled
  222. if app_settings.log_to_file:
  223. log_file = app_settings.log_dir / "bambuddy.log"
  224. file_handler = RotatingFileHandler(
  225. log_file,
  226. maxBytes=5 * 1024 * 1024, # 5MB
  227. backupCount=3,
  228. encoding="utf-8",
  229. )
  230. file_handler.setLevel(log_level)
  231. file_handler.setFormatter(logging.Formatter(log_format))
  232. root_logger.addHandler(file_handler)
  233. logging.info("Logging to file: %s", log_file)
  234. # Reduce noise from third-party libraries in production
  235. if not app_settings.debug:
  236. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  237. logging.getLogger("httpcore").setLevel(logging.WARNING)
  238. logging.getLogger("httpx").setLevel(logging.WARNING)
  239. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  240. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  241. # Track active prints: {(printer_id, filename): archive_id}
  242. _active_prints: dict[tuple[int, str], int] = {}
  243. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  244. # {(printer_id, filename): archive_id}
  245. _expected_prints: dict[tuple[int, str], int] = {}
  246. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  247. # Used by usage tracker to map 3MF slots to physical AMS trays
  248. _print_ams_mappings: dict[int, list[int]] = {}
  249. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  250. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  251. _last_progress_milestone: dict[int, int] = {}
  252. # Track whether first layer complete notification has been sent for current print
  253. _first_layer_notified: dict[int, bool] = {}
  254. # Track HMS errors that have been notified: {printer_id: set of error codes}
  255. # This prevents sending duplicate notifications for the same error
  256. _notified_hms_errors: dict[int, set[str]] = {}
  257. # Track when HMS errors were last seen: {printer_id: timestamp}
  258. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  259. _hms_last_seen: dict[int, float] = {}
  260. _HMS_CLEAR_GRACE_SECONDS = 30.0
  261. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  262. # Used for snapshot-diff detection at print completion
  263. _timelapse_baselines: dict[int, set[str]] = {}
  264. # Track printers waiting for bed to cool after print completion.
  265. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  266. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  267. _bed_cool_waiters: dict[int, dict] = {}
  268. # Track printers where the user explicitly stopped the print from the queue UI.
  269. # When on_print_complete fires with status "failed" for these printers we treat it
  270. # as "cancelled" (stopped by user) so the correct notification email is sent.
  271. _user_stopped_printers: set[int] = set()
  272. # Track created_by_id for expected prints so the user email can be sent even when
  273. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  274. # {(printer_id, filename): created_by_id}
  275. _expected_print_creators: dict[tuple[int, str], int] = {}
  276. # TTL for expected-print entries: evict registrations older than this to prevent
  277. # unbounded growth when a print is registered but never starts (e.g. printer
  278. # disconnect, app restart, print started from the printer panel).
  279. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  280. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  281. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  282. # Cleanup loop interval
  283. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  284. _expected_prints_cleanup_task: asyncio.Task | None = None
  285. async def _get_plug_energy(plug, db) -> dict | None:
  286. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  287. For HA plugs, configures the service with current settings from DB.
  288. For MQTT plugs, returns data from the subscription service.
  289. For REST plugs, polls the status URL with JSON path extraction.
  290. """
  291. if plug.plug_type == "homeassistant":
  292. from backend.app.api.routes.settings import get_homeassistant_settings
  293. ha_settings = await get_homeassistant_settings(db)
  294. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  295. return await homeassistant_service.get_energy(plug)
  296. elif plug.plug_type == "mqtt":
  297. # MQTT plugs report "today" energy, not lifetime total
  298. # For per-print tracking, we use "today" as the counter (resets at midnight)
  299. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  300. if mqtt_data:
  301. return {
  302. "power": mqtt_data.power,
  303. "today": mqtt_data.energy,
  304. "total": mqtt_data.energy, # Use today as total for per-print calculations
  305. }
  306. return None
  307. elif plug.plug_type == "rest":
  308. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  309. return await rest_smart_plug_service.get_energy(plug)
  310. else:
  311. return await tasmota_service.get_energy(plug)
  312. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  313. """Capture the smart plug lifetime counter on the archive at print start.
  314. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  315. tracking survives a backend restart mid-print. The print-end handler reads
  316. this value back from the DB and computes the delta against the current
  317. plug counter.
  318. """
  319. _logger = logging.getLogger(__name__)
  320. try:
  321. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  322. plug = plug_result.scalar_one_or_none()
  323. if not plug:
  324. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  325. return False
  326. energy = await _get_plug_energy(plug, db)
  327. if not energy or energy.get("total") is None:
  328. _logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  329. return False
  330. archive.energy_start_kwh = float(energy["total"])
  331. await db.commit()
  332. _logger.info(
  333. "[ENERGY] Recorded starting energy%s for archive %s: %s kWh",
  334. f" ({context})" if context else "",
  335. archive.id,
  336. energy["total"],
  337. )
  338. return True
  339. except Exception as e:
  340. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  341. return False
  342. def register_expected_print(
  343. printer_id: int,
  344. filename: str,
  345. archive_id: int,
  346. ams_mapping: list[int] | None = None,
  347. created_by_id: int | None = None,
  348. ):
  349. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  350. # Store with multiple filename variations to catch different naming patterns
  351. _expected_prints[(printer_id, filename)] = archive_id
  352. # Also store without .3mf extension if present
  353. if filename.endswith(".3mf"):
  354. base = filename[:-4]
  355. _expected_prints[(printer_id, base)] = archive_id
  356. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  357. # Store AMS mapping for usage tracking at print completion
  358. if ams_mapping is not None:
  359. _print_ams_mappings[archive_id] = ams_mapping
  360. # Store created_by_id so the user start email can be sent even when the archive
  361. # itself has no created_by_id (e.g. library-file-based queue prints)
  362. if created_by_id is not None:
  363. _expected_print_creators[(printer_id, filename)] = created_by_id
  364. if filename.endswith(".3mf"):
  365. base = filename[:-4]
  366. _expected_print_creators[(printer_id, base)] = created_by_id
  367. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  368. # Record registration time for TTL-based eviction
  369. _registered_at = time.monotonic()
  370. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  371. if filename.endswith(".3mf"):
  372. base = filename[:-4]
  373. _expected_print_registered_at[(printer_id, base)] = _registered_at
  374. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  375. logging.getLogger(__name__).info(
  376. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}"
  377. )
  378. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  379. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  380. stored_ams_mapping = data.get("ams_mapping")
  381. if not stored_ams_mapping and archive_id:
  382. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  383. return stored_ams_mapping
  384. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  385. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  386. print completes successfully. Gated to status=='completed': failed, cancelled
  387. and aborted prints do not count as usage. Caller is responsible for committing
  388. the session. No-op when the queue item has no linked library file (e.g. reprints
  389. from an archive). See #1008."""
  390. if queue_status != "completed" or item.library_file_id is None:
  391. return
  392. from backend.app.models.library import LibraryFile
  393. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  394. if lib_file is None:
  395. return
  396. lib_file.print_count = (lib_file.print_count or 0) + 1
  397. lib_file.last_printed_at = datetime.now(timezone.utc)
  398. def mark_printer_stopped_by_user(printer_id: int) -> None:
  399. """Mark that the active print on this printer was stopped by the user from the queue UI.
  400. When on_print_complete fires with status 'failed' for a printer in this set we
  401. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  402. rather than a 'print failed' notification.
  403. """
  404. _user_stopped_printers.add(printer_id)
  405. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  406. _last_status_broadcast: dict[int, str] = {}
  407. # Track printers where we've updated nozzle_count
  408. _nozzle_count_updated: set[int] = set()
  409. async def on_printer_status_change(printer_id: int, state: PrinterState):
  410. """Handle printer status changes - broadcast via WebSocket."""
  411. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  412. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  413. temps = state.temperatures or {}
  414. nozzle_temp = round(temps.get("nozzle", 0))
  415. bed_temp = round(temps.get("bed", 0))
  416. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  417. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  418. # Auto-detect dual-nozzle printers from MQTT temperature data
  419. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  420. _nozzle_count_updated.add(printer_id)
  421. # Update nozzle_count in database
  422. async with async_session() as db:
  423. from backend.app.models.printer import Printer
  424. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  425. printer = result.scalar_one_or_none()
  426. if printer and printer.nozzle_count != 2:
  427. printer.nozzle_count = 2
  428. await db.commit()
  429. logging.getLogger(__name__).info(
  430. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  431. )
  432. # Include target temps for heating phase detection
  433. bed_target = round(temps.get("bed_target", 0))
  434. nozzle_target = round(temps.get("nozzle_target", 0))
  435. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  436. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  437. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  438. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  439. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  440. ams_tray_key = (
  441. tuple(
  442. (t.get("id"), t.get("tray_type", ""), t.get("state"))
  443. for a in (state.raw_data.get("ams") or [])
  444. for t in a.get("tray", [])
  445. )
  446. if state.raw_data
  447. else ()
  448. )
  449. status_key = (
  450. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  451. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  452. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  453. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  454. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  455. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}"
  456. )
  457. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  458. try:
  459. printer_info = printer_manager.get_printer(printer_id)
  460. if printer_info:
  461. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  462. except Exception:
  463. pass # Don't fail status callback if MQTT fails
  464. if _last_status_broadcast.get(printer_id) == status_key:
  465. return # No change, skip WebSocket broadcast
  466. _last_status_broadcast[printer_id] = status_key
  467. # Check for progress milestone notifications (25%, 50%, 75%)
  468. progress = state.progress or 0
  469. is_printing = state.state in ("RUNNING", "PRINTING")
  470. if is_printing and progress > 0:
  471. # Determine which milestone we've reached
  472. current_milestone = 0
  473. if progress >= 75:
  474. current_milestone = 75
  475. elif progress >= 50:
  476. current_milestone = 50
  477. elif progress >= 25:
  478. current_milestone = 25
  479. last_milestone = _last_progress_milestone.get(printer_id, 0)
  480. # If we've crossed a new milestone, send notification
  481. if current_milestone > last_milestone:
  482. _last_progress_milestone[printer_id] = current_milestone
  483. try:
  484. async with async_session() as db:
  485. from backend.app.models.printer import Printer
  486. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  487. printer = result.scalar_one_or_none()
  488. printer_name = printer.name if printer else f"Printer {printer_id}"
  489. filename = state.subtask_name or state.gcode_file or "Unknown"
  490. # remaining_time is in minutes, convert to seconds for notification
  491. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  492. # Capture camera snapshot for notification image attachment
  493. image_data = await _capture_snapshot_for_notification(
  494. printer_id, printer, logging.getLogger(__name__)
  495. )
  496. await notification_service.on_print_progress(
  497. printer_id,
  498. printer_name,
  499. filename,
  500. current_milestone,
  501. db,
  502. remaining_time_seconds,
  503. image_data=image_data,
  504. )
  505. except Exception as e:
  506. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  507. elif progress < 5:
  508. # Reset milestone tracking when print restarts or new print begins
  509. _last_progress_milestone[printer_id] = 0
  510. _first_layer_notified[printer_id] = False
  511. # HMS error codes that should not trigger notifications even though they
  512. # have known descriptions (e.g. user-initiated actions, not real errors).
  513. _HMS_NOTIFICATION_SUPPRESS = {
  514. "0500_400E", # Printing was cancelled (user action, not an error)
  515. }
  516. # Check for new HMS errors and send notifications
  517. current_hms_errors = getattr(state, "hms_errors", []) or []
  518. if current_hms_errors:
  519. # Build set of current error codes (using attr for uniqueness)
  520. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  521. previously_notified = _notified_hms_errors.get(printer_id, set())
  522. # Find new errors that haven't been notified yet
  523. new_error_codes = current_error_codes - previously_notified
  524. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  525. _notified_hms_errors[printer_id] = current_error_codes
  526. _hms_last_seen[printer_id] = time.time()
  527. if new_error_codes:
  528. # Get the actual new errors for the notification
  529. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  530. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  531. try:
  532. async with async_session() as db:
  533. from backend.app.models.printer import Printer
  534. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  535. printer = result.scalar_one_or_none()
  536. printer_name = printer.name if printer else f"Printer {printer_id}"
  537. # Format error details for notification
  538. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  539. module_names = {
  540. 0x03: "Print/Task",
  541. 0x05: "Nozzle/Extruder",
  542. 0x07: "AMS/Filament",
  543. 0x0C: "Motion Controller",
  544. 0x12: "Chamber",
  545. }
  546. from backend.app.services.hms_errors import get_error_description
  547. # Capture camera snapshot once for all error notifications
  548. error_image_data = await _capture_snapshot_for_notification(
  549. printer_id, printer, logging.getLogger(__name__)
  550. )
  551. sent_count = 0
  552. for error in new_errors:
  553. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  554. # Build short code like "0700_8010"
  555. # Mask to 16 bits to handle printers that send larger values
  556. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  557. error_code_masked = error_code_int & 0xFFFF
  558. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  559. # Only notify for errors with known descriptions — printers
  560. # send many undocumented/phantom codes that aren't real errors.
  561. description = get_error_description(short_code)
  562. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  563. continue
  564. error_type = f"{module_name} Error"
  565. error_detail = description
  566. await notification_service.on_printer_error(
  567. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  568. )
  569. sent_count += 1
  570. if sent_count:
  571. logging.getLogger(__name__).info(
  572. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  573. )
  574. # Also publish to MQTT relay
  575. printer_info = printer_manager.get_printer(printer_id)
  576. if printer_info:
  577. errors_data = [
  578. {
  579. "code": e.code,
  580. "attr": e.attr,
  581. "module": e.module,
  582. "severity": e.severity,
  583. }
  584. for e in new_errors
  585. ]
  586. await mqtt_relay.on_printer_error(
  587. printer_id, printer_info.name, printer_info.serial_number, errors_data
  588. )
  589. except Exception as e:
  590. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  591. else:
  592. # No HMS errors — only clear tracking after a grace period to prevent
  593. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  594. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  595. # on/off every few seconds as conditions fluctuate around thresholds.
  596. if printer_id in _notified_hms_errors:
  597. last_seen = _hms_last_seen.get(printer_id, 0)
  598. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  599. _notified_hms_errors.pop(printer_id, None)
  600. _hms_last_seen.pop(printer_id, None)
  601. await ws_manager.send_printer_status(
  602. printer_id,
  603. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  604. )
  605. def _is_bambu_uuid(tray_uuid: str) -> bool:
  606. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  607. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  608. async def on_ams_change(printer_id: int, ams_data: list):
  609. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  610. logger = logging.getLogger(__name__)
  611. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  612. # on_print_complete may pop _active_sessions during our awaits (#880).
  613. from backend.app.services.usage_tracker import _active_sessions
  614. _print_active = printer_id in _active_sessions
  615. # MQTT relay - publish AMS change
  616. try:
  617. printer_info = printer_manager.get_printer(printer_id)
  618. if printer_info:
  619. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  620. except Exception:
  621. pass # Don't fail AMS callback if MQTT fails
  622. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  623. # This ensures frontend gets immediate updates when AMS slots are configured
  624. try:
  625. state = printer_manager.get_status(printer_id)
  626. if state:
  627. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  628. await ws_manager.send_printer_status(
  629. printer_id,
  630. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  631. )
  632. except Exception as e:
  633. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  634. from backend.app.utils.color_utils import colors_similar as _colors_similar
  635. # Auto-unlink spool assignments with stale fingerprints
  636. try:
  637. async with async_session() as db:
  638. from sqlalchemy.orm import selectinload
  639. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  640. from backend.app.models.spool_assignment import SpoolAssignment as SA
  641. result = await db.execute(select(SA).where(SA.printer_id == printer_id).options(selectinload(SA.spool)))
  642. stale = []
  643. for assignment in result.scalars().all():
  644. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  645. if assignment.ams_id == 255:
  646. ps = printer_manager.get_status(printer_id)
  647. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  648. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  649. current_tray = None
  650. for vt in vt_tray_raw:
  651. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  652. current_tray = vt
  653. break
  654. if not current_tray:
  655. # vt_tray data may not have arrived yet — keep assignment
  656. continue
  657. else:
  658. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  659. if not current_tray:
  660. logger.info(
  661. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  662. assignment.spool_id,
  663. assignment.ams_id,
  664. assignment.tray_id,
  665. )
  666. stale.append(assignment) # Slot empty
  667. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  668. # A Bambu Lab spool is in this slot — check if it's the same spool
  669. # that's currently assigned. If yes, keep the assignment (avoids
  670. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  671. # the printer's filament preset on every startup).
  672. tray_uuid = current_tray.get("tray_uuid", "")
  673. tag_uid = current_tray.get("tag_uid", "")
  674. spool = assignment.spool
  675. spool_matches = False
  676. if spool:
  677. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  678. spool.tag_uid
  679. and tag_uid
  680. and tag_uid != "0000000000000000"
  681. and spool.tag_uid.upper() == tag_uid.upper()
  682. ):
  683. spool_matches = True
  684. if spool_matches:
  685. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  686. cur_color = current_tray.get("tray_color", "")
  687. cur_type = current_tray.get("tray_type", "")
  688. fp_color = assignment.fingerprint_color or ""
  689. fp_type = assignment.fingerprint_type or ""
  690. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  691. assignment.fingerprint_color = cur_color
  692. assignment.fingerprint_type = cur_type
  693. logger.debug(
  694. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  695. assignment.spool_id,
  696. assignment.ams_id,
  697. assignment.tray_id,
  698. )
  699. continue
  700. # Different BL spool or unrecognized — unlink so auto-assign can match
  701. logger.info(
  702. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  703. assignment.spool_id,
  704. assignment.ams_id,
  705. assignment.tray_id,
  706. tray_uuid,
  707. )
  708. stale.append(assignment)
  709. else:
  710. cur_color = current_tray.get("tray_color", "")
  711. cur_type = current_tray.get("tray_type", "")
  712. fp_color = assignment.fingerprint_color or ""
  713. fp_type = assignment.fingerprint_type or ""
  714. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  715. # Fingerprint mismatch — but check if tray now matches the
  716. # assigned spool (e.g. auto-configure changed the tray).
  717. spool = assignment.spool
  718. if spool:
  719. spool_color = (spool.rgba or "FFFFFFFF").upper()
  720. spool_type = (spool.material or "").upper()
  721. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  722. # Tray was reconfigured to match the spool — update fingerprint
  723. logger.info(
  724. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  725. assignment.spool_id,
  726. assignment.ams_id,
  727. assignment.tray_id,
  728. )
  729. assignment.fingerprint_color = cur_color
  730. assignment.fingerprint_type = cur_type
  731. continue
  732. logger.info(
  733. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  734. assignment.spool_id,
  735. assignment.ams_id,
  736. assignment.tray_id,
  737. cur_color,
  738. cur_type,
  739. fp_color,
  740. fp_type,
  741. spool.rgba if spool else "?",
  742. spool.material if spool else "?",
  743. )
  744. stale.append(assignment) # Spool changed
  745. for a in stale:
  746. await db.delete(a)
  747. if stale:
  748. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  749. # Commit any changes (stale deletions and/or fingerprint updates)
  750. await db.commit()
  751. except Exception as e:
  752. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  753. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS)
  754. try:
  755. async with async_session() as db:
  756. from backend.app.api.routes.settings import get_setting
  757. from backend.app.models.spool_assignment import SpoolAssignment as SA
  758. from backend.app.services.spool_tag_matcher import (
  759. auto_assign_spool,
  760. create_spool_from_tray,
  761. find_matching_untagged_spool,
  762. get_spool_by_tag,
  763. is_bambu_tag,
  764. is_valid_tag,
  765. link_tag_to_inventory_spool,
  766. )
  767. _spoolman_on = await get_setting(db, "spoolman_enabled")
  768. if not _spoolman_on or _spoolman_on.lower() != "true":
  769. for ams_unit in ams_data:
  770. if not isinstance(ams_unit, dict):
  771. continue
  772. ams_id = int(ams_unit.get("id", 0))
  773. for tray in ams_unit.get("tray", []):
  774. if not isinstance(tray, dict):
  775. continue
  776. tray_id = int(tray.get("id", 0))
  777. tag_uid = tray.get("tag_uid", "")
  778. tray_uuid = tray.get("tray_uuid", "")
  779. tray_info_idx = tray.get("tray_info_idx", "")
  780. if not tray.get("tray_type"):
  781. continue # Empty slot
  782. # Check if assignment already exists for this slot
  783. existing = await db.execute(
  784. select(SA)
  785. .options(selectinload(SA.spool))
  786. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  787. )
  788. existing_assignment = existing.scalar_one_or_none()
  789. if existing_assignment:
  790. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  791. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  792. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  793. # Skip during active prints: the usage tracker handles deduction
  794. # precisely via 3MF data on print completion. Without this guard the
  795. # AMS remain% SET and the usage tracker ADD both fire from the same
  796. # MQTT message, doubling the deduction (#880).
  797. if _print_active:
  798. continue
  799. remain_raw = tray.get("remain")
  800. if (
  801. remain_raw is not None
  802. and existing_assignment.spool
  803. and not existing_assignment.spool.weight_locked
  804. ):
  805. try:
  806. remain_val = int(remain_raw)
  807. except (TypeError, ValueError):
  808. remain_val = -1
  809. if 1 <= remain_val <= 100:
  810. lw = existing_assignment.spool.label_weight or 1000
  811. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  812. current_used = existing_assignment.spool.weight_used or 0
  813. if new_used > current_used + 1:
  814. logger.info(
  815. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  816. existing_assignment.spool_id,
  817. current_used,
  818. new_used,
  819. remain_val,
  820. )
  821. existing_assignment.spool.weight_used = new_used
  822. await db.commit()
  823. continue
  824. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  825. # BL spool with RFID tag: auto-match → inventory match → auto-create
  826. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  827. if not spool:
  828. # Try matching an untagged inventory spool (same material/color)
  829. spool = await find_matching_untagged_spool(db, tray)
  830. if spool:
  831. await link_tag_to_inventory_spool(db, spool, tray)
  832. else:
  833. spool = await create_spool_from_tray(db, tray)
  834. await auto_assign_spool(
  835. printer_id,
  836. ams_id,
  837. tray_id,
  838. spool,
  839. printer_manager,
  840. db,
  841. tray_info_idx=tray_info_idx,
  842. )
  843. await db.commit()
  844. await ws_manager.broadcast(
  845. {
  846. "type": "spool_auto_assigned",
  847. "printer_id": printer_id,
  848. "ams_id": ams_id,
  849. "tray_id": tray_id,
  850. "spool_id": spool.id,
  851. }
  852. )
  853. logger.info(
  854. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  855. spool.id,
  856. printer_id,
  857. ams_id,
  858. tray_id,
  859. )
  860. elif is_valid_tag(tag_uid, tray_uuid):
  861. # Non-BL spool with some tag — let user choose
  862. await ws_manager.broadcast(
  863. {
  864. "type": "unknown_tag",
  865. "printer_id": printer_id,
  866. "ams_id": ams_id,
  867. "tray_id": tray_id,
  868. "tag_uid": tag_uid,
  869. "tray_uuid": tray_uuid,
  870. }
  871. )
  872. else:
  873. # No tag at all — let user choose from inventory
  874. await ws_manager.broadcast(
  875. {
  876. "type": "unknown_tag",
  877. "printer_id": printer_id,
  878. "ams_id": ams_id,
  879. "tray_id": tray_id,
  880. "tag_uid": "",
  881. "tray_uuid": "",
  882. }
  883. )
  884. except Exception as e:
  885. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  886. try:
  887. async with async_session() as db:
  888. from backend.app.api.routes.settings import get_setting
  889. from backend.app.models.printer import Printer
  890. # Check if Spoolman is enabled
  891. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  892. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  893. return
  894. # Check sync mode
  895. sync_mode = await get_setting(db, "spoolman_sync_mode")
  896. if sync_mode and sync_mode != "auto":
  897. return # Only sync on auto mode
  898. # Check if weight sync is disabled
  899. disable_weight_sync_str = await get_setting(db, "spoolman_disable_weight_sync")
  900. disable_weight_sync = disable_weight_sync_str and disable_weight_sync_str.lower() == "true"
  901. # Get Spoolman URL
  902. spoolman_url = await get_setting(db, "spoolman_url")
  903. if not spoolman_url:
  904. return
  905. # Get or create Spoolman client
  906. client = await get_spoolman_client()
  907. if not client:
  908. client = await init_spoolman_client(spoolman_url)
  909. # Check if Spoolman is reachable
  910. if not await client.health_check():
  911. logger.warning("Spoolman not reachable at %s", spoolman_url)
  912. return
  913. # Get printer name for location
  914. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  915. printer = result.scalar_one_or_none()
  916. printer_name = printer.name if printer else f"Printer {printer_id}"
  917. # OPTIMIZATION: Fetch all spools once before processing trays
  918. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  919. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  920. try:
  921. cached_spools = await client.get_spools()
  922. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  923. except Exception as e:
  924. logger.error(
  925. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  926. printer_id,
  927. e,
  928. )
  929. return
  930. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  931. from sqlalchemy.orm import selectinload
  932. from backend.app.models.spool_assignment import SpoolAssignment
  933. inventory_weights: dict[tuple[int, int], float] = {}
  934. try:
  935. assign_result = await db.execute(
  936. select(SpoolAssignment)
  937. .options(selectinload(SpoolAssignment.spool))
  938. .where(SpoolAssignment.printer_id == printer_id)
  939. )
  940. for assignment in assign_result.scalars().all():
  941. spool = assignment.spool
  942. if spool and spool.label_weight > 0:
  943. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  944. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  945. except Exception as e:
  946. logger.debug("Could not load inventory weights for printer %s: %s", printer_id, e)
  947. # Sync each AMS tray, tracking UUIDs and spool IDs for cleanup
  948. synced = 0
  949. current_tray_uuids: set[str] = set()
  950. synced_spool_ids: set[int] = set()
  951. for ams_unit in ams_data:
  952. ams_id = int(ams_unit.get("id", 0))
  953. trays = ams_unit.get("tray", [])
  954. for tray_data in trays:
  955. tray = client.parse_ams_tray(ams_id, tray_data)
  956. if not tray:
  957. continue # Empty tray
  958. # Track this spool's UUID as currently present in the AMS
  959. spool_tag = (
  960. tray.tray_uuid
  961. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  962. else tray.tag_uid
  963. )
  964. if spool_tag:
  965. current_tray_uuids.add(spool_tag.upper())
  966. try:
  967. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  968. result = await client.sync_ams_tray(
  969. tray,
  970. printer_name,
  971. disable_weight_sync=disable_weight_sync,
  972. cached_spools=cached_spools,
  973. inventory_remaining=inv_remaining,
  974. )
  975. if result:
  976. synced += 1
  977. if result.get("id"):
  978. synced_spool_ids.add(result["id"])
  979. # If a new spool was created, add it to the cache
  980. # so subsequent trays can find it if they reference the same tag
  981. # Check if this spool already exists in cache
  982. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  983. if not spool_exists:
  984. cached_spools.append(result)
  985. logger.debug(
  986. "[Printer %s] Added newly created spool %s to cache",
  987. printer_id,
  988. result["id"],
  989. )
  990. except Exception as e:
  991. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  992. if synced > 0:
  993. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  994. # Clear location for spools no longer in this printer's AMS
  995. try:
  996. cleared = await client.clear_location_for_removed_spools(
  997. printer_name, current_tray_uuids, cached_spools=cached_spools, synced_spool_ids=synced_spool_ids
  998. )
  999. if cleared > 0:
  1000. logger.info("Auto-cleared location for %s spools removed from printer %s", cleared, printer_id)
  1001. except Exception as e:
  1002. logger.error("Error clearing locations for removed spools on printer %s: %s", printer_id, e)
  1003. except Exception as e:
  1004. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  1005. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  1006. """Capture a camera snapshot for notification image attachment.
  1007. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  1008. Uses: external camera > buffered frame > fresh capture.
  1009. """
  1010. if not printer:
  1011. return None
  1012. try:
  1013. from backend.app.api.routes.settings import get_setting
  1014. async with async_session() as db:
  1015. capture_enabled = await get_setting(db, "capture_finish_photo")
  1016. if capture_enabled is not None and capture_enabled.lower() != "true":
  1017. return None
  1018. # Try external camera first
  1019. if printer.external_camera_enabled and printer.external_camera_url:
  1020. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  1021. from backend.app.services.external_camera import capture_frame
  1022. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type or "mjpeg")
  1023. if frame_data and len(frame_data) <= 2_500_000:
  1024. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  1025. return _apply_camera_rotation(frame_data, printer, logger)
  1026. # Try buffered frame from active stream
  1027. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1028. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1029. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  1030. buffered_frame = get_buffered_frame(printer_id)
  1031. if (active_for_printer or active_chamber) and buffered_frame:
  1032. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  1033. if len(buffered_frame) <= 2_500_000:
  1034. return _apply_camera_rotation(buffered_frame, printer, logger)
  1035. # Fresh capture from printer camera
  1036. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  1037. from backend.app.services.camera import capture_camera_frame_bytes
  1038. frame_data = await capture_camera_frame_bytes(
  1039. printer.ip_address, printer.access_code, printer.model, timeout=15
  1040. )
  1041. if frame_data and len(frame_data) <= 2_500_000:
  1042. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  1043. return _apply_camera_rotation(frame_data, printer, logger)
  1044. except Exception as e:
  1045. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  1046. return None
  1047. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  1048. """Apply camera rotation to snapshot image if configured."""
  1049. rotation = getattr(printer, "camera_rotation", 0)
  1050. if not rotation or rotation == 0:
  1051. return image_data
  1052. try:
  1053. from io import BytesIO
  1054. from PIL import Image
  1055. img = Image.open(BytesIO(image_data))
  1056. # PIL rotate is counter-clockwise, so negate for clockwise rotation
  1057. img = img.rotate(-rotation, expand=True)
  1058. buf = BytesIO()
  1059. img.save(buf, format="JPEG", quality=90)
  1060. rotated = buf.getvalue()
  1061. logger.info("[SNAPSHOT] Applied %d° rotation: %s → %s bytes", rotation, len(image_data), len(rotated))
  1062. return rotated
  1063. except Exception as e:
  1064. logger.warning("[SNAPSHOT] Failed to apply rotation: %s", e)
  1065. return image_data
  1066. async def _send_print_start_notification(
  1067. printer_id: int,
  1068. data: dict,
  1069. archive_data: dict | None = None,
  1070. logger=None,
  1071. ):
  1072. """Helper to send print start notification with optional archive data."""
  1073. if logger is None:
  1074. logger = logging.getLogger(__name__)
  1075. try:
  1076. async with async_session() as db:
  1077. from backend.app.models.printer import Printer
  1078. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1079. printer = result.scalar_one_or_none()
  1080. printer_name = printer.name if printer else f"Printer {printer_id}"
  1081. # Capture camera snapshot for notification image attachment
  1082. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  1083. if image_data:
  1084. if archive_data is None:
  1085. archive_data = {}
  1086. archive_data["image_data"] = image_data
  1087. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  1088. # Send user-specific email notification for print start
  1089. if archive_data and archive_data.get("created_by_id"):
  1090. await notification_service.send_user_print_email(
  1091. event_type="user_print_start",
  1092. created_by_id=archive_data["created_by_id"],
  1093. printer_name=printer_name,
  1094. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  1095. db=db,
  1096. )
  1097. except Exception as e:
  1098. logger.warning("Notification on_print_start failed: %s", e)
  1099. async def _dispatch_user_print_email(
  1100. status: str,
  1101. created_by_id: int | None,
  1102. printer_name: str,
  1103. filename: str,
  1104. db,
  1105. ) -> None:
  1106. """Send a user-specific print-completion email based on print status.
  1107. Maps the normalised print status to the correct event type and delegates
  1108. to :meth:`NotificationService.send_user_print_email`. A single helper
  1109. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  1110. "stopped"`` dispatch block at every call site.
  1111. Does nothing if *created_by_id* is ``None``.
  1112. """
  1113. if created_by_id is None:
  1114. return
  1115. if status == "completed":
  1116. event_type = "user_print_complete"
  1117. elif status == "failed":
  1118. event_type = "user_print_failed"
  1119. elif status in ("stopped", "aborted", "cancelled"):
  1120. event_type = "user_print_stopped"
  1121. else:
  1122. return
  1123. await notification_service.send_user_print_email(
  1124. event_type=event_type,
  1125. created_by_id=created_by_id,
  1126. printer_name=printer_name,
  1127. filename=filename,
  1128. db=db,
  1129. )
  1130. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  1131. """Extract printable objects from an archive's 3MF file and store in printer state."""
  1132. try:
  1133. from backend.app.services.archive import extract_printable_objects_from_3mf
  1134. file_path = app_settings.base_dir / archive.file_path
  1135. if file_path.is_file() and str(file_path).endswith(".3mf"):
  1136. with open(file_path, "rb") as f:
  1137. threemf_data = f.read()
  1138. # Extract with positions for UI overlay
  1139. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  1140. if printable_objects:
  1141. client = printer_manager.get_client(printer_id)
  1142. if client:
  1143. client.state.printable_objects = printable_objects
  1144. client.state.printable_objects_bbox_all = bbox_all
  1145. client.state.skipped_objects = []
  1146. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  1147. except Exception as e:
  1148. logger.debug("Failed to extract printable objects from archive: %s", e)
  1149. async def on_print_start(printer_id: int, data: dict):
  1150. """Handle print start - archive the 3MF file immediately."""
  1151. logger = logging.getLogger(__name__)
  1152. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  1153. # Clear any stale user-stopped flag from previous print cycles
  1154. _user_stopped_printers.discard(printer_id)
  1155. # Cancel any active bed cooldown waiter for this printer
  1156. if _bed_cool_waiters.pop(printer_id, None):
  1157. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  1158. # Clear cached cover images so the new print's thumbnail is fetched fresh
  1159. from backend.app.api.routes.printers import clear_cover_cache
  1160. clear_cover_cache(printer_id)
  1161. await ws_manager.send_print_start(printer_id, data)
  1162. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  1163. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  1164. # MQTT relay - publish print start
  1165. try:
  1166. printer_info = printer_manager.get_printer(printer_id)
  1167. if printer_info:
  1168. await mqtt_relay.on_print_start(
  1169. printer_id,
  1170. printer_info.name,
  1171. printer_info.serial_number,
  1172. data.get("filename", ""),
  1173. data.get("subtask_name", ""),
  1174. )
  1175. except Exception:
  1176. pass # Don't fail print start callback if MQTT fails
  1177. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  1178. try:
  1179. async with async_session() as db:
  1180. from backend.app.api.routes.settings import get_setting
  1181. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1182. if not _spoolman_on or _spoolman_on.lower() != "true":
  1183. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  1184. await usage_on_print_start(printer_id, data, printer_manager, db=db)
  1185. except Exception as e:
  1186. logger.warning("Usage tracker on_print_start failed: %s", e)
  1187. # Track if notification was sent (to avoid sending twice)
  1188. notification_sent = False
  1189. # Smart plug automation: turn on plug when print starts
  1190. try:
  1191. async with async_session() as db:
  1192. await smart_plug_manager.on_print_start(printer_id, db)
  1193. except Exception as e:
  1194. logger.warning("Smart plug on_print_start failed: %s", e)
  1195. async with async_session() as db:
  1196. from backend.app.models.printer import Printer
  1197. from backend.app.services.bambu_ftp import list_files_async
  1198. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1199. printer = result.scalar_one_or_none()
  1200. # Plate detection check - pause if objects detected on build plate
  1201. logger.info(
  1202. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  1203. )
  1204. if printer and printer.plate_detection_enabled:
  1205. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  1206. try:
  1207. from backend.app.services.plate_detection import check_plate_empty
  1208. # Build ROI tuple from printer settings if available
  1209. roi = None
  1210. if all(
  1211. [
  1212. printer.plate_detection_roi_x is not None,
  1213. printer.plate_detection_roi_y is not None,
  1214. printer.plate_detection_roi_w is not None,
  1215. printer.plate_detection_roi_h is not None,
  1216. ]
  1217. ):
  1218. roi = (
  1219. printer.plate_detection_roi_x,
  1220. printer.plate_detection_roi_y,
  1221. printer.plate_detection_roi_w,
  1222. printer.plate_detection_roi_h,
  1223. )
  1224. # Auto-turn on chamber light if it's off for better detection
  1225. light_was_off = False
  1226. client = printer_manager.get_client(printer_id)
  1227. if client and client.state:
  1228. light_was_off = not client.state.chamber_light
  1229. if light_was_off:
  1230. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  1231. client.set_chamber_light(True)
  1232. # Wait for light to physically turn on and camera to adjust exposure
  1233. await asyncio.sleep(2.5)
  1234. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  1235. plate_result = await check_plate_empty(
  1236. printer_id=printer_id,
  1237. ip_address=printer.ip_address,
  1238. access_code=printer.access_code,
  1239. model=printer.model,
  1240. include_debug_image=False,
  1241. external_camera_url=printer.external_camera_url,
  1242. external_camera_type=printer.external_camera_type,
  1243. use_external=printer.external_camera_enabled,
  1244. roi=roi,
  1245. )
  1246. # Restore chamber light to original state
  1247. if light_was_off and client:
  1248. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  1249. client.set_chamber_light(False)
  1250. if not plate_result.needs_calibration and not plate_result.is_empty:
  1251. # Objects detected - pause the print!
  1252. logger.warning(
  1253. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  1254. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  1255. )
  1256. client = printer_manager.get_client(printer_id)
  1257. if client:
  1258. client.pause_print()
  1259. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  1260. # Send notification about plate not empty
  1261. await ws_manager.broadcast(
  1262. {
  1263. "type": "plate_not_empty",
  1264. "printer_id": printer_id,
  1265. "printer_name": printer.name,
  1266. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  1267. }
  1268. )
  1269. # Also send push notification
  1270. try:
  1271. await notification_service.on_plate_not_empty(
  1272. printer_id=printer_id,
  1273. printer_name=printer.name,
  1274. db=db,
  1275. difference_percent=plate_result.difference_percent,
  1276. )
  1277. except Exception as notif_err:
  1278. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  1279. else:
  1280. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  1281. except Exception as plate_err:
  1282. # Don't block print on plate detection errors
  1283. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  1284. if not printer:
  1285. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  1286. if not notification_sent:
  1287. await _send_print_start_notification(printer_id, data, logger=logger)
  1288. return
  1289. if not printer.auto_archive:
  1290. # auto-archive disabled — check if there's an expected print (dispatched
  1291. # by BamBuddy via queue/reprint) that already has an archive to promote.
  1292. # If so, fall through to the expected-print handling below so the archive
  1293. # is tracked in _active_prints and usage tracking works at completion.
  1294. _fn = data.get("filename", "")
  1295. _sn = data.get("subtask_name", "")
  1296. _check_keys: list[tuple[int, str]] = []
  1297. if _sn:
  1298. _check_keys += [
  1299. (printer_id, _sn),
  1300. (printer_id, f"{_sn}.3mf"),
  1301. (printer_id, f"{_sn}.gcode.3mf"),
  1302. ]
  1303. if _fn:
  1304. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  1305. _check_keys.append((printer_id, _base_fn))
  1306. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  1307. _check_keys += [
  1308. (printer_id, _no_archive_base),
  1309. (printer_id, f"{_no_archive_base}.3mf"),
  1310. ]
  1311. _has_expected = any(k in _expected_prints for k in _check_keys)
  1312. if not _has_expected:
  1313. # No expected print — truly external print (started from slicer/touchscreen)
  1314. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  1315. if not notification_sent:
  1316. _no_archive_creator: int | None = None
  1317. for _key in _check_keys:
  1318. _expected_prints.pop(_key, None)
  1319. _expected_print_registered_at.pop(_key, None)
  1320. popped_creator = _expected_print_creators.pop(_key, None)
  1321. if _no_archive_creator is None:
  1322. _no_archive_creator = popped_creator
  1323. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  1324. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  1325. return
  1326. else:
  1327. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  1328. # Get the filename and subtask_name
  1329. filename = data.get("filename", "")
  1330. subtask_name = data.get("subtask_name", "")
  1331. # MQTT subtask_id uniquely identifies a print job on the printer. When
  1332. # present, it lets us match an archive across a backend restart (#972):
  1333. # same id → same print → resume the existing row instead of cancelling
  1334. # it and recreating from scratch (which loses started_at). Treat "0"
  1335. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  1336. raw_mqtt = data.get("raw_data") or {}
  1337. subtask_id = raw_mqtt.get("subtask_id")
  1338. if subtask_id is not None:
  1339. subtask_id = str(subtask_id).strip()
  1340. if subtask_id in ("", "0"):
  1341. subtask_id = None
  1342. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  1343. # Skip calibration prints — internal printer files should not be archived
  1344. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  1345. if filename and filename.startswith("/usr/"):
  1346. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  1347. if not notification_sent:
  1348. await _send_print_start_notification(printer_id, data, logger=logger)
  1349. return
  1350. if not filename and not subtask_name:
  1351. # Send notification without archive data (no filename)
  1352. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  1353. if not notification_sent:
  1354. await _send_print_start_notification(printer_id, data, logger=logger)
  1355. return
  1356. # Check if this is an expected print from reprint/scheduled
  1357. # Build list of possible keys to check
  1358. expected_keys = []
  1359. if subtask_name:
  1360. expected_keys.append((printer_id, subtask_name))
  1361. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  1362. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1363. if filename:
  1364. fname = filename.split("/")[-1] if "/" in filename else filename
  1365. expected_keys.append((printer_id, fname))
  1366. # Strip extensions to match
  1367. base = fname.replace(".gcode", "").replace(".3mf", "")
  1368. expected_keys.append((printer_id, base))
  1369. expected_keys.append((printer_id, f"{base}.3mf"))
  1370. expected_archive_id = None
  1371. for key in expected_keys:
  1372. expected_archive_id = _expected_prints.pop(key, None)
  1373. _expected_print_registered_at.pop(key, None)
  1374. if expected_archive_id:
  1375. # Clean up other possible keys for this print
  1376. for other_key in expected_keys:
  1377. _expected_prints.pop(other_key, None)
  1378. _expected_print_registered_at.pop(other_key, None)
  1379. break
  1380. if expected_archive_id:
  1381. # This is a reprint/scheduled print - use existing archive, don't create new one
  1382. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  1383. from backend.app.models.archive import PrintArchive
  1384. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  1385. archive = result.scalar_one_or_none()
  1386. if archive:
  1387. # Update archive status to printing
  1388. archive.status = "printing"
  1389. archive.started_at = datetime.now(timezone.utc)
  1390. if subtask_id and not archive.subtask_id:
  1391. archive.subtask_id = subtask_id
  1392. await db.commit()
  1393. # Track as active print
  1394. _active_prints[(printer_id, archive.filename)] = archive.id
  1395. if subtask_name:
  1396. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1397. # Inject ams_mapping into usage tracker session — the session was created
  1398. # before expected-print promotion, so it may have ams_mapping=None when
  1399. # the MQTT request topic subscription failed (common on P1S/A1).
  1400. _stored_map = _print_ams_mappings.get(expected_archive_id)
  1401. if _stored_map:
  1402. try:
  1403. from backend.app.services.usage_tracker import _active_sessions
  1404. _ut_session = _active_sessions.get(printer_id)
  1405. if _ut_session and not _ut_session.ams_mapping:
  1406. _ut_session.ams_mapping = _stored_map
  1407. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  1408. except Exception:
  1409. pass
  1410. # Set up energy tracking (#941: persist start on archive row)
  1411. await _record_energy_start(archive, printer_id, db, context="expected-print")
  1412. await ws_manager.send_archive_updated(
  1413. {
  1414. "id": archive.id,
  1415. "status": "printing",
  1416. }
  1417. )
  1418. # Send notification with archive data (reprint/scheduled)
  1419. if not notification_sent:
  1420. # Use archive's created_by_id; fall back to the creator registered via
  1421. # register_expected_print (handles library-file-based queue items where
  1422. # the freshly-created archive has no created_by_id yet).
  1423. # Pop ALL matching keys so no stale entries remain in the dict.
  1424. fallback_creator = None
  1425. for key in expected_keys:
  1426. popped = _expected_print_creators.pop(key, None)
  1427. if fallback_creator is None:
  1428. fallback_creator = popped
  1429. archive_data = {
  1430. "print_time_seconds": archive.print_time_seconds,
  1431. "created_by_id": archive.created_by_id or fallback_creator,
  1432. }
  1433. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1434. # Extract printable objects from the archived 3MF file
  1435. _load_objects_from_archive(archive, printer_id, logger)
  1436. # Store Spoolman tracking data for per-filament usage reporting
  1437. try:
  1438. await _store_spoolman_print_data(
  1439. printer_id,
  1440. archive.id,
  1441. archive.file_path,
  1442. db,
  1443. printer_manager,
  1444. ams_mapping=_get_start_ams_mapping(data, archive.id),
  1445. )
  1446. except Exception as e:
  1447. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1448. return # Skip creating a new archive
  1449. # Check if there's already a "printing" archive for this printer/file
  1450. # This prevents duplicates when backend restarts during an active print
  1451. from backend.app.models.archive import PrintArchive
  1452. existing_archive: PrintArchive | None = None
  1453. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  1454. # across a backend restart for the same print, so this is the most
  1455. # reliable way to reattach. We also accept a previously stale-cancelled
  1456. # archive here so users upgrading mid-print get revived when the row
  1457. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  1458. if subtask_id:
  1459. by_id = await db.execute(
  1460. select(PrintArchive)
  1461. .where(PrintArchive.printer_id == printer_id)
  1462. .where(PrintArchive.subtask_id == subtask_id)
  1463. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  1464. .order_by(PrintArchive.created_at.desc())
  1465. .limit(1)
  1466. )
  1467. candidate = by_id.scalar_one_or_none()
  1468. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  1469. existing_archive = candidate
  1470. # Fallback match: name-based lookup. Kept as-is for prints whose
  1471. # subtask_id is missing ("0" / local / non-cloud prints).
  1472. if existing_archive is None:
  1473. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  1474. existing = await db.execute(
  1475. select(PrintArchive)
  1476. .where(PrintArchive.printer_id == printer_id)
  1477. .where(PrintArchive.status == "printing")
  1478. .where(
  1479. or_(
  1480. PrintArchive.print_name == check_name,
  1481. PrintArchive.filename.in_(
  1482. [
  1483. f"{check_name}.3mf",
  1484. f"{check_name}.gcode.3mf",
  1485. ]
  1486. ),
  1487. )
  1488. )
  1489. .order_by(PrintArchive.created_at.desc())
  1490. .limit(1)
  1491. )
  1492. existing_archive = existing.scalar_one_or_none()
  1493. if existing_archive:
  1494. # subtask_id match → always resume, regardless of age. Same print,
  1495. # just a backend restart. Revive if it was previously stale-cancelled.
  1496. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  1497. if subtask_match:
  1498. if existing_archive.status == "cancelled":
  1499. logger.warning(
  1500. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  1501. existing_archive.id,
  1502. subtask_id,
  1503. )
  1504. existing_archive.status = "printing"
  1505. existing_archive.failure_reason = None
  1506. await db.commit()
  1507. else:
  1508. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  1509. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1510. if existing_archive.energy_start_kwh is None:
  1511. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  1512. if not notification_sent:
  1513. archive_data = {
  1514. "print_time_seconds": existing_archive.print_time_seconds,
  1515. "created_by_id": existing_archive.created_by_id,
  1516. }
  1517. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1518. _load_objects_from_archive(existing_archive, printer_id, logger)
  1519. return
  1520. # Name-match only: fall back to the legacy 4h staleness heuristic.
  1521. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  1522. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  1523. logger.warning(
  1524. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  1525. f"marking as cancelled and creating new archive"
  1526. )
  1527. existing_archive.status = "cancelled"
  1528. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  1529. await db.commit()
  1530. # Fall through to create new archive (don't return)
  1531. _existing_archive = None # Clear so we don't use stale archive
  1532. else:
  1533. logger.info(
  1534. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  1535. )
  1536. # Track this as the active print
  1537. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1538. # Attach subtask_id retroactively so future restarts can resume
  1539. if subtask_id and not existing_archive.subtask_id:
  1540. existing_archive.subtask_id = subtask_id
  1541. await db.commit()
  1542. # Also set up energy tracking if not already tracked (#941: persisted column)
  1543. if existing_archive.energy_start_kwh is None:
  1544. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  1545. # Send notification with archive data (existing archive)
  1546. if not notification_sent:
  1547. archive_data = {
  1548. "print_time_seconds": existing_archive.print_time_seconds,
  1549. "created_by_id": existing_archive.created_by_id,
  1550. }
  1551. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1552. # Extract printable objects from the archived 3MF file
  1553. _load_objects_from_archive(existing_archive, printer_id, logger)
  1554. return
  1555. # Build list of possible 3MF filenames to try
  1556. possible_names = []
  1557. # Bambu printers typically store files as "Name.gcode.3mf"
  1558. # The subtask_name is usually the best source for the filename
  1559. if subtask_name:
  1560. # Try common Bambu naming patterns
  1561. possible_names.append(f"{subtask_name}.gcode.3mf")
  1562. possible_names.append(f"{subtask_name}.3mf")
  1563. # Try original filename with .3mf extension
  1564. if filename:
  1565. # Extract just the filename part, not the full path
  1566. fname = filename.split("/")[-1] if "/" in filename else filename
  1567. if fname.endswith(".3mf"):
  1568. possible_names.append(fname)
  1569. elif fname.endswith(".gcode"):
  1570. base = fname.rsplit(".", 1)[0]
  1571. possible_names.append(f"{base}.gcode.3mf")
  1572. possible_names.append(f"{base}.3mf")
  1573. else:
  1574. possible_names.append(f"{fname}.gcode.3mf")
  1575. possible_names.append(f"{fname}.3mf")
  1576. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1577. space_variants = []
  1578. for name in possible_names:
  1579. if " " in name:
  1580. space_variants.append(name.replace(" ", "_"))
  1581. possible_names.extend(space_variants)
  1582. # Remove duplicates while preserving order
  1583. seen = set()
  1584. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  1585. logger.info("Trying filenames: %s", possible_names)
  1586. # Try to find and download the 3MF file
  1587. temp_path = None
  1588. downloaded_filename = None
  1589. # Cache check: cover endpoint may have already pulled this 3MF during
  1590. # the print (frontend opens the card and shows the thumbnail) — reuse
  1591. # that file instead of re-downloading 36MB over the same FTP link that
  1592. # just served it (#972). The cache keys on a normalized filename so
  1593. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  1594. for try_filename in possible_names:
  1595. if not try_filename.endswith(".3mf"):
  1596. continue
  1597. cached = get_cached_3mf(printer_id, try_filename)
  1598. if cached:
  1599. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  1600. temp_path = cached
  1601. downloaded_filename = try_filename
  1602. break
  1603. # Get FTP retry settings
  1604. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1605. for try_filename in possible_names if not downloaded_filename else []:
  1606. if not try_filename.endswith(".3mf"):
  1607. continue
  1608. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  1609. # printers, so try it first — deferring it to last cost #972's reporter
  1610. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  1611. # landing on the path that actually had the file.
  1612. remote_paths = [
  1613. f"/{try_filename}",
  1614. f"/cache/{try_filename}",
  1615. f"/model/{try_filename}",
  1616. f"/data/{try_filename}",
  1617. f"/data/Metadata/{try_filename}",
  1618. ]
  1619. temp_path = app_settings.archive_dir / "temp" / try_filename
  1620. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1621. for remote_path in remote_paths:
  1622. logger.debug("Trying FTP download: %s", remote_path)
  1623. try:
  1624. if ftp_retry_enabled:
  1625. downloaded = await with_ftp_retry(
  1626. download_file_async,
  1627. printer.ip_address,
  1628. printer.access_code,
  1629. remote_path,
  1630. temp_path,
  1631. timeout=ftp_timeout,
  1632. socket_timeout=ftp_timeout,
  1633. printer_model=printer.model,
  1634. max_retries=ftp_retry_count,
  1635. retry_delay=ftp_retry_delay,
  1636. operation_name=f"Download 3MF from {remote_path}",
  1637. non_retry_exceptions=(FileNotOnPrinterError,),
  1638. )
  1639. else:
  1640. downloaded = await download_file_async(
  1641. printer.ip_address,
  1642. printer.access_code,
  1643. remote_path,
  1644. temp_path,
  1645. timeout=ftp_timeout,
  1646. socket_timeout=ftp_timeout,
  1647. printer_model=printer.model,
  1648. )
  1649. if downloaded:
  1650. downloaded_filename = try_filename
  1651. logger.info("Downloaded: %s", remote_path)
  1652. # Populate shared cache so the cover endpoint (if it
  1653. # runs next) doesn't refetch the same 36MB over FTP.
  1654. cache_3mf_download(printer_id, try_filename, temp_path)
  1655. break
  1656. except FileNotOnPrinterError:
  1657. # 550 — file isn't at this path. Advance to next candidate
  1658. # without burning the retry budget.
  1659. logger.debug("3MF not at %s (550), trying next path", remote_path)
  1660. except Exception as e:
  1661. logger.debug("FTP download failed for %s: %s", remote_path, e)
  1662. if downloaded_filename:
  1663. break
  1664. # If still not found, try listing directories to find matching file
  1665. # Different printer models use different directory structures
  1666. if not downloaded_filename and (filename or subtask_name):
  1667. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  1668. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  1669. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  1670. for search_dir in search_dirs:
  1671. if downloaded_filename:
  1672. break
  1673. try:
  1674. dir_files = await list_files_async(
  1675. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  1676. )
  1677. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  1678. if threemf_files:
  1679. logger.info(
  1680. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  1681. )
  1682. for f in dir_files:
  1683. if f.get("is_directory"):
  1684. continue
  1685. fname = f.get("name", "")
  1686. # Normalize both for comparison (spaces and underscores are equivalent)
  1687. fname_normalized = fname.lower().replace(" ", "_")
  1688. search_normalized = search_term.replace(" ", "_")
  1689. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  1690. logger.info("Found matching file in %s: %s", search_dir, fname)
  1691. temp_path = app_settings.archive_dir / "temp" / fname
  1692. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1693. remote_full_path = posixpath.join(search_dir, fname)
  1694. if ftp_retry_enabled:
  1695. downloaded = await with_ftp_retry(
  1696. download_file_async,
  1697. printer.ip_address,
  1698. printer.access_code,
  1699. remote_full_path,
  1700. temp_path,
  1701. timeout=ftp_timeout,
  1702. socket_timeout=ftp_timeout,
  1703. printer_model=printer.model,
  1704. max_retries=ftp_retry_count,
  1705. retry_delay=ftp_retry_delay,
  1706. operation_name=f"Download 3MF from {remote_full_path}",
  1707. )
  1708. else:
  1709. downloaded = await download_file_async(
  1710. printer.ip_address,
  1711. printer.access_code,
  1712. remote_full_path,
  1713. temp_path,
  1714. timeout=ftp_timeout,
  1715. socket_timeout=ftp_timeout,
  1716. printer_model=printer.model,
  1717. )
  1718. if downloaded:
  1719. downloaded_filename = fname
  1720. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  1721. cache_3mf_download(printer_id, fname, temp_path)
  1722. break
  1723. except Exception as e:
  1724. logger.debug("Failed to list %s: %s", search_dir, e)
  1725. if not downloaded_filename or not temp_path:
  1726. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  1727. # Create a fallback archive without 3MF data so the print is still tracked
  1728. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  1729. try:
  1730. from backend.app.models.archive import PrintArchive
  1731. # Derive print name from subtask_name or filename
  1732. print_name = subtask_name or filename
  1733. if print_name:
  1734. # Clean up the name (remove extensions, path parts)
  1735. print_name = print_name.split("/")[-1]
  1736. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1737. else:
  1738. print_name = "Unknown Print"
  1739. # Recover estimated print time from MQTT (best-effort for notifications)
  1740. fallback_print_time = None
  1741. mqtt_remaining = data.get("remaining_time")
  1742. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  1743. fallback_print_time = int(mqtt_remaining)
  1744. if fallback_print_time is None:
  1745. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  1746. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  1747. fallback_print_time = int(mc_remaining * 60)
  1748. # Create minimal archive entry
  1749. fallback_archive = PrintArchive(
  1750. printer_id=printer_id,
  1751. filename=filename or f"{print_name}.3mf",
  1752. file_path="", # Empty - no 3MF file available
  1753. file_size=0,
  1754. print_name=print_name,
  1755. print_time_seconds=fallback_print_time,
  1756. status="printing",
  1757. started_at=datetime.now(timezone.utc),
  1758. subtask_id=subtask_id,
  1759. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  1760. )
  1761. db.add(fallback_archive)
  1762. await db.commit()
  1763. await db.refresh(fallback_archive)
  1764. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  1765. # Start timelapse session if external camera is enabled
  1766. if printer.external_camera_enabled and printer.external_camera_url:
  1767. from backend.app.services.layer_timelapse import start_session
  1768. start_session(
  1769. printer_id,
  1770. fallback_archive.id,
  1771. printer.external_camera_url,
  1772. printer.external_camera_type or "mjpeg",
  1773. )
  1774. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, fallback_archive.id)
  1775. # Track as active print
  1776. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  1777. if filename:
  1778. _active_prints[(printer_id, filename)] = fallback_archive.id
  1779. if subtask_name:
  1780. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  1781. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  1782. # Record starting energy if smart plug available (#941: persisted column)
  1783. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  1784. # Send WebSocket notification
  1785. await ws_manager.send_archive_created(
  1786. {
  1787. "id": fallback_archive.id,
  1788. "printer_id": fallback_archive.printer_id,
  1789. "filename": fallback_archive.filename,
  1790. "print_name": fallback_archive.print_name,
  1791. "status": fallback_archive.status,
  1792. }
  1793. )
  1794. # MQTT relay - publish archive created
  1795. try:
  1796. await mqtt_relay.on_archive_created(
  1797. archive_id=fallback_archive.id,
  1798. print_name=fallback_archive.print_name,
  1799. printer_name=printer.name,
  1800. status=fallback_archive.status,
  1801. )
  1802. except Exception:
  1803. pass # Don't fail if MQTT fails
  1804. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  1805. try:
  1806. await _store_spoolman_print_data(
  1807. printer_id,
  1808. fallback_archive.id,
  1809. fallback_archive.file_path,
  1810. db,
  1811. printer_manager,
  1812. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  1813. )
  1814. except Exception as e:
  1815. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  1816. # Send notification without archive data (file not found)
  1817. if not notification_sent:
  1818. await _send_print_start_notification(printer_id, data, logger=logger)
  1819. return
  1820. except Exception as e:
  1821. logger.error("Failed to create fallback archive: %s", e)
  1822. # Send notification without archive data (file not found)
  1823. if not notification_sent:
  1824. await _send_print_start_notification(printer_id, data, logger=logger)
  1825. return
  1826. try:
  1827. # Archive the file with status "printing"
  1828. service = ArchiveService(db)
  1829. archive = await service.archive_print(
  1830. printer_id=printer_id,
  1831. source_file=temp_path,
  1832. print_data={**data, "status": "printing"},
  1833. subtask_id=subtask_id,
  1834. )
  1835. if archive:
  1836. # Track this active print (use both original filename and downloaded filename)
  1837. _active_prints[(printer_id, downloaded_filename)] = archive.id
  1838. if filename and filename != downloaded_filename:
  1839. _active_prints[(printer_id, filename)] = archive.id
  1840. if subtask_name:
  1841. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1842. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  1843. # Start timelapse session if external camera is enabled
  1844. if printer.external_camera_enabled and printer.external_camera_url:
  1845. from backend.app.services.layer_timelapse import start_session
  1846. start_session(
  1847. printer_id,
  1848. archive.id,
  1849. printer.external_camera_url,
  1850. printer.external_camera_type or "mjpeg",
  1851. )
  1852. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, archive.id)
  1853. # Record starting energy from smart plug if available (#941: persisted column)
  1854. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  1855. await ws_manager.send_archive_created(
  1856. {
  1857. "id": archive.id,
  1858. "printer_id": archive.printer_id,
  1859. "filename": archive.filename,
  1860. "print_name": archive.print_name,
  1861. "status": archive.status,
  1862. }
  1863. )
  1864. # MQTT relay - publish archive created
  1865. try:
  1866. await mqtt_relay.on_archive_created(
  1867. archive_id=archive.id,
  1868. print_name=archive.print_name,
  1869. printer_name=printer.name,
  1870. status=archive.status,
  1871. )
  1872. except Exception:
  1873. pass # Don't fail if MQTT fails
  1874. # Send notification with archive data (new archive created)
  1875. if not notification_sent:
  1876. archive_data = {
  1877. "print_time_seconds": archive.print_time_seconds,
  1878. "created_by_id": archive.created_by_id,
  1879. }
  1880. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1881. # Extract printable objects for skip object functionality
  1882. try:
  1883. from backend.app.services.archive import extract_printable_objects_from_3mf
  1884. with open(temp_path, "rb") as f:
  1885. threemf_data = f.read()
  1886. # Extract with positions for UI overlay
  1887. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  1888. threemf_data, include_positions=True
  1889. )
  1890. if printable_objects:
  1891. # Store objects in printer state
  1892. client = printer_manager.get_client(printer_id)
  1893. if client:
  1894. client.state.printable_objects = printable_objects
  1895. client.state.printable_objects_bbox_all = bbox_all
  1896. client.state.skipped_objects = [] # Reset skipped objects for new print
  1897. logger.info(
  1898. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  1899. )
  1900. except Exception as e:
  1901. logger.debug("Failed to extract printable objects: %s", e)
  1902. # Store Spoolman tracking data for per-filament usage reporting
  1903. try:
  1904. await _store_spoolman_print_data(
  1905. printer_id,
  1906. archive.id,
  1907. archive.file_path,
  1908. db,
  1909. printer_manager,
  1910. ams_mapping=_get_start_ams_mapping(data, archive.id),
  1911. )
  1912. except Exception as e:
  1913. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1914. # Capture timelapse file baseline for snapshot-diff on completion
  1915. try:
  1916. baseline_files, _ = await _list_timelapse_videos(printer)
  1917. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  1918. logger.info(
  1919. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  1920. len(_timelapse_baselines[printer_id]),
  1921. printer_id,
  1922. )
  1923. except Exception as e:
  1924. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  1925. finally:
  1926. # Keep temp_path around until print completes so the cover endpoint
  1927. # can reuse it (#972). Cache eviction in on_print_complete deletes
  1928. # the file. If the cache entry was evicted early (file vanished),
  1929. # clean up any stragglers here to avoid leaking disk on retries.
  1930. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  1931. if temp_path and temp_path.exists() and cached_now != temp_path:
  1932. temp_path.unlink()
  1933. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  1934. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  1935. """List video files from printer's timelapse directory.
  1936. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  1937. Returns (video_files, found_path) where video_files is a list of file dicts
  1938. and found_path is the directory where they were found, or ([], None).
  1939. """
  1940. from backend.app.services.bambu_ftp import list_files_async
  1941. logger = logging.getLogger(__name__)
  1942. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1943. try:
  1944. found_files = await list_files_async(
  1945. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1946. )
  1947. if found_files:
  1948. video_files = [
  1949. f
  1950. for f in found_files
  1951. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  1952. ]
  1953. if video_files:
  1954. return video_files, timelapse_path
  1955. except Exception as e:
  1956. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  1957. continue
  1958. return [], None
  1959. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  1960. """
  1961. Scan for timelapse with retries using a snapshot-diff approach.
  1962. Instead of picking the "most recent by mtime" (unreliable when the printer
  1963. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  1964. waiting, then look for any NEW filename that appears after each delay.
  1965. If baseline_names is provided (captured at print start), it is used directly.
  1966. Otherwise falls back to taking a baseline at completion time (best-effort
  1967. for prints started before app restart).
  1968. Falls back to name-matching (print name contained in MP4 filename) if no
  1969. new file appears after all retries.
  1970. """
  1971. from pathlib import Path
  1972. logger = logging.getLogger(__name__)
  1973. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  1974. try:
  1975. async with async_session() as db:
  1976. from backend.app.models.printer import Printer
  1977. service = ArchiveService(db)
  1978. archive = await service.get_archive(archive_id)
  1979. if not archive:
  1980. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  1981. return
  1982. if archive.timelapse_path:
  1983. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  1984. return
  1985. if not archive.printer_id:
  1986. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  1987. return
  1988. if baseline_names is not None:
  1989. # Use pre-captured baseline from print start (no race condition)
  1990. logger.info(
  1991. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  1992. len(baseline_names),
  1993. archive_id,
  1994. )
  1995. else:
  1996. # Fallback: take baseline now (e.g. app restarted mid-print)
  1997. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1998. printer = result.scalar_one_or_none()
  1999. if not printer:
  2000. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  2001. return
  2002. baseline_files, _ = await _list_timelapse_videos(printer)
  2003. baseline_names = {f.get("name", "") for f in baseline_files}
  2004. logger.info(
  2005. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  2006. len(baseline_names),
  2007. archive_id,
  2008. )
  2009. # Derive base_name for name-matching fallback
  2010. base_name = Path(archive.filename).stem if archive.filename else ""
  2011. if base_name.endswith(".gcode"):
  2012. base_name = base_name[:-6]
  2013. except Exception as e:
  2014. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  2015. return
  2016. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  2017. retry_delays = [5, 10, 20, 30]
  2018. for attempt, delay in enumerate(retry_delays, 1):
  2019. logger.info(
  2020. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  2021. attempt,
  2022. len(retry_delays),
  2023. delay,
  2024. archive_id,
  2025. )
  2026. await asyncio.sleep(delay)
  2027. try:
  2028. async with async_session() as db:
  2029. from backend.app.models.printer import Printer
  2030. from backend.app.services.bambu_ftp import download_file_bytes_async
  2031. service = ArchiveService(db)
  2032. archive = await service.get_archive(archive_id)
  2033. if not archive:
  2034. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  2035. return
  2036. if archive.timelapse_path:
  2037. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  2038. return
  2039. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2040. printer = result.scalar_one_or_none()
  2041. if not printer:
  2042. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  2043. return
  2044. video_files, found_path = await _list_timelapse_videos(printer)
  2045. if not video_files:
  2046. logger.info("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  2047. continue
  2048. logger.info("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  2049. for f in video_files[:5]:
  2050. logger.info("[TIMELAPSE] - %s", f.get("name"))
  2051. # Find files that are NEW (not in baseline snapshot)
  2052. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  2053. if new_files:
  2054. # Pick the first new file (there should typically be exactly one)
  2055. target = new_files[0]
  2056. file_name = target.get("name")
  2057. remote_path = target.get("path") or f"/timelapse/{file_name}"
  2058. logger.info(
  2059. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  2060. attempt,
  2061. file_name,
  2062. archive_id,
  2063. )
  2064. timelapse_data = await download_file_bytes_async(
  2065. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2066. )
  2067. if timelapse_data:
  2068. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  2069. if success:
  2070. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  2071. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2072. return
  2073. else:
  2074. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  2075. else:
  2076. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  2077. else:
  2078. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  2079. except Exception as e:
  2080. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  2081. # --- Phase 3: Fallback — try name matching against all files ---
  2082. if base_name:
  2083. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  2084. try:
  2085. async with async_session() as db:
  2086. from backend.app.models.printer import Printer
  2087. from backend.app.services.bambu_ftp import download_file_bytes_async
  2088. service = ArchiveService(db)
  2089. archive = await service.get_archive(archive_id)
  2090. if not archive or archive.timelapse_path:
  2091. return
  2092. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2093. printer = result.scalar_one_or_none()
  2094. if not printer:
  2095. return
  2096. video_files, found_path = await _list_timelapse_videos(printer)
  2097. for f in video_files:
  2098. fname = f.get("name", "")
  2099. if base_name.lower() in fname.lower():
  2100. remote_path = f.get("path") or f"/timelapse/{fname}"
  2101. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  2102. timelapse_data = await download_file_bytes_async(
  2103. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2104. )
  2105. if timelapse_data:
  2106. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  2107. if success:
  2108. logger.info(
  2109. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  2110. )
  2111. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2112. return
  2113. break # Only try the first name match
  2114. except Exception as e:
  2115. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  2116. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  2117. async def on_print_complete(printer_id: int, data: dict):
  2118. """Handle print completion - update the archive status."""
  2119. import time
  2120. logger = logging.getLogger(__name__)
  2121. start_time = time.time()
  2122. def log_timing(section: str):
  2123. elapsed = time.time() - start_time
  2124. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  2125. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  2126. # Drop the 3MF download cache for this printer (#972). The print is over,
  2127. # nothing else legitimately needs the bytes; keeping them would only risk
  2128. # handing a stale file to the next print if it reuses the same name.
  2129. clear_3mf_cache(printer_id)
  2130. try:
  2131. ws_data = {
  2132. "status": data.get("status"),
  2133. "filename": data.get("filename"),
  2134. "subtask_name": data.get("subtask_name"),
  2135. "timelapse_was_active": data.get("timelapse_was_active"),
  2136. }
  2137. await ws_manager.send_print_complete(printer_id, ws_data)
  2138. log_timing("WebSocket send_print_complete")
  2139. except Exception as e:
  2140. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  2141. # Capture user info before clearing (needed for print log entry)
  2142. _print_user_info = printer_manager.get_current_print_user(printer_id)
  2143. # Clear current print user tracking (Issue #206)
  2144. printer_manager.clear_current_print_user(printer_id)
  2145. # If the user explicitly stopped this print from the queue UI the printer will
  2146. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  2147. # correct "print stopped" notification/email is sent instead of a failure alert.
  2148. _raw_status = data.get("status", "completed")
  2149. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  2150. logger.info(
  2151. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  2152. _raw_status,
  2153. printer_id,
  2154. )
  2155. data = {**data, "status": "cancelled"}
  2156. _user_stopped_printers.discard(printer_id)
  2157. # Raise the plate-clear gate for queued dispatch (#961). Only for completed/failed —
  2158. # user-cancelled prints don't require a plate-clear ack (nothing printed on the bed).
  2159. # Persisted to DB so the gate survives Auto Off power cycles and Bambuddy restarts.
  2160. _final_status = data.get("status", "completed")
  2161. if _final_status in ("completed", "failed"):
  2162. printer_manager.set_awaiting_plate_clear(printer_id, True)
  2163. # MQTT relay - publish print complete
  2164. try:
  2165. printer_info = printer_manager.get_printer(printer_id)
  2166. if printer_info:
  2167. await mqtt_relay.on_print_complete(
  2168. printer_id,
  2169. printer_info.name,
  2170. printer_info.serial_number,
  2171. data.get("filename", ""),
  2172. data.get("subtask_name", ""),
  2173. data.get("status", "completed"),
  2174. )
  2175. except Exception:
  2176. pass # Don't fail print complete callback if MQTT fails
  2177. filename = data.get("filename", "")
  2178. subtask_name = data.get("subtask_name", "")
  2179. if not filename and not subtask_name:
  2180. logger.warning("Print complete without filename or subtask_name")
  2181. return
  2182. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  2183. # Build list of possible keys to try (matching how they were registered in on_print_start)
  2184. possible_keys = []
  2185. # Try subtask_name variations first (most reliable for matching)
  2186. if subtask_name:
  2187. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  2188. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  2189. possible_keys.append((printer_id, subtask_name))
  2190. # Try filename variations
  2191. if filename:
  2192. # Extract just the filename if it's a path
  2193. fname = filename.split("/")[-1] if "/" in filename else filename
  2194. if fname.endswith(".3mf"):
  2195. possible_keys.append((printer_id, fname))
  2196. elif fname.endswith(".gcode"):
  2197. base_name = fname.rsplit(".", 1)[0]
  2198. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  2199. possible_keys.append((printer_id, f"{base_name}.3mf"))
  2200. possible_keys.append((printer_id, fname))
  2201. else:
  2202. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  2203. possible_keys.append((printer_id, f"{fname}.3mf"))
  2204. possible_keys.append((printer_id, fname))
  2205. # Also try full path versions
  2206. if filename.endswith(".3mf"):
  2207. possible_keys.append((printer_id, filename))
  2208. elif filename.endswith(".gcode"):
  2209. base_name = filename.rsplit(".", 1)[0]
  2210. possible_keys.append((printer_id, f"{base_name}.3mf"))
  2211. possible_keys.append((printer_id, filename))
  2212. else:
  2213. possible_keys.append((printer_id, f"{filename}.3mf"))
  2214. possible_keys.append((printer_id, filename))
  2215. # Find the archive for this print
  2216. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  2217. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  2218. archive_id = None
  2219. for key in possible_keys:
  2220. archive_id = _active_prints.pop(key, None)
  2221. if archive_id:
  2222. logger.info("Found archive %s with key %s", archive_id, key)
  2223. # Also clean up any other keys pointing to this archive
  2224. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  2225. for k in keys_to_remove:
  2226. _active_prints.pop(k, None)
  2227. break
  2228. if not archive_id:
  2229. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  2230. async with async_session() as db:
  2231. from backend.app.models.archive import PrintArchive
  2232. # Try matching by subtask_name (stored as print_name) first
  2233. if subtask_name:
  2234. result = await db.execute(
  2235. select(PrintArchive)
  2236. .where(PrintArchive.printer_id == printer_id)
  2237. .where(PrintArchive.status == "printing")
  2238. .where(
  2239. or_(
  2240. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  2241. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  2242. )
  2243. )
  2244. .order_by(PrintArchive.created_at.desc())
  2245. .limit(1)
  2246. )
  2247. archive = result.scalar_one_or_none()
  2248. if archive:
  2249. archive_id = archive.id
  2250. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  2251. # Also try by filename
  2252. if not archive_id and filename:
  2253. result = await db.execute(
  2254. select(PrintArchive)
  2255. .where(PrintArchive.printer_id == printer_id)
  2256. .where(PrintArchive.filename == filename)
  2257. .where(PrintArchive.status == "printing")
  2258. .order_by(PrintArchive.created_at.desc())
  2259. .limit(1)
  2260. )
  2261. archive = result.scalar_one_or_none()
  2262. if archive:
  2263. archive_id = archive.id
  2264. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374)
  2265. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S)
  2266. # auto-start files found in root on power cycle, causing ghost prints.
  2267. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  2268. try:
  2269. if subtask_name:
  2270. async with async_session() as db:
  2271. from backend.app.models.printer import Printer
  2272. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2273. printer = result.scalar_one_or_none()
  2274. if printer:
  2275. from backend.app.services.bambu_ftp import delete_file_async
  2276. # Try both .3mf and .gcode extensions — the printer may have either
  2277. for ext in (".3mf", ".gcode"):
  2278. remote_path = f"/{subtask_name}{ext}"
  2279. # Retry up to 3 times — the printer may still lock the filesystem briefly after a print ends
  2280. for attempt in range(1, 4):
  2281. try:
  2282. delete_result = await delete_file_async(
  2283. printer.ip_address,
  2284. printer.access_code,
  2285. remote_path,
  2286. printer_model=printer.model,
  2287. )
  2288. if delete_result:
  2289. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  2290. break
  2291. except Exception as e:
  2292. delete_result = False
  2293. logger.warning(
  2294. "SD card cleanup attempt %d/3 raised for %s: %s",
  2295. attempt,
  2296. remote_path,
  2297. e,
  2298. )
  2299. if not delete_result and attempt < 3:
  2300. await asyncio.sleep(2)
  2301. elif not delete_result:
  2302. logger.warning(
  2303. "SD card cleanup failed after 3 attempts for %s (file may linger on SD card)",
  2304. remote_path,
  2305. )
  2306. except Exception as e:
  2307. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  2308. log_timing("SD card cleanup")
  2309. # Update queue item status early — must run before the archive_id early-return
  2310. # so queue items don't get stuck in "printing" when archive lookup fails.
  2311. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  2312. queue_item_id = None
  2313. queue_status = None
  2314. queue_auto_off = False
  2315. try:
  2316. from backend.app.core.database import run_with_retry
  2317. from backend.app.models.print_queue import PrintQueueItem
  2318. async def _update_queue_status(db):
  2319. nonlocal queue_item_id, queue_status, queue_auto_off
  2320. result = await db.execute(
  2321. select(PrintQueueItem)
  2322. .where(PrintQueueItem.printer_id == printer_id)
  2323. .where(PrintQueueItem.status == "printing")
  2324. )
  2325. printing_items = list(result.scalars().all())
  2326. if len(printing_items) > 1:
  2327. logger.warning(
  2328. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  2329. printer_id,
  2330. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  2331. )
  2332. item = printing_items[0] if printing_items else None
  2333. if item:
  2334. queue_status = data.get("status", "completed")
  2335. # MQTT sends "aborted" for cancelled prints; normalise to
  2336. # "cancelled" so it matches the queue schema Literal.
  2337. if queue_status == "aborted":
  2338. queue_status = "cancelled"
  2339. item.status = queue_status
  2340. item.completed_at = datetime.now(timezone.utc)
  2341. # Bump usage counters on the source library file so admins can
  2342. # sort by "last printed" and (eventually) auto-purge stale
  2343. # files — #1008.
  2344. await _bump_library_file_usage_if_completed(db, item, queue_status)
  2345. await db.commit()
  2346. queue_item_id = item.id
  2347. queue_auto_off = item.auto_off_after
  2348. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  2349. await run_with_retry(_update_queue_status, label="queue status update")
  2350. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  2351. # their own sessions and have their own error handling — no retry needed.
  2352. if queue_item_id is not None:
  2353. # MQTT relay - publish queue job completed
  2354. try:
  2355. printer_info = printer_manager.get_printer(printer_id)
  2356. await mqtt_relay.on_queue_job_completed(
  2357. job_id=queue_item_id,
  2358. filename=filename or subtask_name,
  2359. printer_id=printer_id,
  2360. printer_name=printer_info.name if printer_info else "Unknown",
  2361. status=queue_status,
  2362. )
  2363. except Exception:
  2364. pass # Don't fail if MQTT fails
  2365. # Check if queue is now empty and send notification
  2366. try:
  2367. from sqlalchemy import func as sa_func
  2368. async with async_session() as db:
  2369. count_result = await db.execute(
  2370. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  2371. )
  2372. pending_count = count_result.scalar() or 0
  2373. if pending_count == 0:
  2374. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  2375. completed_result = await db.execute(
  2376. select(sa_func.count(PrintQueueItem.id)).where(
  2377. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  2378. PrintQueueItem.completed_at >= today_start,
  2379. )
  2380. )
  2381. completed_count = completed_result.scalar() or 1
  2382. await notification_service.on_queue_completed(
  2383. completed_count=completed_count,
  2384. db=db,
  2385. )
  2386. except Exception:
  2387. pass # Don't fail if notification fails
  2388. # Handle auto_off_after - power off printer if requested (after cooldown)
  2389. if queue_auto_off:
  2390. async with async_session() as db:
  2391. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2392. plugs = list(result.scalars().all())
  2393. enabled_plugs = [p for p in plugs if p.enabled]
  2394. if enabled_plugs:
  2395. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  2396. async def cooldown_and_poweroff(pid: int, plug_ids: list[int]):
  2397. # Wait for nozzle to cool down
  2398. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  2399. # Re-fetch plugs in new session and turn off each one
  2400. async with async_session() as new_db:
  2401. for plug_id in plug_ids:
  2402. try:
  2403. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  2404. p = result.scalar_one_or_none()
  2405. if p and p.enabled:
  2406. service = await smart_plug_manager.get_service_for_plug(p, new_db)
  2407. success = await service.turn_off(p)
  2408. if success:
  2409. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  2410. else:
  2411. logger.warning("Failed to power off plug '%s' for printer %s", p.name, pid)
  2412. except Exception as e:
  2413. logger.warning("Failed to power off plug %s for printer %s: %s", plug_id, pid, e)
  2414. asyncio.create_task(cooldown_and_poweroff(printer_id, [p.id for p in enabled_plugs]))
  2415. except Exception as e:
  2416. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  2417. log_timing("Queue item update")
  2418. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  2419. # Must run before archive_id early-return so it fires for all prints (including
  2420. # prints started from BambuStudio/touchscreen that have no archive).
  2421. if data.get("status") == "completed":
  2422. try:
  2423. from backend.app.api.routes.settings import get_setting
  2424. async with async_session() as db:
  2425. threshold_str = await get_setting(db, "bed_cooled_threshold")
  2426. threshold = float(threshold_str) if threshold_str else 35.0
  2427. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  2428. async with async_session() as db:
  2429. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  2430. if providers:
  2431. _bed_cool_waiters[printer_id] = {
  2432. "threshold": threshold,
  2433. "filename": filename or subtask_name or "",
  2434. "registered_at": time.time(),
  2435. }
  2436. logger.info(
  2437. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  2438. printer_id,
  2439. threshold,
  2440. )
  2441. else:
  2442. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  2443. except Exception as e:
  2444. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  2445. # --- Track filament consumption (must run before archive_id early-return so usage
  2446. # is recorded even when auto-archive is disabled) ---
  2447. usage_results: list[dict] = []
  2448. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  2449. stored_ams_mapping = data.get("ams_mapping")
  2450. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  2451. if not stored_ams_mapping and archive_id:
  2452. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  2453. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  2454. try:
  2455. async with async_session() as db:
  2456. from backend.app.api.routes.settings import get_setting
  2457. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2458. if not _spoolman_on or _spoolman_on.lower() != "true":
  2459. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  2460. async with async_session() as db:
  2461. usage_results = await usage_on_print_complete(
  2462. printer_id,
  2463. data,
  2464. printer_manager,
  2465. db,
  2466. archive_id=archive_id,
  2467. ams_mapping=stored_ams_mapping,
  2468. )
  2469. if usage_results:
  2470. await ws_manager.broadcast(
  2471. {
  2472. "type": "spool_usage_logged",
  2473. "printer_id": printer_id,
  2474. "usage": usage_results,
  2475. }
  2476. )
  2477. log_timing("Usage tracker")
  2478. except Exception as e:
  2479. logger.warning("Usage tracker on_print_complete failed: %s", e)
  2480. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  2481. if archive_id:
  2482. if data.get("status") == "completed":
  2483. try:
  2484. await _report_spoolman_usage(printer_id, archive_id)
  2485. log_timing("Spoolman usage report")
  2486. except Exception as e:
  2487. logger.warning("Spoolman usage reporting failed: %s", e)
  2488. else:
  2489. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  2490. try:
  2491. async with async_session() as db:
  2492. await _cleanup_spoolman_tracking(
  2493. printer_id,
  2494. archive_id,
  2495. db,
  2496. last_layer_num=data.get("last_layer_num"),
  2497. last_progress=data.get("last_progress"),
  2498. )
  2499. except Exception as e:
  2500. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  2501. log_timing("Filament usage tracking")
  2502. if not archive_id:
  2503. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  2504. # Still send print-complete/failed/stopped notifications even without an archive.
  2505. # Try to enrich with queue/library-file data so user-specific emails work too.
  2506. async def _notify_no_archive():
  2507. try:
  2508. async with async_session() as db:
  2509. from backend.app.models.library import LibraryFile
  2510. from backend.app.models.print_queue import PrintQueueItem
  2511. from backend.app.models.printer import Printer
  2512. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2513. printer_obj = result.scalar_one_or_none()
  2514. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  2515. # Try to find the most-recent queue item for this printer so we can
  2516. # recover created_by_id and estimated print time.
  2517. # NOTE: By the time this task runs the queue item status has already
  2518. # been updated to a terminal state (completed/failed/cancelled), so
  2519. # we look for recently-completed items (within the last 5 minutes).
  2520. no_archive_data: dict | None = None
  2521. try:
  2522. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  2523. q_result = await db.execute(
  2524. select(PrintQueueItem)
  2525. .where(PrintQueueItem.printer_id == printer_id)
  2526. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  2527. .where(PrintQueueItem.completed_at >= cutoff)
  2528. .order_by(PrintQueueItem.completed_at.desc())
  2529. .limit(1)
  2530. )
  2531. queue_item = q_result.scalar_one_or_none()
  2532. if queue_item:
  2533. no_archive_data = {"created_by_id": queue_item.created_by_id}
  2534. # Pull estimated time from library file when available
  2535. if queue_item.library_file_id:
  2536. lib_result = await db.execute(
  2537. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  2538. )
  2539. lib_file = lib_result.scalar_one_or_none()
  2540. if lib_file and lib_file.print_time_seconds:
  2541. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  2542. except Exception as lookup_err:
  2543. logger.debug(
  2544. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  2545. )
  2546. # Enrich with usage tracker results (captured in enclosing scope)
  2547. if usage_results:
  2548. if no_archive_data is None:
  2549. no_archive_data = {}
  2550. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  2551. if total_from_usage > 0:
  2552. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  2553. no_archive_data["usage_results"] = usage_results
  2554. # Try MQTT remaining_time for print duration when no queue/library data
  2555. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  2556. mqtt_remaining = data.get("remaining_time")
  2557. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  2558. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  2559. ps = data.get("status", "completed")
  2560. logger.info(
  2561. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  2562. )
  2563. await notification_service.on_print_complete(
  2564. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  2565. )
  2566. # Send user-specific email if we have a created_by_id
  2567. if no_archive_data and no_archive_data.get("created_by_id"):
  2568. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  2569. await _dispatch_user_print_email(
  2570. ps,
  2571. no_archive_data["created_by_id"],
  2572. p_name,
  2573. raw_filename,
  2574. db,
  2575. )
  2576. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  2577. except Exception as e:
  2578. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  2579. task = asyncio.create_task(_notify_no_archive())
  2580. task.add_done_callback(lambda _t: None)
  2581. return
  2582. log_timing("Archive lookup")
  2583. # Update archive status
  2584. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  2585. try:
  2586. async with async_session() as db:
  2587. service = ArchiveService(db)
  2588. status = data.get("status", "completed")
  2589. # Auto-detect failure reason
  2590. failure_reason = None
  2591. if status == "aborted":
  2592. failure_reason = "User cancelled"
  2593. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  2594. elif status == "failed":
  2595. # Try to determine failure reason from HMS errors
  2596. hms_errors = data.get("hms_errors", [])
  2597. if hms_errors:
  2598. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  2599. # Map known HMS error modules to failure reasons
  2600. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  2601. for err in hms_errors:
  2602. module = err.get("module", 0)
  2603. if module == 0x07: # Filament module
  2604. failure_reason = "Filament runout"
  2605. break
  2606. elif module == 0x0C: # Motion controller
  2607. failure_reason = "Layer shift"
  2608. break
  2609. elif module == 0x05: # Nozzle/extruder
  2610. failure_reason = "Clogged nozzle"
  2611. break
  2612. if failure_reason:
  2613. logger.info("[ARCHIVE] Detected failure_reason from HMS: %s", failure_reason)
  2614. else:
  2615. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  2616. await service.update_archive_status(
  2617. archive_id,
  2618. status=status,
  2619. completed_at=datetime.now(timezone.utc) if status in ("completed", "failed", "aborted") else None,
  2620. failure_reason=failure_reason,
  2621. )
  2622. logger.info(
  2623. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  2624. )
  2625. await ws_manager.send_archive_updated(
  2626. {
  2627. "id": archive_id,
  2628. "status": status,
  2629. }
  2630. )
  2631. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  2632. # MQTT relay - publish archive updated
  2633. try:
  2634. await mqtt_relay.on_archive_updated(
  2635. archive_id=archive_id,
  2636. print_name=filename or subtask_name,
  2637. status=status,
  2638. )
  2639. except Exception:
  2640. pass # Don't fail if MQTT fails
  2641. except Exception as e:
  2642. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  2643. # Continue with other operations even if archive update fails
  2644. log_timing("Archive status update")
  2645. # Write independent print log entry (separate table, never touches archives)
  2646. try:
  2647. async with async_session() as db:
  2648. from backend.app.models.archive import PrintArchive
  2649. from backend.app.services.print_log import write_log_entry
  2650. archive = await db.get(PrintArchive, archive_id)
  2651. if archive:
  2652. # Back-fill created_by_id on reprint (#730): reprint reuses the
  2653. # source archive row rather than creating a new one, so an
  2654. # archive that was auto-created from a printer-initiated
  2655. # print (created_by_id=NULL) would otherwise stay unattributed
  2656. # forever. When we have a print-session user AND the archive
  2657. # has no attribution yet, credit the current user. Never
  2658. # overwrite an existing attribution — the original uploader
  2659. # keeps ownership.
  2660. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  2661. if archive.created_by_id is None and _print_user_id is not None:
  2662. archive.created_by_id = _print_user_id
  2663. p_info = printer_manager.get_printer(printer_id)
  2664. await write_log_entry(
  2665. db,
  2666. status=data.get("status", "completed"),
  2667. print_name=archive.print_name,
  2668. printer_name=p_info.name if p_info else None,
  2669. printer_id=printer_id,
  2670. started_at=archive.started_at,
  2671. completed_at=archive.completed_at,
  2672. filament_type=archive.filament_type,
  2673. filament_color=archive.filament_color,
  2674. filament_used_grams=archive.filament_used_grams,
  2675. thumbnail_path=archive.thumbnail_path,
  2676. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  2677. )
  2678. await db.commit()
  2679. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  2680. except Exception as e:
  2681. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  2682. log_timing("Print log entry")
  2683. # Run slow operations as background tasks to avoid blocking the event loop
  2684. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  2685. async def _background_energy_calculation():
  2686. """Calculate and save energy usage in background.
  2687. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  2688. backend restart no longer loses per-print energy data).
  2689. """
  2690. try:
  2691. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  2692. async with async_session() as db:
  2693. from backend.app.models.archive import PrintArchive
  2694. archive = await db.get(PrintArchive, archive_id)
  2695. if archive is None:
  2696. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  2697. return
  2698. starting_kwh = archive.energy_start_kwh
  2699. if starting_kwh is None:
  2700. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  2701. return
  2702. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2703. plug = plug_result.scalar_one_or_none()
  2704. if plug is None:
  2705. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  2706. return
  2707. energy = await _get_plug_energy(plug, db)
  2708. logger.info("[ENERGY-BG] Energy response: %s", energy)
  2709. if not energy or energy.get("total") is None:
  2710. logger.warning("[ENERGY-BG] No 'total' in energy response")
  2711. return
  2712. energy_used = round(energy["total"] - starting_kwh, 4)
  2713. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  2714. if energy_used < 0:
  2715. logger.warning(
  2716. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  2717. archive_id,
  2718. starting_kwh,
  2719. energy["total"],
  2720. )
  2721. return
  2722. from backend.app.api.routes.settings import get_setting
  2723. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  2724. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  2725. archive.energy_kwh = energy_used
  2726. archive.energy_cost = round(energy_used * cost_per_kwh, 3)
  2727. await db.commit()
  2728. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, archive.energy_cost)
  2729. except Exception as e:
  2730. logger.warning("[ENERGY-BG] Failed: %s", e)
  2731. async def _background_finish_photo() -> str | None:
  2732. """Capture finish photo in background. Returns photo filename if captured."""
  2733. try:
  2734. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  2735. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2736. async with async_session() as db:
  2737. from backend.app.api.routes.settings import get_setting
  2738. capture_enabled = await get_setting(db, "capture_finish_photo")
  2739. if capture_enabled is None or capture_enabled.lower() == "true":
  2740. from backend.app.models.printer import Printer
  2741. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2742. printer = result.scalar_one_or_none()
  2743. if printer and archive_id:
  2744. from backend.app.models.archive import PrintArchive
  2745. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2746. archive = result.scalar_one_or_none()
  2747. if archive:
  2748. import uuid
  2749. from datetime import datetime
  2750. from pathlib import Path
  2751. if archive.file_path:
  2752. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  2753. else:
  2754. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  2755. archive_dir = app_settings.archive_dir / str(archive.id)
  2756. photo_filename = None
  2757. # Check for external camera first
  2758. if printer.external_camera_enabled and printer.external_camera_url:
  2759. logger.info("[PHOTO-BG] Using external camera")
  2760. from backend.app.services.external_camera import capture_frame
  2761. frame_data = await capture_frame(
  2762. printer.external_camera_url, printer.external_camera_type or "mjpeg"
  2763. )
  2764. if frame_data:
  2765. photos_dir = archive_dir / "photos"
  2766. photos_dir.mkdir(parents=True, exist_ok=True)
  2767. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  2768. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  2769. photo_path = photos_dir / photo_filename
  2770. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  2771. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  2772. else:
  2773. # Check if camera stream is active - use buffered frame to avoid freeze
  2774. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  2775. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2776. active_chamber_for_printer = [
  2777. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  2778. ]
  2779. buffered_frame = get_buffered_frame(printer_id)
  2780. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  2781. # Use frame from active stream
  2782. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  2783. photos_dir = archive_dir / "photos"
  2784. photos_dir.mkdir(parents=True, exist_ok=True)
  2785. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  2786. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  2787. photo_path = photos_dir / photo_filename
  2788. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  2789. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  2790. else:
  2791. # No active stream - capture new frame
  2792. from backend.app.services.camera import capture_finish_photo
  2793. photo_filename = await capture_finish_photo(
  2794. printer_id=printer_id,
  2795. ip_address=printer.ip_address,
  2796. access_code=printer.access_code,
  2797. model=printer.model,
  2798. archive_dir=archive_dir,
  2799. )
  2800. if photo_filename:
  2801. photos = archive.photos or []
  2802. photos.append(photo_filename)
  2803. archive.photos = photos
  2804. await db.commit()
  2805. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  2806. return photo_filename
  2807. return None
  2808. except Exception as e:
  2809. logger.warning("[PHOTO-BG] Failed: %s", e)
  2810. return None
  2811. asyncio.create_task(_background_energy_calculation())
  2812. # Photo capture task - result will be used by notifications
  2813. photo_task = asyncio.create_task(_background_finish_photo())
  2814. log_timing("Background tasks scheduled (energy, photo)")
  2815. # Also run smart plug, notifications, and maintenance as background tasks
  2816. print_status = data.get("status", "completed")
  2817. async def _background_smart_plug():
  2818. """Handle smart plug automation in background."""
  2819. try:
  2820. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  2821. async with async_session() as db:
  2822. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  2823. logger.info("[AUTO-OFF-BG] Completed")
  2824. except Exception as e:
  2825. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  2826. async def _background_notifications(finish_photo_filename: str | None = None):
  2827. """Send print complete notifications in background."""
  2828. try:
  2829. logger.info(
  2830. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  2831. )
  2832. async with async_session() as db:
  2833. from backend.app.models.archive import PrintArchive
  2834. from backend.app.models.printer import Printer
  2835. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2836. printer = result.scalar_one_or_none()
  2837. printer_name = printer.name if printer else f"Printer {printer_id}"
  2838. archive_data = None
  2839. if archive_id:
  2840. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2841. archive = archive_result.scalar_one_or_none()
  2842. if archive:
  2843. archive_data = {
  2844. "print_time_seconds": archive.print_time_seconds,
  2845. "actual_filament_grams": archive.filament_used_grams,
  2846. "failure_reason": archive.failure_reason,
  2847. "created_by_id": archive.created_by_id,
  2848. }
  2849. # Scale filament usage for partial prints
  2850. if print_status != "completed" and archive.filament_used_grams:
  2851. progress = data.get("progress") or 0
  2852. scale = max(0.0, min(progress / 100.0, 1.0))
  2853. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  2854. archive_data["progress"] = progress
  2855. # Pass per-slot data from archive.extra_data
  2856. if archive.extra_data and archive.extra_data.get("filament_slots"):
  2857. slots = archive.extra_data["filament_slots"]
  2858. if print_status != "completed":
  2859. scale = max(0.0, min((data.get("progress") or 0) / 100.0, 1.0))
  2860. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  2861. archive_data["filament_slots"] = slots
  2862. # Enrich filament_grams from usage_results when archive has no 3MF data
  2863. if not archive_data.get("actual_filament_grams") and usage_results:
  2864. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  2865. if total_from_usage > 0:
  2866. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  2867. # Pass usage tracker results for AMS slot info in notifications
  2868. if usage_results:
  2869. archive_data["usage_results"] = usage_results
  2870. # Add finish photo URL and image bytes if available
  2871. if finish_photo_filename:
  2872. from backend.app.api.routes.settings import get_setting
  2873. external_url = await get_setting(db, "external_url")
  2874. if external_url:
  2875. external_url = external_url.rstrip("/")
  2876. archive_data["finish_photo_url"] = (
  2877. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2878. )
  2879. else:
  2880. # Fallback to relative URL (won't work for external services)
  2881. archive_data["finish_photo_url"] = (
  2882. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2883. )
  2884. # Read finish photo bytes for image attachment (e.g. Pushover)
  2885. try:
  2886. from pathlib import Path
  2887. photo_path = (
  2888. app_settings.base_dir
  2889. / Path(archive.file_path).parent
  2890. / "photos"
  2891. / finish_photo_filename
  2892. )
  2893. if photo_path.exists():
  2894. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2895. if len(photo_bytes) <= 2_500_000:
  2896. archive_data["image_data"] = photo_bytes
  2897. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2898. else:
  2899. logger.warning(
  2900. f"[NOTIFY-BG] Finish photo too large for attachment: "
  2901. f"{len(photo_bytes)} bytes"
  2902. )
  2903. except Exception as e:
  2904. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2905. await notification_service.on_print_complete(
  2906. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  2907. )
  2908. # Send user-specific email notification
  2909. if archive_data:
  2910. created_by_id = archive_data.get("created_by_id")
  2911. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  2912. await _dispatch_user_print_email(
  2913. print_status,
  2914. created_by_id,
  2915. printer_name,
  2916. raw_filename,
  2917. db,
  2918. )
  2919. logger.info("[NOTIFY-BG] Completed")
  2920. except Exception as e:
  2921. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  2922. async def _background_maintenance_check():
  2923. """Check for maintenance due in background."""
  2924. if print_status != "completed":
  2925. return
  2926. try:
  2927. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  2928. async with async_session() as db:
  2929. from backend.app.models.printer import Printer
  2930. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2931. printer = result.scalar_one_or_none()
  2932. printer_name = printer.name if printer else f"Printer {printer_id}"
  2933. await ensure_default_types(db)
  2934. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  2935. items_needing_attention = [
  2936. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  2937. for item in overview.maintenance_items
  2938. if item.enabled and (item.is_due or item.is_warning)
  2939. ]
  2940. if items_needing_attention:
  2941. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  2942. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  2943. # MQTT relay - publish maintenance alerts
  2944. for item in items_needing_attention:
  2945. try:
  2946. await mqtt_relay.on_maintenance_alert(
  2947. printer_id=printer_id,
  2948. printer_name=printer_name,
  2949. maintenance_type=item["name"],
  2950. current_value=0, # Not easily available here
  2951. threshold=0, # Not easily available here
  2952. )
  2953. except Exception:
  2954. pass # Don't fail if MQTT fails
  2955. else:
  2956. logger.info("[MAINT-BG] Completed (no items need attention)")
  2957. except Exception as e:
  2958. logger.warning("[MAINT-BG] Failed: %s", e)
  2959. asyncio.create_task(_background_smart_plug())
  2960. asyncio.create_task(_background_maintenance_check())
  2961. # Notification task waits for photo capture to complete first (with timeout)
  2962. async def _photo_then_notify():
  2963. """Wait for photo capture, then send notification with photo URL."""
  2964. finish_photo = None
  2965. try:
  2966. finish_photo = await asyncio.wait_for(photo_task, timeout=45)
  2967. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  2968. except TimeoutError:
  2969. logger.warning("[PHOTO-NOTIFY] Photo capture timed out after 45s, sending notification without photo")
  2970. except Exception as e:
  2971. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  2972. try:
  2973. await _background_notifications(finish_photo)
  2974. except Exception as e:
  2975. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  2976. asyncio.create_task(_photo_then_notify())
  2977. # Stitch external camera layer timelapse if session was active
  2978. print_status = data.get("status", "completed")
  2979. async def _background_layer_timelapse():
  2980. """Stitch layer timelapse and attach to archive."""
  2981. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  2982. try:
  2983. if print_status == "completed":
  2984. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  2985. timelapse_path = await tl_complete(printer_id)
  2986. if timelapse_path and archive_id:
  2987. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  2988. async with async_session() as db:
  2989. service = ArchiveService(db)
  2990. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  2991. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  2992. # Clean up the temp file
  2993. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2994. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  2995. elif timelapse_path:
  2996. # Timelapse created but no archive - just clean up
  2997. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2998. else:
  2999. # Print failed or cancelled - cancel timelapse session
  3000. cancel_session(printer_id)
  3001. logger.info(
  3002. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  3003. )
  3004. except Exception as e:
  3005. logger.warning("[LAYER-TL] Failed: %s", e)
  3006. # Try to cancel session on error
  3007. try:
  3008. cancel_session(printer_id)
  3009. except Exception:
  3010. pass # Best-effort timelapse session cancellation on error
  3011. asyncio.create_task(_background_layer_timelapse())
  3012. log_timing("All background tasks scheduled")
  3013. # Auto-scan for timelapse if recording was active during the print
  3014. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  3015. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  3016. # Schedule timelapse scan as background task with retries
  3017. # The printer needs time to encode the video after print completion
  3018. baseline = _timelapse_baselines.pop(printer_id, None)
  3019. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id, baseline))
  3020. log_timing("Timelapse scan scheduled")
  3021. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  3022. # AMS sensor history recording
  3023. _ams_history_task: asyncio.Task | None = None
  3024. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  3025. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  3026. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  3027. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  3028. _ams_alarm_cooldown: dict[str, datetime] = {}
  3029. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  3030. async def record_ams_history():
  3031. """Background task to record AMS humidity and temperature data."""
  3032. logger = logging.getLogger(__name__)
  3033. # Wait a short time for MQTT connections to establish on startup
  3034. await asyncio.sleep(10)
  3035. while True:
  3036. try:
  3037. from backend.app.models.ams_history import AMSSensorHistory
  3038. from backend.app.models.printer import Printer
  3039. from backend.app.models.settings import Settings
  3040. async with async_session() as db:
  3041. # Get all active printers
  3042. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  3043. printers = result.scalars().all()
  3044. # Get alarm thresholds from settings
  3045. humidity_threshold = 60.0 # Default: fair threshold
  3046. temp_threshold = 35.0 # Default: fair threshold
  3047. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  3048. setting = result.scalar_one_or_none()
  3049. if setting:
  3050. try:
  3051. humidity_threshold = float(setting.value)
  3052. except (ValueError, TypeError):
  3053. pass # Keep default threshold if stored value is invalid
  3054. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  3055. setting = result.scalar_one_or_none()
  3056. if setting:
  3057. try:
  3058. temp_threshold = float(setting.value)
  3059. except (ValueError, TypeError):
  3060. pass # Keep default threshold if stored value is invalid
  3061. recorded_count = 0
  3062. for printer in printers:
  3063. # Get current state from printer manager
  3064. state = printer_manager.get_status(printer.id)
  3065. if not state or not state.connected or not state.raw_data:
  3066. continue # Skip disconnected printers - don't use stale data
  3067. raw_data = state.raw_data
  3068. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  3069. continue
  3070. # Record data for each AMS unit
  3071. for ams_data in raw_data["ams"]:
  3072. ams_id = int(ams_data.get("id", 0))
  3073. # Get humidity (prefer humidity_raw)
  3074. humidity_raw = ams_data.get("humidity_raw")
  3075. humidity_idx = ams_data.get("humidity")
  3076. humidity = None
  3077. if humidity_raw is not None:
  3078. try:
  3079. humidity = float(humidity_raw)
  3080. except (ValueError, TypeError):
  3081. pass # Skip unparseable humidity; will try fallback
  3082. if humidity is None and humidity_idx is not None:
  3083. try:
  3084. humidity = float(humidity_idx)
  3085. except (ValueError, TypeError):
  3086. pass # Skip unparseable humidity index value
  3087. # Get temperature
  3088. temperature = None
  3089. temp_str = ams_data.get("temp")
  3090. if temp_str is not None:
  3091. try:
  3092. temperature = float(temp_str)
  3093. except (ValueError, TypeError):
  3094. pass # Skip unparseable temperature value
  3095. # Skip if no data
  3096. if humidity is None and temperature is None:
  3097. continue
  3098. # Record the data point
  3099. history = AMSSensorHistory(
  3100. printer_id=printer.id,
  3101. ams_id=ams_id,
  3102. humidity=humidity,
  3103. humidity_raw=float(humidity_raw) if humidity_raw else None,
  3104. temperature=temperature,
  3105. )
  3106. db.add(history)
  3107. recorded_count += 1
  3108. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  3109. is_ams_ht = ams_id >= 128
  3110. if is_ams_ht:
  3111. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  3112. else:
  3113. ams_label = f"AMS-{chr(65 + ams_id)}"
  3114. # Check humidity alarm (only if above threshold)
  3115. if humidity is not None and humidity > humidity_threshold:
  3116. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  3117. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  3118. now = datetime.now(timezone.utc)
  3119. if (
  3120. last_alarm is None
  3121. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  3122. ):
  3123. _ams_alarm_cooldown[cooldown_key] = now
  3124. logger.info(
  3125. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  3126. )
  3127. try:
  3128. # Call different notification method based on AMS type
  3129. if is_ams_ht:
  3130. await notification_service.on_ams_ht_humidity_high(
  3131. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  3132. )
  3133. else:
  3134. await notification_service.on_ams_humidity_high(
  3135. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  3136. )
  3137. except Exception as e:
  3138. logger.warning("Failed to send humidity alarm: %s", e)
  3139. # Check temperature alarm (only if above threshold)
  3140. if temperature is not None and temperature > temp_threshold:
  3141. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  3142. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  3143. now = datetime.now(timezone.utc)
  3144. if (
  3145. last_alarm is None
  3146. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  3147. ):
  3148. _ams_alarm_cooldown[cooldown_key] = now
  3149. logger.info(
  3150. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  3151. )
  3152. try:
  3153. # Call different notification method based on AMS type
  3154. if is_ams_ht:
  3155. await notification_service.on_ams_ht_temperature_high(
  3156. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  3157. )
  3158. else:
  3159. await notification_service.on_ams_temperature_high(
  3160. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  3161. )
  3162. except Exception as e:
  3163. logger.warning("Failed to send temperature alarm: %s", e)
  3164. await db.commit()
  3165. if recorded_count > 0:
  3166. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  3167. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  3168. global _ams_cleanup_counter
  3169. _ams_cleanup_counter += 1
  3170. if _ams_cleanup_counter >= 288:
  3171. _ams_cleanup_counter = 0
  3172. # Get retention days from settings
  3173. from backend.app.models.settings import Settings
  3174. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  3175. setting = result.scalar_one_or_none()
  3176. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  3177. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  3178. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  3179. await db.commit()
  3180. if result.rowcount > 0:
  3181. logger.info(
  3182. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  3183. )
  3184. # Wait until next recording interval
  3185. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  3186. except asyncio.CancelledError:
  3187. break
  3188. except Exception as e:
  3189. logger.warning("AMS history recording failed: %s", e)
  3190. await asyncio.sleep(60) # Wait a bit before retrying
  3191. def start_ams_history_recording():
  3192. """Start the AMS history recording background task."""
  3193. global _ams_history_task
  3194. if _ams_history_task is None:
  3195. _ams_history_task = asyncio.create_task(record_ams_history())
  3196. logging.getLogger(__name__).info("AMS history recording started")
  3197. def stop_ams_history_recording():
  3198. """Stop the AMS history recording background task."""
  3199. global _ams_history_task
  3200. if _ams_history_task:
  3201. _ams_history_task.cancel()
  3202. _ams_history_task = None
  3203. logging.getLogger(__name__).info("AMS history recording stopped")
  3204. # Printer runtime tracking
  3205. _runtime_tracking_task: asyncio.Task | None = None
  3206. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  3207. async def track_printer_runtime():
  3208. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  3209. logger = logging.getLogger(__name__)
  3210. # Wait for MQTT connections to establish on startup
  3211. await asyncio.sleep(15)
  3212. while True:
  3213. try:
  3214. from backend.app.models.printer import Printer
  3215. # Fetch printer IDs in a short-lived read-only session
  3216. async with async_session() as db:
  3217. result = await db.execute(
  3218. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  3219. Printer.is_active.is_(True)
  3220. )
  3221. )
  3222. printer_rows = result.all()
  3223. now = datetime.now(timezone.utc)
  3224. updated_count = 0
  3225. # Update each printer in its own short session to minimise write-lock
  3226. # hold time and avoid blocking critical commits like queue status
  3227. # updates (#897).
  3228. for pid, pname, runtime_secs, last_update in printer_rows:
  3229. state = printer_manager.get_status(pid)
  3230. if not state:
  3231. logger.debug("[%s] Runtime tracking: no state available", pname)
  3232. continue
  3233. if not state.connected:
  3234. logger.debug("[%s] Runtime tracking: not connected", pname)
  3235. continue
  3236. needs_commit = False
  3237. new_runtime = runtime_secs
  3238. new_last_update = last_update
  3239. if state.state in ("RUNNING", "PAUSE"):
  3240. if last_update:
  3241. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  3242. elapsed = (now - lu).total_seconds()
  3243. if elapsed > 0:
  3244. new_runtime = runtime_secs + int(elapsed)
  3245. updated_count += 1
  3246. needs_commit = True
  3247. logger.debug(
  3248. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  3249. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  3250. )
  3251. else:
  3252. needs_commit = True
  3253. logger.debug("[%s] Runtime tracking: first active detection", pname)
  3254. new_last_update = now
  3255. else:
  3256. if last_update is not None:
  3257. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  3258. new_last_update = None
  3259. needs_commit = True
  3260. if needs_commit:
  3261. try:
  3262. async with async_session() as db:
  3263. result = await db.execute(select(Printer).where(Printer.id == pid))
  3264. printer = result.scalar_one_or_none()
  3265. if printer:
  3266. printer.runtime_seconds = new_runtime
  3267. printer.last_runtime_update = new_last_update
  3268. await db.commit()
  3269. except Exception as e:
  3270. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  3271. if updated_count > 0:
  3272. logger.debug("Updated runtime for %s printer(s)", updated_count)
  3273. except asyncio.CancelledError:
  3274. logger.info("Runtime tracking cancelled")
  3275. break
  3276. except Exception as e:
  3277. logger.warning("Runtime tracking failed: %s", e)
  3278. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  3279. def start_runtime_tracking():
  3280. """Start the printer runtime tracking background task."""
  3281. global _runtime_tracking_task
  3282. if _runtime_tracking_task is None:
  3283. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  3284. logging.getLogger(__name__).info("Printer runtime tracking started")
  3285. def stop_runtime_tracking():
  3286. """Stop the printer runtime tracking background task."""
  3287. global _runtime_tracking_task
  3288. if _runtime_tracking_task:
  3289. _runtime_tracking_task.cancel()
  3290. _runtime_tracking_task = None
  3291. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  3292. # SpoolBuddy device watchdog
  3293. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  3294. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  3295. async def _spoolbuddy_watchdog_loop():
  3296. """Periodic check for SpoolBuddy devices that have gone offline."""
  3297. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  3298. while True:
  3299. try:
  3300. await spoolbuddy_watchdog()
  3301. except asyncio.CancelledError:
  3302. break
  3303. except Exception as e:
  3304. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  3305. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  3306. def start_spoolbuddy_watchdog():
  3307. global _spoolbuddy_watchdog_task
  3308. if _spoolbuddy_watchdog_task is None:
  3309. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  3310. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  3311. def stop_spoolbuddy_watchdog():
  3312. global _spoolbuddy_watchdog_task
  3313. if _spoolbuddy_watchdog_task:
  3314. _spoolbuddy_watchdog_task.cancel()
  3315. _spoolbuddy_watchdog_task = None
  3316. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  3317. # Camera stream orphan cleanup
  3318. _camera_cleanup_task: asyncio.Task | None = None
  3319. CAMERA_CLEANUP_INTERVAL = 60
  3320. async def _camera_cleanup_loop():
  3321. """Periodically clean up orphaned ffmpeg processes."""
  3322. from backend.app.api.routes.camera import cleanup_orphaned_streams
  3323. while True:
  3324. try:
  3325. await cleanup_orphaned_streams()
  3326. except asyncio.CancelledError:
  3327. break
  3328. except Exception as e:
  3329. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  3330. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  3331. def start_camera_cleanup():
  3332. global _camera_cleanup_task
  3333. if _camera_cleanup_task is None:
  3334. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  3335. logging.getLogger(__name__).info("Camera stream cleanup started")
  3336. def stop_camera_cleanup():
  3337. global _camera_cleanup_task
  3338. if _camera_cleanup_task:
  3339. _camera_cleanup_task.cancel()
  3340. _camera_cleanup_task = None
  3341. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  3342. # ---------------------------------------------------------------------------
  3343. # Expected-print TTL eviction
  3344. # ---------------------------------------------------------------------------
  3345. def _evict_stale_expected_prints() -> None:
  3346. """Remove entries from _expected_prints / _expected_print_creators that are
  3347. older than _EXPECTED_PRINT_TTL_SECONDS.
  3348. This prevents unbounded growth when a print is registered (via
  3349. register_expected_print) but on_print_start never fires — e.g. because the
  3350. printer disconnects, the app restarts, or the print is started directly from
  3351. the printer panel without going through the queue.
  3352. """
  3353. # Use monotonic time so the TTL is unaffected by system clock adjustments
  3354. # (e.g. NTP sync, DST changes).
  3355. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  3356. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  3357. if not stale_keys:
  3358. return
  3359. evicted_archive_ids: set[int] = set()
  3360. for key in stale_keys:
  3361. archive_id = _expected_prints.pop(key, None)
  3362. if archive_id is not None:
  3363. evicted_archive_ids.add(archive_id)
  3364. _expected_print_creators.pop(key, None)
  3365. _expected_print_registered_at.pop(key, None)
  3366. # Also clean up _print_ams_mappings for archive_ids that have no remaining
  3367. # live keys in _expected_prints (i.e. all variants were just evicted).
  3368. live_archive_ids = set(_expected_prints.values())
  3369. for archive_id in evicted_archive_ids:
  3370. if archive_id not in live_archive_ids:
  3371. _print_ams_mappings.pop(archive_id, None)
  3372. logging.getLogger(__name__).info(
  3373. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  3374. )
  3375. async def _expected_prints_cleanup_loop() -> None:
  3376. """Background task: periodically evict stale expected-print entries."""
  3377. while True:
  3378. try:
  3379. _evict_stale_expected_prints()
  3380. except asyncio.CancelledError:
  3381. raise
  3382. except Exception as e:
  3383. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  3384. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  3385. def start_expected_prints_cleanup() -> None:
  3386. global _expected_prints_cleanup_task
  3387. if _expected_prints_cleanup_task is None:
  3388. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  3389. logging.getLogger(__name__).info("Expected prints cleanup started")
  3390. def stop_expected_prints_cleanup() -> None:
  3391. global _expected_prints_cleanup_task
  3392. if _expected_prints_cleanup_task:
  3393. _expected_prints_cleanup_task.cancel()
  3394. _expected_prints_cleanup_task = None
  3395. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  3396. # ---------------------------------------------------------------------------
  3397. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  3398. # ---------------------------------------------------------------------------
  3399. _auth_cleanup_task: asyncio.Task | None = None
  3400. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  3401. async def _run_auth_cleanup() -> None:
  3402. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  3403. from backend.app.core.database import async_session
  3404. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  3405. from backend.app.models.user_totp import UserTOTP
  3406. now = datetime.now(timezone.utc)
  3407. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  3408. try:
  3409. async with async_session() as db:
  3410. stale_cutoff = now - timedelta(hours=1)
  3411. result = await db.execute(
  3412. select(UserTOTP).where(
  3413. UserTOTP.is_enabled.is_(False),
  3414. UserTOTP.created_at < stale_cutoff,
  3415. )
  3416. )
  3417. stale_records = result.scalars().all()
  3418. if stale_records:
  3419. for rec in stale_records:
  3420. await db.delete(rec)
  3421. await db.commit()
  3422. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  3423. except Exception as e:
  3424. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  3425. # Remove expired revoked-JTI entries (they are no longer needed once the
  3426. # original token's exp has passed — the token would be rejected by JWT
  3427. # signature verification regardless).
  3428. try:
  3429. async with async_session() as db:
  3430. await db.execute(
  3431. delete(AuthEphemeralToken).where(
  3432. AuthEphemeralToken.token_type == "revoked_jti",
  3433. AuthEphemeralToken.expires_at < now,
  3434. )
  3435. )
  3436. await db.commit()
  3437. except Exception as e:
  3438. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  3439. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  3440. # Events outside this window can never affect rate-limit decisions — they only
  3441. # consume DB space. Use the same window constant as the rate limiter so the
  3442. # two are always in sync.
  3443. try:
  3444. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  3445. async with async_session() as db:
  3446. await db.execute(
  3447. delete(AuthRateLimitEvent).where(
  3448. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  3449. )
  3450. )
  3451. await db.commit()
  3452. except Exception as e:
  3453. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  3454. async def _auth_cleanup_loop() -> None:
  3455. """Periodic background task: run auth cleanup every hour."""
  3456. while True:
  3457. try:
  3458. await _run_auth_cleanup()
  3459. except asyncio.CancelledError:
  3460. break
  3461. except Exception as e:
  3462. logging.warning("Auth cleanup loop error: %s", e)
  3463. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  3464. def start_auth_cleanup() -> None:
  3465. global _auth_cleanup_task
  3466. if _auth_cleanup_task is None:
  3467. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  3468. logging.getLogger(__name__).info("Auth periodic cleanup started")
  3469. def stop_auth_cleanup() -> None:
  3470. global _auth_cleanup_task
  3471. if _auth_cleanup_task:
  3472. _auth_cleanup_task.cancel()
  3473. _auth_cleanup_task = None
  3474. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  3475. @asynccontextmanager
  3476. async def lifespan(app: FastAPI):
  3477. # Startup
  3478. await init_db()
  3479. # Register an app-scoped httpx client for Bambu Cloud services so
  3480. # per-request BambuCloudService instances reuse the same connection pool
  3481. # (important for routes like /cloud/filament-info that chain many
  3482. # get_setting_detail calls). The shared client stores no region/token
  3483. # state, so the per-request ownership pattern that fixed the region-bleed
  3484. # bug is preserved.
  3485. import httpx as _httpx
  3486. from backend.app.services.bambu_cloud import set_shared_http_client
  3487. from backend.app.services.makerworld import (
  3488. set_shared_http_client as set_shared_makerworld_http_client,
  3489. )
  3490. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  3491. set_shared_http_client(_shared_cloud_http_client)
  3492. # Reuse the same connection pool for MakerWorld — different host, same
  3493. # keep-alive pool saves a TLS handshake per request.
  3494. set_shared_makerworld_http_client(_shared_cloud_http_client)
  3495. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  3496. # This can happen when a print was cancelled mid-print on versions before this fix.
  3497. try:
  3498. async with async_session() as db:
  3499. from backend.app.models.print_queue import PrintQueueItem
  3500. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  3501. aborted_items = result.scalars().all()
  3502. if aborted_items:
  3503. for item in aborted_items:
  3504. item.status = "cancelled"
  3505. await db.commit()
  3506. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  3507. except Exception as e:
  3508. logging.warning("Failed to fix aborted queue items: %s", e)
  3509. # Restore debug logging state from previous session
  3510. await init_debug_logging()
  3511. # Set up printer manager callbacks
  3512. loop = asyncio.get_event_loop()
  3513. printer_manager.set_event_loop(loop)
  3514. printer_manager.set_status_change_callback(on_printer_status_change)
  3515. printer_manager.set_print_start_callback(on_print_start)
  3516. printer_manager.set_print_complete_callback(on_print_complete)
  3517. printer_manager.set_ams_change_callback(on_ams_change)
  3518. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  3519. await printer_manager.load_awaiting_plate_clear_from_db()
  3520. # Layer change callback for external camera timelapse
  3521. async def on_layer_change(printer_id: int, layer_num: int):
  3522. """Capture timelapse frame on layer change + first layer notification."""
  3523. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  3524. await tl_layer_change(printer_id, layer_num)
  3525. # First layer complete notification (layer_num >= 2 means layer 1 is done)
  3526. if 2 <= layer_num <= 5 and not _first_layer_notified.get(printer_id, False):
  3527. _first_layer_notified[printer_id] = True
  3528. try:
  3529. async with async_session() as db:
  3530. from backend.app.models.printer import Printer
  3531. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3532. printer = result.scalar_one_or_none()
  3533. if not printer:
  3534. return
  3535. printer_name = printer.name
  3536. client = printer_manager.get_client(printer_id)
  3537. state = client.state if client else None
  3538. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  3539. total_layers = state.total_layers if state else 0
  3540. image_data = await _capture_snapshot_for_notification(
  3541. printer_id, printer, logging.getLogger(__name__)
  3542. )
  3543. await notification_service.on_first_layer_complete(
  3544. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  3545. )
  3546. except Exception as e:
  3547. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  3548. printer_manager.set_layer_change_callback(on_layer_change)
  3549. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  3550. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  3551. waiter = _bed_cool_waiters.get(printer_id)
  3552. if not waiter:
  3553. return
  3554. threshold = waiter["threshold"]
  3555. if bed_temp > threshold:
  3556. return
  3557. # Bed is at or below threshold — fire notification and remove waiter
  3558. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  3559. if not waiter_info:
  3560. return # Another callback already handled it
  3561. bed_cool_logger = logging.getLogger(__name__)
  3562. bed_cool_logger.info(
  3563. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  3564. bed_temp,
  3565. printer_id,
  3566. threshold,
  3567. )
  3568. try:
  3569. printer_info = printer_manager.get_printer(printer_id)
  3570. p_name = printer_info.name if printer_info else "Unknown"
  3571. async with async_session() as db:
  3572. await notification_service.on_bed_cooled(
  3573. printer_id=printer_id,
  3574. printer_name=p_name,
  3575. bed_temp=bed_temp,
  3576. threshold=threshold,
  3577. filename=waiter_info["filename"],
  3578. db=db,
  3579. )
  3580. except Exception as e:
  3581. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  3582. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  3583. # Initialize MQTT relay from settings
  3584. async with async_session() as db:
  3585. from backend.app.api.routes.settings import get_setting
  3586. mqtt_settings = {
  3587. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  3588. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  3589. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  3590. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  3591. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  3592. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  3593. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  3594. }
  3595. await mqtt_relay.configure(mqtt_settings)
  3596. # Restore MQTT smart plug subscriptions
  3597. if mqtt_settings.get("mqtt_enabled"):
  3598. from backend.app.models.smart_plug import SmartPlug
  3599. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  3600. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  3601. mqtt_plugs = result.scalars().all()
  3602. restored = 0
  3603. for plug in mqtt_plugs:
  3604. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  3605. restored += 1
  3606. if restored:
  3607. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  3608. # Connect to all active printers
  3609. async with async_session() as db:
  3610. await init_printer_connections(db)
  3611. # Auto-connect to Spoolman if enabled
  3612. async with async_session() as db:
  3613. from backend.app.api.routes.settings import get_setting
  3614. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3615. spoolman_url = await get_setting(db, "spoolman_url")
  3616. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  3617. try:
  3618. client = await init_spoolman_client(spoolman_url)
  3619. if await client.health_check():
  3620. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  3621. # Ensure the 'tag' extra field exists for RFID/UUID storage
  3622. await client.ensure_tag_extra_field()
  3623. else:
  3624. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  3625. except Exception as e:
  3626. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  3627. # Start the print scheduler
  3628. asyncio.create_task(print_scheduler.run())
  3629. # Start background dispatch worker for send/start operations
  3630. await background_dispatch.start()
  3631. # Start the smart plug scheduler for time-based on/off
  3632. smart_plug_manager.start_scheduler()
  3633. # Resume any pending auto-offs that were interrupted by restart
  3634. await smart_plug_manager.resume_pending_auto_offs()
  3635. # Start the notification digest scheduler
  3636. notification_service.start_digest_scheduler()
  3637. # Start the GitHub backup scheduler
  3638. await github_backup_service.start_scheduler()
  3639. # Start the local backup scheduler
  3640. await local_backup_service.start_scheduler()
  3641. await obico_detection_service.start()
  3642. # Start the library trash sweeper (#1008)
  3643. await library_trash_service.start_scheduler()
  3644. # Start the archive auto-purge sweeper (#1008 follow-up)
  3645. await archive_purge_service.start_scheduler()
  3646. # Start AMS history recording
  3647. start_ams_history_recording()
  3648. # Start printer runtime tracking
  3649. start_runtime_tracking()
  3650. # Start SpoolBuddy device watchdog
  3651. start_spoolbuddy_watchdog()
  3652. # Start camera stream orphan cleanup
  3653. start_camera_cleanup()
  3654. # Start expected-print TTL eviction (prevents memory leak when prints are
  3655. # registered but on_print_start never fires)
  3656. start_expected_prints_cleanup()
  3657. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  3658. start_auth_cleanup()
  3659. # Initialize virtual printer manager and sync from DB
  3660. from backend.app.services.virtual_printer import virtual_printer_manager
  3661. virtual_printer_manager.set_session_factory(async_session)
  3662. try:
  3663. await virtual_printer_manager.sync_from_db()
  3664. logging.info("Virtual printer manager synced from database")
  3665. except Exception as e:
  3666. logging.warning("Failed to sync virtual printers: %s", e)
  3667. yield
  3668. # Shutdown
  3669. print_scheduler.stop()
  3670. await background_dispatch.stop()
  3671. smart_plug_manager.stop_scheduler()
  3672. notification_service.stop_digest_scheduler()
  3673. github_backup_service.stop_scheduler()
  3674. local_backup_service.stop_scheduler()
  3675. library_trash_service.stop_scheduler()
  3676. archive_purge_service.stop_scheduler()
  3677. obico_detection_service.stop()
  3678. stop_ams_history_recording()
  3679. stop_runtime_tracking()
  3680. stop_spoolbuddy_watchdog()
  3681. stop_camera_cleanup()
  3682. stop_expected_prints_cleanup()
  3683. stop_auth_cleanup()
  3684. printer_manager.disconnect_all()
  3685. await close_spoolman_client()
  3686. # Stop all virtual printer services
  3687. await virtual_printer_manager.stop_all()
  3688. await mqtt_smart_plug_service.disconnect(timeout=2)
  3689. await mqtt_relay.disconnect(timeout=2)
  3690. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  3691. set_shared_http_client(None)
  3692. set_shared_makerworld_http_client(None)
  3693. await _shared_cloud_http_client.aclose()
  3694. # Checkpoint WAL (SQLite only) and close all database connections
  3695. from backend.app.core.db_dialect import is_sqlite
  3696. if is_sqlite():
  3697. try:
  3698. async with engine.begin() as conn:
  3699. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  3700. logging.info("WAL checkpoint completed")
  3701. except Exception as e:
  3702. logging.warning("WAL checkpoint failed: %s", e)
  3703. await engine.dispose()
  3704. app = FastAPI(
  3705. title=app_settings.app_name,
  3706. description="Archive and manage Bambu Lab 3MF files",
  3707. version=APP_VERSION,
  3708. lifespan=lifespan,
  3709. )
  3710. # =============================================================================
  3711. # Authentication Middleware - Secures ALL API routes by default
  3712. # =============================================================================
  3713. # Public routes that don't require authentication even when auth is enabled
  3714. PUBLIC_API_ROUTES = {
  3715. # Auth routes needed before/during login
  3716. "/api/v1/auth/status",
  3717. "/api/v1/auth/login",
  3718. "/api/v1/auth/setup", # Needed for initial setup and recovery
  3719. # Advanced auth status needed for login page
  3720. "/api/v1/auth/advanced-auth/status",
  3721. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  3722. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  3723. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  3724. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  3725. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  3726. # OIDC routes that must be reachable without a JWT
  3727. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  3728. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  3729. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  3730. # Version check for updates (no sensitive data)
  3731. "/api/v1/updates/version",
  3732. # Metrics endpoint handles its own prometheus_token authentication
  3733. "/api/v1/metrics",
  3734. }
  3735. # Route prefixes that are public (for routes with dynamic segments)
  3736. PUBLIC_API_PREFIXES = [
  3737. # WebSocket connections handle their own auth
  3738. "/api/v1/ws",
  3739. # OIDC authorize redirects — include provider_id in path
  3740. "/api/v1/auth/oidc/authorize/",
  3741. ]
  3742. # Route patterns that are public (read-only display data)
  3743. # These are checked with "in path" - needed because browsers load images/videos
  3744. # via <img src> and <video src> which don't include Authorization headers
  3745. PUBLIC_API_PATTERNS = [
  3746. # Thumbnails
  3747. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  3748. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  3749. # Images and media
  3750. "/photos/", # /archives/{id}/photos/{filename}
  3751. "/project-image/", # /archives/{id}/project-image/{path}
  3752. "/qrcode", # /archives/{id}/qrcode
  3753. "/timelapse", # /archives/{id}/timelapse (video)
  3754. "/cover", # /printers/{id}/cover
  3755. "/icon", # /external-links/{id}/icon
  3756. # Camera (streams loaded via <img> tag)
  3757. "/camera/stream", # /printers/{id}/camera/stream
  3758. "/camera/snapshot", # /printers/{id}/camera/snapshot
  3759. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  3760. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  3761. # download token in the URL path instead.
  3762. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  3763. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  3764. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  3765. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  3766. ]
  3767. @app.middleware("http")
  3768. async def security_headers_middleware(request, call_next):
  3769. """Add standard HTTP security headers to every response."""
  3770. response = await call_next(request)
  3771. response.headers["X-Content-Type-Options"] = "nosniff"
  3772. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  3773. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  3774. # Content-Security-Policy for the React SPA.
  3775. # Notes:
  3776. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  3777. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  3778. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  3779. # - media-src blob:: timelapse video player uses Blob URLs.
  3780. # - font-src data:: some icon fonts are embedded as data URIs.
  3781. if request.url.path.startswith("/gcode-viewer"):
  3782. # The gcode viewer is embedded in an iframe served by this same origin,
  3783. # so frame-ancestors must allow 'self'. prettygcode.js also uses eval()
  3784. # internally, so script-src needs 'unsafe-eval'.
  3785. response.headers["Content-Security-Policy"] = (
  3786. "default-src 'self'; "
  3787. "script-src 'self' 'unsafe-eval'; "
  3788. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
  3789. "img-src 'self' data: blob:; "
  3790. "media-src 'self' blob:; "
  3791. "connect-src 'self' ws: wss:; "
  3792. "font-src 'self' data: https://fonts.gstatic.com; "
  3793. "object-src 'none'; "
  3794. "base-uri 'self'; "
  3795. "frame-src 'self' http: https:; "
  3796. "frame-ancestors 'self';"
  3797. )
  3798. else:
  3799. response.headers["Content-Security-Policy"] = (
  3800. "default-src 'self'; "
  3801. "script-src 'self'; "
  3802. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
  3803. "img-src 'self' data: blob:; "
  3804. "media-src 'self' blob:; "
  3805. "connect-src 'self' ws: wss:; "
  3806. "font-src 'self' data: https://fonts.gstatic.com; "
  3807. "object-src 'none'; "
  3808. "base-uri 'self'; "
  3809. "frame-src 'self' http: https:; "
  3810. "frame-ancestors 'none';"
  3811. )
  3812. if request.url.scheme == "https":
  3813. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  3814. return response
  3815. @app.middleware("http")
  3816. async def auth_middleware(request, call_next):
  3817. """Enforce authentication on all API routes when auth is enabled.
  3818. This middleware provides defense-in-depth by checking auth at the API gateway level,
  3819. regardless of whether individual routes have auth dependencies.
  3820. """
  3821. from starlette.responses import JSONResponse
  3822. path = request.url.path
  3823. # Only apply to API routes
  3824. if not path.startswith("/api/"):
  3825. return await call_next(request)
  3826. # Allow public routes
  3827. if path in PUBLIC_API_ROUTES:
  3828. return await call_next(request)
  3829. # Allow public prefixes
  3830. for prefix in PUBLIC_API_PREFIXES:
  3831. if path.startswith(prefix):
  3832. return await call_next(request)
  3833. # Allow public patterns (read-only display data like thumbnails)
  3834. for pattern in PUBLIC_API_PATTERNS:
  3835. if pattern in path:
  3836. return await call_next(request)
  3837. # Check if auth is enabled
  3838. try:
  3839. async with async_session() as db:
  3840. from backend.app.core.auth import is_auth_enabled
  3841. auth_enabled = await is_auth_enabled(db)
  3842. if not auth_enabled:
  3843. # Auth disabled, allow all requests
  3844. return await call_next(request)
  3845. except Exception:
  3846. # If we can't check auth status, allow request (fail open for DB issues)
  3847. return await call_next(request)
  3848. # Auth is enabled - require valid token
  3849. auth_header = request.headers.get("Authorization")
  3850. x_api_key = request.headers.get("X-API-Key")
  3851. # Check for API key auth first
  3852. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  3853. # API key authentication - let the request through to be validated by route handler
  3854. # API keys are validated per-route since they have different permission levels
  3855. return await call_next(request)
  3856. # Check for JWT auth
  3857. if not auth_header or not auth_header.startswith("Bearer "):
  3858. return JSONResponse(
  3859. status_code=401,
  3860. content={"detail": "Authentication required"},
  3861. headers={"WWW-Authenticate": "Bearer"},
  3862. )
  3863. # Validate JWT token
  3864. import jwt
  3865. try:
  3866. from backend.app.core.auth import (
  3867. ALGORITHM,
  3868. SECRET_KEY,
  3869. _is_token_fresh,
  3870. get_user_by_username,
  3871. is_jti_revoked,
  3872. )
  3873. token = auth_header.replace("Bearer ", "")
  3874. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  3875. username = payload.get("sub")
  3876. if not username:
  3877. raise ValueError("No username in token")
  3878. jti = payload.get("jti")
  3879. if not jti:
  3880. raise ValueError("No jti in token")
  3881. iat = payload.get("iat")
  3882. # Reject revoked tokens (defense-in-depth gateway check)
  3883. if await is_jti_revoked(jti):
  3884. return JSONResponse(
  3885. status_code=401,
  3886. content={"detail": "Token has been revoked"},
  3887. headers={"WWW-Authenticate": "Bearer"},
  3888. )
  3889. # Verify user exists, is active, and token is still fresh (L-R8-A)
  3890. async with async_session() as db:
  3891. user = await get_user_by_username(db, username)
  3892. if not user or not user.is_active:
  3893. return JSONResponse(
  3894. status_code=401,
  3895. content={"detail": "User not found or inactive"},
  3896. headers={"WWW-Authenticate": "Bearer"},
  3897. )
  3898. if not _is_token_fresh(iat, user):
  3899. return JSONResponse(
  3900. status_code=401,
  3901. content={"detail": "Token no longer valid"},
  3902. headers={"WWW-Authenticate": "Bearer"},
  3903. )
  3904. except jwt.ExpiredSignatureError:
  3905. return JSONResponse(
  3906. status_code=401,
  3907. content={"detail": "Token has expired"},
  3908. headers={"WWW-Authenticate": "Bearer"},
  3909. )
  3910. except (jwt.InvalidTokenError, ValueError, Exception):
  3911. return JSONResponse(
  3912. status_code=401,
  3913. content={"detail": "Invalid token"},
  3914. headers={"WWW-Authenticate": "Bearer"},
  3915. )
  3916. return await call_next(request)
  3917. # API routes
  3918. app.include_router(auth.router, prefix=app_settings.api_prefix)
  3919. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  3920. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  3921. app.include_router(users.router, prefix=app_settings.api_prefix)
  3922. app.include_router(groups.router, prefix=app_settings.api_prefix)
  3923. app.include_router(printers.router, prefix=app_settings.api_prefix)
  3924. app.include_router(archives.router, prefix=app_settings.api_prefix)
  3925. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  3926. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  3927. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  3928. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  3929. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  3930. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  3931. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  3932. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  3933. app.include_router(background_dispatch_routes.router, prefix=app_settings.api_prefix)
  3934. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  3935. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  3936. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  3937. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  3938. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  3939. app.include_router(updates.router, prefix=app_settings.api_prefix)
  3940. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  3941. app.include_router(camera.router, prefix=app_settings.api_prefix)
  3942. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  3943. app.include_router(projects.router, prefix=app_settings.api_prefix)
  3944. app.include_router(library.router, prefix=app_settings.api_prefix)
  3945. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  3946. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  3947. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  3948. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  3949. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  3950. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  3951. app.include_router(system.router, prefix=app_settings.api_prefix)
  3952. app.include_router(support.router, prefix=app_settings.api_prefix)
  3953. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  3954. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  3955. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  3956. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  3957. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  3958. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  3959. app.include_router(obico.router, prefix=app_settings.api_prefix)
  3960. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  3961. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  3962. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  3963. # Serve static files (React build)
  3964. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  3965. app.mount(
  3966. "/assets",
  3967. StaticFiles(directory=app_settings.static_dir / "assets"),
  3968. name="assets",
  3969. )
  3970. if (app_settings.static_dir / "img").exists():
  3971. app.mount(
  3972. "/img",
  3973. StaticFiles(directory=app_settings.static_dir / "img"),
  3974. name="img",
  3975. )
  3976. if (app_settings.static_dir / "icons").exists():
  3977. app.mount(
  3978. "/icons",
  3979. StaticFiles(directory=app_settings.static_dir / "icons"),
  3980. name="icons",
  3981. )
  3982. @app.get("/")
  3983. async def serve_frontend():
  3984. """Serve the React frontend."""
  3985. index_file = app_settings.static_dir / "index.html"
  3986. if index_file.exists():
  3987. return FileResponse(index_file)
  3988. return {
  3989. "message": "Bambuddy API",
  3990. "docs": "/docs",
  3991. "frontend": "Build and place React app in /static directory",
  3992. }
  3993. @app.get("/health")
  3994. async def health_check():
  3995. """Health check endpoint."""
  3996. return {"status": "healthy"}
  3997. @app.get("/manifest.json")
  3998. async def serve_manifest():
  3999. """Serve PWA manifest."""
  4000. manifest_file = app_settings.static_dir / "manifest.json"
  4001. if manifest_file.exists():
  4002. return FileResponse(manifest_file, media_type="application/manifest+json")
  4003. return {"error": "Manifest not found"}
  4004. @app.get("/sw.js")
  4005. async def serve_service_worker():
  4006. """Serve service worker."""
  4007. sw_file = app_settings.static_dir / "sw.js"
  4008. if sw_file.exists():
  4009. return FileResponse(
  4010. sw_file,
  4011. media_type="application/javascript",
  4012. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  4013. )
  4014. return {"error": "Service worker not found"}
  4015. @app.get("/sw-register.js")
  4016. async def serve_sw_register():
  4017. """Serve the service-worker registration bootstrap script.
  4018. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  4019. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  4020. """
  4021. reg_file = app_settings.static_dir / "sw-register.js"
  4022. if reg_file.exists():
  4023. return FileResponse(reg_file, media_type="application/javascript")
  4024. return {"error": "sw-register.js not found"}
  4025. # ── GCode viewer static files ────────────────────────────────────────────────
  4026. # Served via explicit routes so ordering is guaranteed (app.mount() loses
  4027. # to the /{full_path:path} catch-all in some Starlette versions).
  4028. _gcode_viewer_dir = (app_settings.static_dir.parent / "gcode_viewer").resolve()
  4029. def _gcode_viewer_response(rel: str) -> FileResponse:
  4030. from fastapi import HTTPException as _HTTPException
  4031. safe = (_gcode_viewer_dir / rel).resolve()
  4032. if not safe.is_relative_to(_gcode_viewer_dir):
  4033. raise _HTTPException(status_code=403)
  4034. if safe.is_file():
  4035. mt, _ = _mimetypes.guess_type(str(safe))
  4036. return FileResponse(str(safe), media_type=mt or "application/octet-stream")
  4037. raise _HTTPException(status_code=404)
  4038. @app.get("/gcode-viewer/")
  4039. async def serve_gcode_viewer_index() -> FileResponse:
  4040. """Raw PrettyGCode viewer for the iframe. The bare ``/gcode-viewer``
  4041. (no trailing slash) intentionally falls through to the SPA catch-all so a
  4042. full-page reload re-enters the React layout instead of serving the iframe
  4043. contents standalone."""
  4044. return _gcode_viewer_response("index.html")
  4045. @app.get("/gcode-viewer/{file_path:path}")
  4046. async def serve_gcode_viewer_file(file_path: str) -> FileResponse:
  4047. return _gcode_viewer_response(file_path)
  4048. # Catch-all route for React Router (must be last)
  4049. @app.get("/{full_path:path}")
  4050. async def serve_spa(full_path: str):
  4051. """Serve React app for client-side routing."""
  4052. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  4053. if full_path.startswith("api/"):
  4054. from fastapi import HTTPException
  4055. raise HTTPException(status_code=404, detail="Not found")
  4056. index_file = app_settings.static_dir / "index.html"
  4057. if index_file.exists():
  4058. return FileResponse(index_file)
  4059. return {"error": "Frontend not built"}