bambu_mqtt.py 293 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966
  1. """Bambu Lab MQTT communication service.
  2. IMPORTANT: Always use qos=1 for all MQTT publish calls!
  3. The printer ignores qos=0 messages when busy broadcasting status updates.
  4. Using qos=1 ensures the printer acknowledges and processes our commands immediately.
  5. This was discovered when K-profile requests with qos=0 took 20-30 seconds,
  6. but with qos=1 they respond instantly.
  7. """
  8. import asyncio
  9. import json
  10. import logging
  11. import os
  12. import ssl
  13. import threading
  14. import time
  15. from collections import deque
  16. from collections.abc import Callable
  17. from dataclasses import dataclass, field
  18. from datetime import datetime, timezone
  19. import paho.mqtt.client as mqtt
  20. from backend.app.services.hms_actions import HMSAction, get_actions_for_error_code
  21. logger = logging.getLogger(__name__)
  22. # AMS module name prefixes used in get_version responses.
  23. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  24. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  25. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  26. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  27. _AMS_MODULE_PREFIXES = ("ams/", "n3f/", "n3s/")
  28. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  29. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  30. OrcaSlicer reads bit 18 of the hex string via
  31. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  32. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  33. that doesn't yield a clean integer so downstream consumers preserve today's
  34. behaviour rather than treating "absent" as "OFF".
  35. """
  36. if not isinstance(cfg_raw, str) or not cfg_raw:
  37. return None
  38. try:
  39. return bool((int(cfg_raw, 16) >> 18) & 1)
  40. except ValueError:
  41. return None
  42. def apply_tray_exist_bits(
  43. units: list,
  44. tray_exist_bits_str: str | int | None,
  45. *,
  46. power_on_flag: bool = True,
  47. log_label: str | None = None,
  48. annotate_exists: bool = False,
  49. ) -> int:
  50. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  51. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  52. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  53. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  54. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  55. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  56. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  57. instead of guessing from payload shape (#1322, #147).
  58. Two callers share this helper to keep their views consistent:
  59. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  60. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  61. facing push_status (#1726 — without this the VP would forward stale
  62. per-tray fields for empty slots, and BambuStudio's Sync would render
  63. phantom loaded slots).
  64. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  65. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  66. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  67. so spool removal is detected without requiring a manual reconnect.
  68. AMS-HT units (``id >= 128``) use a separate addressing scheme and are
  69. skipped here.
  70. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  71. way). Ints are tolerated for defensive symmetry but typically not seen
  72. on the wire. ``None`` / empty / unparseable → no-op.
  73. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  74. every processed slot. This is firmware's authoritative "spool physically
  75. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  76. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  77. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  78. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  79. leaves it False so the ``exists`` key never reaches the slicer wire format.
  80. Mutates ``units`` in place. Returns the number of slots cleared.
  81. """
  82. if not tray_exist_bits_str:
  83. return 0
  84. try:
  85. if isinstance(tray_exist_bits_str, int):
  86. tray_exist_bits = tray_exist_bits_str
  87. else:
  88. tray_exist_bits = int(tray_exist_bits_str, 16)
  89. except (ValueError, TypeError):
  90. return 0
  91. if tray_exist_bits == 0 and not power_on_flag:
  92. return 0
  93. if not isinstance(units, list):
  94. return 0
  95. cleared = 0
  96. for ams_unit in units:
  97. if not isinstance(ams_unit, dict):
  98. continue
  99. ams_id_raw = ams_unit.get("id")
  100. if ams_id_raw is None:
  101. continue
  102. try:
  103. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  104. except (ValueError, TypeError):
  105. continue
  106. if not isinstance(ams_id, int) or ams_id >= 128:
  107. # Skip AMS-HT (id >= 128) — separate addressing scheme.
  108. continue
  109. for tray in ams_unit.get("tray", []):
  110. if not isinstance(tray, dict):
  111. continue
  112. tray_id_raw = tray.get("id")
  113. if tray_id_raw is None:
  114. continue
  115. try:
  116. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  117. except (ValueError, TypeError):
  118. continue
  119. if not isinstance(tray_id, int):
  120. continue
  121. global_bit = ams_id * 4 + tray_id
  122. slot_exists = (tray_exist_bits >> global_bit) & 1
  123. if annotate_exists:
  124. tray["exists"] = bool(slot_exists)
  125. if slot_exists:
  126. continue
  127. tray["state"] = 9
  128. if tray.get("tray_type"):
  129. if log_label:
  130. logger.debug(
  131. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  132. f"(tray_exist_bits bit {global_bit} = 0)"
  133. )
  134. tray["tray_type"] = ""
  135. tray["tray_sub_brands"] = ""
  136. tray["tray_color"] = ""
  137. tray["tray_id_name"] = ""
  138. tray["tag_uid"] = "0000000000000000"
  139. tray["tray_uuid"] = "00000000000000000000000000000000"
  140. tray["tray_info_idx"] = ""
  141. tray["remain"] = 0
  142. cleared += 1
  143. return cleared
  144. @dataclass
  145. class MQTTLogEntry:
  146. """Log entry for MQTT message debugging."""
  147. timestamp: str
  148. topic: str
  149. direction: str # "in" or "out"
  150. payload: dict
  151. @dataclass
  152. class HMSError:
  153. """Health Management System error from printer."""
  154. code: str
  155. attr: int # Attribute value for constructing wiki URL
  156. module: int
  157. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  158. message: str = ""
  159. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  160. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  161. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  162. # HMSError without explicitly passing actions can't silently land None on the schema
  163. # boundary and raise ValidationError at routes/printers.py response time.
  164. actions: list[str] = field(default_factory=list)
  165. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  166. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  167. job_id: str | None = None
  168. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  169. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  170. # 32-bit `print_error` path. The frontend echoes this back to
  171. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  172. # used to send caused the firmware to silently reject HMS commands on H2C
  173. # (#1830) and on `hms[]`-sourced faults generally.
  174. full_code: str = ""
  175. # HMS short codes the firmware emits during normal user-cancel sequences.
  176. # These aren't faults — they're status echoes that confirm the cancel happened.
  177. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  178. # so they don't drive the printer card's "X problem" badge, the red pip, or
  179. # any other consumer that treats hms_errors as the active-fault list.
  180. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  181. {
  182. "0300_400C", # "The task was canceled."
  183. "0500_400E", # "Printing was cancelled."
  184. }
  185. )
  186. @dataclass
  187. class KProfile:
  188. """Pressure advance (K) calibration profile from printer."""
  189. slot_id: int
  190. extruder_id: int
  191. nozzle_id: str
  192. nozzle_diameter: str
  193. filament_id: str
  194. name: str
  195. k_value: str
  196. n_coef: str = "0.000000"
  197. ams_id: int = 0
  198. tray_id: int = -1
  199. setting_id: str | None = None
  200. @dataclass
  201. class NozzleInfo:
  202. """Nozzle hardware configuration."""
  203. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  204. nozzle_diameter: str = "" # e.g., "0.4"
  205. @dataclass
  206. class FilaSwitchState:
  207. """Filament Track Switch (FTS) accessory state.
  208. The FTS is an external accessory that mediates filament routing between an
  209. AMS and the printer's extruders. When installed, the AMS no longer has a
  210. fixed extruder assignment — any slot can be routed to any extruder via the
  211. track switch. Detected from print.device.fila_switch in MQTT.
  212. """
  213. installed: bool = False
  214. # in[track] = currently loaded slot for that track (-1 = empty). The slot
  215. # value is reported as observed in MQTT (treated as a global tray ID).
  216. in_slots: list[int] = field(default_factory=list)
  217. # out[track] = extruder this track terminates at (0 = right/main, 1 = left)
  218. out_extruders: list[int] = field(default_factory=list)
  219. stat: int = 0 # status flags (0 = idle)
  220. info: int = 0 # info flags
  221. @dataclass
  222. class PrintOptions:
  223. """AI detection and print options from xcam data."""
  224. # Core AI detectors
  225. spaghetti_detector: bool = False
  226. print_halt: bool = False
  227. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  228. first_layer_inspector: bool = False
  229. printing_monitor: bool = False # AI print quality monitoring
  230. buildplate_marker_detector: bool = False
  231. allow_skip_parts: bool = False
  232. # Additional AI detectors - decoded from cfg bitmask
  233. nozzle_clumping_detector: bool = True
  234. nozzle_clumping_sensitivity: str = "medium"
  235. pileup_detector: bool = True
  236. pileup_sensitivity: str = "medium"
  237. airprint_detector: bool = True
  238. airprint_sensitivity: str = "medium"
  239. auto_recovery_step_loss: bool = True # Uses print.print_option command
  240. filament_tangle_detect: bool = False
  241. @dataclass
  242. class PrinterState:
  243. connected: bool = False
  244. state: str = "unknown"
  245. current_print: str | None = None
  246. subtask_name: str | None = None
  247. progress: float = 0.0
  248. remaining_time: int = 0
  249. layer_num: int = 0
  250. total_layers: int = 0
  251. temperatures: dict = field(default_factory=dict)
  252. raw_data: dict = field(default_factory=dict)
  253. gcode_file: str | None = None
  254. subtask_id: str | None = None
  255. hms_errors: list = field(default_factory=list) # List of HMSError
  256. kprofiles: list = field(default_factory=list) # List of KProfile
  257. sdcard: bool = False # SD card inserted
  258. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  259. timelapse: bool = False # Timelapse recording active
  260. ipcam: bool = False # Live view / camera streaming enabled
  261. wifi_signal: int | None = None # WiFi signal strength in dBm
  262. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  263. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  264. # Nozzle hardware info (for dual nozzle printers, index 0 = left, 1 = right)
  265. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  266. # AI detection and print options
  267. print_options: PrintOptions = field(default_factory=PrintOptions)
  268. # Calibration stage tracking (from stg_cur and stg fields)
  269. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  270. stg: list = field(default_factory=list) # List of stages to execute
  271. # Air conditioning mode (0=cooling, 1=heating)
  272. airduct_mode: int = 0
  273. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  274. speed_level: int = 2
  275. # Chamber light on/off
  276. chamber_light: bool = False
  277. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  278. active_extruder: int = 0
  279. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  280. tray_now: int = 255
  281. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  282. # tray_tar = the slot the paused/loading print now expects
  283. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  284. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  285. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  286. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  287. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  288. tray_tar: int = 255
  289. tray_pre: int = 255
  290. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  291. last_loaded_tray: int = -1
  292. # Pending load target - used to track what tray we're loading for H2D disambiguation
  293. pending_tray_target: int | None = None
  294. # AMS status for filament change tracking (from print.ams.ams_status field)
  295. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  296. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  297. ams_status: int = 0
  298. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  299. ams_status_sub: int = 0 # ams_status & 0xFF
  300. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  301. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  302. mc_print_sub_stage: int = 0
  303. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  304. ams_mapping: list = field(default_factory=list)
  305. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  306. ams_extruder_map: dict = field(default_factory=dict)
  307. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  308. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  309. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  310. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  311. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  312. # regex used to derive the plate number from the path always falls back to
  313. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  314. # Bambuddy dispatches the print itself we know the plate authoritatively;
  315. # we record it here and prefer it over the gcode_file regex. The subtask
  316. # field guards against staleness: if the printer is currently running a
  317. # different subtask (e.g. a Studio-direct dispatch), these values are
  318. # ignored. Cleared on disconnect.
  319. dispatched_plate_id: int | None = None
  320. dispatched_subtask: str | None = None
  321. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  322. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  323. h2d_extruder_snow: dict = field(default_factory=dict)
  324. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  325. nozzle_rack: list = field(default_factory=list)
  326. # Timestamp of last AMS data update (for RFID refresh detection)
  327. last_ams_update: float = 0.0
  328. # Printable objects for skip object functionality: {identify_id: object_name}
  329. printable_objects: dict = field(default_factory=dict)
  330. # Objects that have been skipped during the current print
  331. skipped_objects: list = field(default_factory=list)
  332. # Fan speeds (0-100 percentage, None if not available for this model)
  333. cooling_fan_speed: int | None = None # Part cooling fan
  334. big_fan1_speed: int | None = None # Auxiliary fan
  335. big_fan2_speed: int | None = None # Chamber/exhaust fan
  336. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  337. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  338. # Used by usage tracker to split filament weight on mid-print tray switch
  339. tray_change_log: list = field(default_factory=list)
  340. # Firmware version info (from info.module[name="ota"].sw_ver)
  341. firmware_version: str | None = None
  342. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  343. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  344. developer_mode: bool | None = None
  345. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  346. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  347. # which uses the old protocol path; field not yet found). Consumers must treat
  348. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  349. ams_filament_backup: bool | None = None
  350. # Stage name mapping from BambuStudio DeviceManager.cpp
  351. STAGE_NAMES = {
  352. 0: "Printing",
  353. 1: "Auto bed leveling",
  354. 2: "Heatbed preheating",
  355. 3: "Vibration compensation",
  356. 4: "Changing filament",
  357. 5: "M400 pause",
  358. 6: "Paused (filament ran out)",
  359. 7: "Heating nozzle",
  360. 8: "Calibrating dynamic flow",
  361. 9: "Scanning bed surface",
  362. 10: "Inspecting first layer",
  363. 11: "Identifying build plate type",
  364. 12: "Calibrating Micro Lidar",
  365. 13: "Homing toolhead",
  366. 14: "Cleaning nozzle tip",
  367. 15: "Checking extruder temperature",
  368. 16: "Paused by the user",
  369. 17: "Pause (front cover fall off)",
  370. 18: "Calibrating the micro lidar",
  371. 19: "Calibrating flow ratio",
  372. 20: "Pause (nozzle temperature malfunction)",
  373. 21: "Pause (heatbed temperature malfunction)",
  374. 22: "Filament unloading",
  375. 23: "Pause (step loss)",
  376. 24: "Filament loading",
  377. 25: "Motor noise cancellation",
  378. 26: "Pause (AMS offline)",
  379. 27: "Pause (low speed of the heatbreak fan)",
  380. 28: "Pause (chamber temperature control problem)",
  381. 29: "Cooling chamber",
  382. 30: "Pause (Gcode inserted by user)",
  383. 31: "Motor noise showoff",
  384. 32: "Pause (nozzle clumping)",
  385. 33: "Pause (cutter error)",
  386. 34: "Pause (first layer error)",
  387. 35: "Pause (nozzle clog)",
  388. 36: "Measuring motion precision",
  389. 37: "Enhancing motion precision",
  390. 38: "Measure motion accuracy",
  391. 39: "Nozzle offset calibration",
  392. 40: "High temperature auto bed leveling",
  393. 41: "Auto Check: Quick Release Lever",
  394. 42: "Auto Check: Door and Upper Cover",
  395. 43: "Laser Calibration",
  396. 44: "Auto Check: Platform",
  397. 45: "Confirming BirdsEye Camera location",
  398. 46: "Calibrating BirdsEye Camera",
  399. 47: "Auto bed leveling - phase 1",
  400. 48: "Auto bed leveling - phase 2",
  401. 49: "Heating chamber",
  402. 50: "Cooling heatbed",
  403. 51: "Printing calibration lines",
  404. 52: "Auto Check: Material",
  405. 53: "Live View Camera Calibration",
  406. 54: "Waiting for heatbed temperature",
  407. 55: "Auto Check: Material Position",
  408. 56: "Cutting Module Offset Calibration",
  409. 57: "Measuring Surface",
  410. 58: "Thermal Preconditioning",
  411. 59: "Homing Blade Holder",
  412. 60: "Calibrating Camera Offset",
  413. 61: "Calibrating Blade Holder Position",
  414. 62: "Hotend Pick and Place Test",
  415. 63: "Waiting for Chamber temperature",
  416. 64: "Preparing Hotend",
  417. 65: "Calibrating nozzle clumping detection",
  418. 66: "Purifying the chamber air",
  419. 74: "Preparing", # Seen on H2D during print preparation
  420. 77: "Preparing AMS",
  421. }
  422. def get_stage_name(stage: int) -> str:
  423. """Get human-readable stage name from stage number."""
  424. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  425. class BambuMQTTClient:
  426. """MQTT client for Bambu Lab printer communication."""
  427. MQTT_PORT = 8883
  428. # Class-level cache: serial_number -> False when request topic is known unsupported.
  429. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  430. _request_topic_cache: dict[str, bool] = {}
  431. # Counter for generating unique MQTT client IDs across instances.
  432. _client_instance_counter: int = 0
  433. def __init__(
  434. self,
  435. ip_address: str,
  436. serial_number: str,
  437. access_code: str,
  438. model: str | None = None,
  439. on_state_change: Callable[[PrinterState], None] | None = None,
  440. on_print_start: Callable[[dict], None] | None = None,
  441. on_print_complete: Callable[[dict], None] | None = None,
  442. on_ams_change: Callable[[list], None] | None = None,
  443. on_layer_change: Callable[[int], None] | None = None,
  444. on_bed_temp_update: Callable[[float], None] | None = None,
  445. on_drying_complete: Callable[[int], None] | None = None,
  446. on_print_running_observed: Callable[[dict], None] | None = None,
  447. on_finish_photo_moment: Callable[[dict], None] | None = None,
  448. ):
  449. self.ip_address = ip_address
  450. self.serial_number = serial_number
  451. self.access_code = access_code
  452. self.model = model
  453. # Last value logged by _debug_on_change(), keyed by log site. See there.
  454. self._debug_last: dict[str, object] = {}
  455. self.on_state_change = on_state_change
  456. self.on_print_start = on_print_start
  457. self.on_print_complete = on_print_complete
  458. self.on_ams_change = on_ams_change
  459. self.on_layer_change = on_layer_change
  460. self.on_bed_temp_update = on_bed_temp_update
  461. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  462. # the drying cycle just finished (auto- or manually-triggered).
  463. # Receives the AMS id of the unit that finished drying.
  464. self.on_drying_complete = on_drying_complete
  465. # #1485 follow-up: fired the first time we see RUNNING state in a
  466. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  467. # print, the #1304 first-push guard skipped the start event). Lets
  468. # main.py capture a fresh timelapse baseline at restart-recovery
  469. # time so the completion-time snapshot-diff still works. Receives
  470. # the same shape as on_print_start (filename / subtask_name /
  471. # remaining_time / raw_data / ams_mapping).
  472. self.on_print_running_observed = on_print_running_observed
  473. # #1721: fired the moment the printer enters the end-of-print
  474. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  475. # we've hit the last layer / remaining_time<=0). This is the
  476. # framing #1397 was after — toolhead parked, bed not yet
  477. # dropped — but reached via a clean state signal instead of
  478. # the per-layer M622 J1 macros which caused per-layer nozzle
  479. # parks on slicer profiles with Timelapse Type = Smooth.
  480. # A FINISH-state fallback below fires this same callback if
  481. # stage 22 never arrives (cancel mid-print, external-spool-
  482. # only prints, HMS halt before unload, firmware variants).
  483. self.on_finish_photo_moment = on_finish_photo_moment
  484. # Per-AMS previous dry_time, used to detect the falling edge above.
  485. # Seeded lazily as we observe each AMS unit.
  486. self._previous_dry_times: dict[int, int] = {}
  487. # Per-AMS active-cycle target params (filament + temp) we sent on the
  488. # last start. Bambu does not echo these back in the per-tick AMS push
  489. # — only the dry_time countdown — so we cache what we sent to drive
  490. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  491. self._drying_targets: dict[int, dict[str, object]] = {}
  492. self.state = PrinterState()
  493. self._client: mqtt.Client | None = None
  494. self._loop: asyncio.AbstractEventLoop | None = None
  495. self._previous_gcode_state: str | None = None
  496. self._previous_gcode_file: str | None = None
  497. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  498. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  499. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  500. # #1721: one-shot guard so the end-of-print stage-22 detector
  501. # and the FINISH-state fallback don't both fire on the same
  502. # print. Reset to False on every print start.
  503. self._finish_photo_captured: bool = False
  504. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  505. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  506. # The subtask_id minted for the most recent start_print() command. The
  507. # printer echoes it back in status, but often not within the first few
  508. # seconds — so on_print_start uses this as the id source when the
  509. # printer hasn't reported it yet, letting queue/scheduled archives
  510. # persist a restart-stable id from the moment they dispatch (#1485).
  511. self.last_dispatch_subtask_id: str | None = None
  512. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  513. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  514. self._logging_enabled: bool = False
  515. self._last_message_time: float = 0.0 # Track when we last received a message
  516. # Count of report-topic messages received since the last (re)connect.
  517. # Lets check_staleness() distinguish "printer never sent a status
  518. # report" (typically a wrong / mis-cased serial) from a normal quiet
  519. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  520. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  521. self._report_messages_since_connect: int = 0
  522. self._zero_report_hint_logged: bool = False
  523. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  524. # printer's pushes verbatim to slicers connected to a virtual printer).
  525. # Handlers receive (topic, payload_bytes) before JSON parsing.
  526. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  527. self._disconnection_event: threading.Event | None = None
  528. self._previous_ams_hash: str | None = None # Track AMS changes
  529. # Track external-spool (vt_tray) identity changes separately: the AMS
  530. # hash above covers only AMS units, so an external-spool-only filament
  531. # swap would never re-trigger inventory reconciliation (#2575).
  532. self._previous_vt_tray_hash: str | None = None
  533. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  534. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  535. self._ams_version_cache: dict[int, dict[str, str]] = {}
  536. # Track which (ams_id, field) warnings have already been emitted this connection
  537. # so that missing-serial / missing-firmware warnings fire only once per connection.
  538. self._ams_version_warned: set[tuple[int | str, str]] = set()
  539. # K-profile command tracking
  540. self._sequence_id: int = 0
  541. self._pending_kprofile_response: asyncio.Event | None = None
  542. self._kprofile_response_data: list | None = None
  543. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  544. # Key: module_name, Value: timestamp when command was sent
  545. self._xcam_hold_start: dict[str, float] = {}
  546. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  547. # Track last requested tray ID for H2D dual-nozzle printers
  548. # H2D only reports slot number (0-3) in tray_now, not global tray ID
  549. # We use our tracked value to resolve the correct global ID
  550. self._last_load_tray_id: int | None = None
  551. # Captured ams_mapping from print commands on the request topic
  552. # Intercepts slicer/Bambuddy print commands to get the slot-to-tray mapping
  553. self._captured_ams_mapping: list[int] | None = None
  554. # Request topic subscription tracking
  555. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  556. # topic by killing the TCP connection. We detect this and gracefully degrade.
  557. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  558. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  559. self._request_topic_sub_mid: int | None = None
  560. self._request_topic_sub_time: float = 0.0
  561. self._request_topic_confirmed: bool = False
  562. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  563. # we probe by sending an ams_filament_setting and checking the response.
  564. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  565. self._dev_mode_probed: bool = False
  566. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  567. self._dev_mode_probe_seq: str | None = None
  568. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  569. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  570. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  571. # Set when check_staleness() force-closes the socket to trigger reconnect.
  572. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  573. self._stale_reconnecting: bool = False
  574. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  575. # when the frontend polls status faster than paho can reconnect.
  576. self._last_stale_reconnect: float = 0.0
  577. # Zombie session detection via ams_filament_setting response tracking (#887).
  578. # The dev-mode probe only runs on first connect; this catches zombie sessions
  579. # that develop later (telemetry flows but publishes silently fail).
  580. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  581. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  582. @property
  583. def topic_subscribe(self) -> str:
  584. return f"device/{self.serial_number}/report"
  585. @property
  586. def topic_publish(self) -> str:
  587. return f"device/{self.serial_number}/request"
  588. @property
  589. def report_messages_since_connect(self) -> int:
  590. """Count of report-topic messages received since the latest (re)connect.
  591. Exposed for the connection diagnostic so it can distinguish "MQTT
  592. broker accepted us but the printer never published" (typically a
  593. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  594. bridge that happens to be idle right now. Zero immediately after a
  595. fresh connect is normal; zero after a full status push cycle is the
  596. wrong-serial failure mode.
  597. """
  598. return self._report_messages_since_connect
  599. # Maximum time (seconds) without a message before considering connection stale
  600. STALE_TIMEOUT = 60.0
  601. def is_stale(self) -> bool:
  602. """Check if the connection is stale (no messages for too long)."""
  603. if self._last_message_time == 0:
  604. return False # Never received a message yet
  605. time_since_last = time.time() - self._last_message_time
  606. return time_since_last > self.STALE_TIMEOUT
  607. # Minimum seconds between stale reconnect attempts. Frontend polls
  608. # status every few seconds — without a cooldown, each poll would
  609. # force-close the socket before paho has time to reconnect.
  610. STALE_RECONNECT_COOLDOWN = 30.0
  611. def check_staleness(self) -> bool:
  612. """Check staleness and update connected state if stale. Returns True if connected."""
  613. if self.state.connected and self.is_stale():
  614. # Don't force-close again if we already did recently — give paho
  615. # time to reconnect and the printer time to send its first message.
  616. now = time.time()
  617. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  618. return self.state.connected
  619. logger.warning(
  620. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  621. )
  622. # A connection that keeps going stale without ever receiving a
  623. # status report is almost always a wrong or mis-cased serial
  624. # number — the broker accepts the connection and the subscription
  625. # regardless, but the printer publishes to device/<real-serial>/
  626. # report, which is case-sensitive. Surface that once so the user
  627. # has something actionable instead of an endless reconnect loop.
  628. if self._report_messages_since_connect == 0 and not self._zero_report_hint_logged:
  629. self._zero_report_hint_logged = True
  630. logger.warning(
  631. "[%s] Connected and subscribed, but the printer has sent zero "
  632. "status reports. The most common cause is a wrong or mis-cased "
  633. "serial number — the device/<serial>/report MQTT topic is "
  634. "case-sensitive. Verify the serial number configured in Bambuddy "
  635. "exactly matches the printer.",
  636. self.serial_number,
  637. )
  638. self._last_stale_reconnect = now
  639. self.state.connected = False
  640. if self.on_state_change:
  641. self.on_state_change(self.state)
  642. # Route based on caller thread — see force_reconnect_stale_session.
  643. # check_staleness is normally called from FastAPI handlers (async,
  644. # gets the hard-reset path) but the dispatcher exists for safety.
  645. self._stale_reconnecting = True
  646. self._reset_client_for_reconnect()
  647. return self.state.connected
  648. def force_reconnect_stale_session(self, reason: str) -> None:
  649. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  650. # arriving but our publishes don't reach the printer.
  651. #
  652. # Two routing paths:
  653. #
  654. # Async-context callers (queue dispatch deadline)
  655. # → full client teardown + fresh client_id. Wipes paho's client-side
  656. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  657. # `project_file` from the broken session would otherwise replay on
  658. # reconnect, mixing stale commands into the next dispatch and
  659. # triggering 0500_4003 SD R/W on the printer.
  660. #
  661. # Paho-network-thread callers (line ~2604/~2623 — dev-mode probe and
  662. # ams_filament_setting zombie detection inside `_update_state`)
  663. # → socket-close fallback. Calling `loop_stop()` from inside the
  664. # network thread would self-join and deadlock; the safe pattern is
  665. # to close the socket and let paho's own loop detect the broken
  666. # connection and auto-reconnect (same instance, same client_id —
  667. # queue replay is theoretically possible here but those paths have
  668. # always done socket-close and #1136 was specifically triggered
  669. # from the dispatch path).
  670. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  671. self._stale_reconnecting = True
  672. self.state.connected = False
  673. if self.on_state_change:
  674. self.on_state_change(self.state)
  675. self._reset_client_for_reconnect()
  676. def _reset_client_for_reconnect(self) -> None:
  677. """Route between hard-reset and socket-close based on caller thread.
  678. Hard-reset (preferred) requires we're not running on paho's network
  679. thread, since `loop_stop()` on the same thread deadlocks. Detect via
  680. ``asyncio.get_running_loop()`` — paho's callback thread has no loop;
  681. every legitimate hard-reset caller (FastAPI handlers, background
  682. async tasks) does."""
  683. try:
  684. loop = asyncio.get_running_loop()
  685. except RuntimeError:
  686. loop = None
  687. if loop is not None:
  688. self._loop = loop
  689. self._hard_reset_client()
  690. else:
  691. self._socket_close_for_reconnect()
  692. def _hard_reset_client(self) -> None:
  693. """Tear down the paho client entirely and rebuild it with a fresh
  694. client_id, so the broker drops the old session and paho's local
  695. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  696. Caller is responsible for setting ``_stale_reconnecting`` and
  697. broadcasting the disconnected state."""
  698. old_client = self._client
  699. self._client = None
  700. if old_client is not None:
  701. try:
  702. old_client.disconnect() # MQTT DISCONNECT — broker drops session
  703. except Exception:
  704. pass
  705. try:
  706. old_client.loop_stop() # blocks briefly until the network thread exits
  707. except Exception:
  708. pass
  709. # Skip reconnect if no asyncio loop is available (test environment or
  710. # pre-init). The next initial connect() call from PrinterManager will
  711. # set up the client fresh.
  712. if self._loop is None:
  713. return
  714. try:
  715. self.connect(loop=self._loop)
  716. except Exception as e:
  717. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  718. def _socket_close_for_reconnect(self) -> None:
  719. """Close the underlying socket so paho's loop thread detects the
  720. broken connection and triggers auto-reconnect on the SAME client
  721. instance. Safe to call from paho's own network thread (the loop
  722. polls the socket on every iteration and handles a closed socket
  723. gracefully). Used as a fallback when hard-reset isn't safe; queue
  724. replay remains theoretically possible here but #1136 specifically
  725. traced through the dispatch-deadline path which now hard-resets."""
  726. if self._client:
  727. try:
  728. sock = self._client.socket()
  729. if sock:
  730. sock.close()
  731. except Exception:
  732. pass
  733. def _on_connect(self, client, userdata, flags, rc, properties=None):
  734. if rc == 0:
  735. self.state.connected = True
  736. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  737. # Reset per-connection warning state so warnings fire once per (re)connection
  738. self._ams_version_warned = set()
  739. # Preserve cached developer_mode across auto-reconnects to avoid
  740. # re-probing on every reconnect. The probe (ams_filament_setting to
  741. # ext slot) can destabilize some firmware MQTT brokers, causing a
  742. # reconnect → probe → disconnect feedback loop (#887). Only probe
  743. # once when developer_mode is truly unknown (first connect).
  744. # Reset probe tracking so stale timeout state doesn't carry over.
  745. self._dev_mode_probed = False
  746. self._dev_mode_needs_probe = False
  747. self._dev_mode_probe_seq = None
  748. self._dev_mode_probe_time = 0.0
  749. self._dev_mode_probe_failures = 0
  750. self._connect_time = time.monotonic()
  751. self._report_messages_since_connect = 0
  752. self._last_ams_cmd_time = 0.0
  753. self._ams_cmd_unanswered = 0
  754. client.subscribe(self.topic_subscribe)
  755. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  756. if self._request_topic_supported:
  757. result, mid = client.subscribe(self.topic_publish)
  758. if result == mqtt.MQTT_ERR_SUCCESS:
  759. self._request_topic_sub_mid = mid
  760. self._request_topic_sub_time = time.time()
  761. self._request_topic_confirmed = False
  762. else:
  763. logger.warning(
  764. "[%s] Failed to send request topic subscription",
  765. self.serial_number,
  766. )
  767. self._request_topic_supported = False
  768. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  769. # Request full status update (includes nozzle info in push_status response)
  770. self._request_push_all()
  771. # Request firmware version info
  772. self._request_version()
  773. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  774. # The correct nozzle data comes from push_status.
  775. # Prime K-profile request (Bambu printers often ignore first request)
  776. self._prime_kprofile_request()
  777. # Immediately broadcast connection state change
  778. if self.on_state_change:
  779. self.on_state_change(self.state)
  780. else:
  781. self.state.connected = False
  782. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  783. """Handle SUBACK responses to detect request topic subscription rejection."""
  784. if mid == self._request_topic_sub_mid:
  785. for rc in reason_code_list:
  786. if rc.is_failure:
  787. logger.warning(
  788. "[%s] Request topic subscription rejected (code=%d: %s). "
  789. "ams_mapping capture from slicer-initiated prints unavailable.",
  790. self.serial_number,
  791. rc.value,
  792. rc.getName(),
  793. )
  794. self._request_topic_supported = False
  795. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  796. else:
  797. logger.info(
  798. "[%s] Request topic subscription accepted. "
  799. "ams_mapping capture enabled for slicer-initiated prints.",
  800. self.serial_number,
  801. )
  802. self._request_topic_confirmed = True
  803. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  804. self._request_topic_sub_mid = None
  805. self._request_topic_sub_time = 0.0
  806. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  807. # Always unblock disconnect() callers, regardless of whether we suppress
  808. # the state broadcast below. disconnect() sets _disconnection_event and
  809. # waits on it — every callback path must fire it.
  810. if self._disconnection_event:
  811. self._disconnection_event.set()
  812. # If we intentionally closed the socket for stale reconnect, don't broadcast
  813. # another state change — check_staleness() already set connected=False and
  814. # notified the UI. Just log and let paho auto-reconnect.
  815. if self._stale_reconnecting:
  816. logger.info(
  817. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  818. self.serial_number,
  819. rc,
  820. )
  821. return
  822. # Ignore spurious disconnect callbacks if we've received a message recently
  823. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  824. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  825. # — only suppress when rc indicates a clean/normal disconnect.
  826. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  827. time_since_last_message = time.time() - self._last_message_time
  828. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  829. logger.debug(
  830. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  831. )
  832. return
  833. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  834. # Detect if request topic subscription caused the disconnect.
  835. # If we just subscribed and got disconnected before any SUBACK confirmation,
  836. # the broker likely killed the connection due to the unauthorized subscription.
  837. if (
  838. self._request_topic_sub_time > 0
  839. and not self._request_topic_confirmed
  840. and time.time() - self._request_topic_sub_time < 10.0
  841. ):
  842. logger.warning(
  843. "[%s] Disconnected shortly after request topic subscription. Disabling request topic for this printer.",
  844. self.serial_number,
  845. )
  846. self._request_topic_supported = False
  847. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  848. self._request_topic_sub_mid = None
  849. self._request_topic_sub_time = 0.0
  850. self.state.connected = False
  851. if self.on_state_change:
  852. self.on_state_change(self.state)
  853. def _on_message(self, client, userdata, msg):
  854. for handler in self._raw_message_handlers:
  855. try:
  856. handler(msg.topic, msg.payload)
  857. except Exception:
  858. logger.exception(
  859. "[%s] raw-message handler crashed for topic=%s",
  860. self.serial_number,
  861. msg.topic,
  862. )
  863. try:
  864. try:
  865. raw = msg.payload.decode()
  866. except UnicodeDecodeError:
  867. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  868. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  869. raw = msg.payload.decode(errors="replace")
  870. logger.warning(
  871. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  872. self.serial_number,
  873. msg.topic,
  874. len(msg.payload),
  875. )
  876. payload = json.loads(raw)
  877. # Track last message time - receiving a message proves we're connected
  878. self._last_message_time = time.time()
  879. self.state.connected = True
  880. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  881. if msg.topic == self.topic_publish:
  882. self._handle_request_message(payload)
  883. return
  884. # Count status reports per connection so check_staleness() can tell
  885. # "printer never sent a report" apart from a mid-session quiet gap.
  886. if msg.topic == self.topic_subscribe:
  887. self._report_messages_since_connect += 1
  888. # Log message if logging is enabled
  889. if self._logging_enabled:
  890. self._message_log.append(
  891. MQTTLogEntry(
  892. timestamp=datetime.now(timezone.utc).isoformat(),
  893. topic=msg.topic,
  894. direction="in",
  895. payload=payload,
  896. )
  897. )
  898. self._process_message(payload)
  899. except json.JSONDecodeError:
  900. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  901. def _handle_request_message(self, data: dict) -> None:
  902. """Intercept print commands on the request topic to capture ams_mapping."""
  903. print_data = data.get("print", {})
  904. if not isinstance(print_data, dict):
  905. return
  906. command = print_data.get("command", "")
  907. if command == "project_file":
  908. if "ams_mapping" in print_data:
  909. self._captured_ams_mapping = print_data["ams_mapping"]
  910. logger.info(
  911. "[%s] Captured ams_mapping from print command: %s",
  912. self.serial_number,
  913. self._captured_ams_mapping,
  914. )
  915. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  916. # slicer-launched project_file passes through the request topic,
  917. # log the full payload so we can diff Studio's field set against
  918. # ours. We pin our own sequence_id to "20000" (line ~3195), so
  919. # any other value means the command came from Studio/Orca, not
  920. # from us.
  921. if print_data.get("sequence_id") != "20000":
  922. logger.info(
  923. "[%s] External project_file payload: %s",
  924. self.serial_number,
  925. json.dumps(print_data),
  926. )
  927. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  928. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  929. The state dumps in the push_status handler fire whenever their field is
  930. *present* in the frame — and a full push_status carries every field, so
  931. they fire on every frame regardless of whether anything changed. Several
  932. even say "updated" or "changes" in their own comment while doing nothing
  933. of the sort.
  934. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  935. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  936. minutes: the reporter enabled debug logging as asked and the support
  937. bundle came back holding under five minutes of history, almost none of it
  938. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  939. these dumps.
  940. Deduplicating on the value keeps every transition — which is the only part
  941. anyone reads these lines for — and drops the steady-state repetition.
  942. ``value`` must capture everything interpolated into ``msg``, or a change
  943. will be swallowed; pass a tuple when the message renders several fields.
  944. """
  945. if not logger.isEnabledFor(logging.DEBUG):
  946. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  947. # and these clients outlive the toggle. Letting INFO-level frames warm
  948. # the cache would be self-defeating: the operator turns debug on
  949. # precisely to see the printer's current state, and a cache already
  950. # holding every steady-state value would suppress that baseline until
  951. # something happened to change. On an idle printer the bundle would
  952. # come back with none of these lines at all.
  953. #
  954. # So while debug is off we record nothing and drop whatever we had.
  955. # Every enable then starts cold and dumps a full baseline on the next
  956. # frame, exactly as it did before this method existed.
  957. self._debug_last.clear()
  958. return
  959. if self._debug_last.get(key) == value:
  960. return
  961. self._debug_last[key] = value
  962. logger.debug(msg, *args)
  963. def _process_message(self, payload: dict):
  964. """Process incoming MQTT message from printer."""
  965. # Handle top-level AMS data (comes outside of "print" key)
  966. # Wrap in try/except to prevent breaking the MQTT connection
  967. if "ams" in payload:
  968. try:
  969. self._handle_ams_data(payload["ams"])
  970. except Exception as e:
  971. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  972. # Handle xcam data (camera settings and AI detection) at top level
  973. if "xcam" in payload:
  974. xcam_data = payload["xcam"]
  975. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  976. self._parse_xcam_data(xcam_data)
  977. # Fire state change callback for top-level xcam (not nested in "print")
  978. if "print" not in payload and self.on_state_change:
  979. self.on_state_change(self.state)
  980. # Handle system responses (accessories info, etc.)
  981. if "system" in payload:
  982. system_data = payload["system"]
  983. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  984. self._handle_system_response(system_data)
  985. # Handle info responses (firmware version info from get_version command)
  986. if "info" in payload:
  987. info_data = payload["info"]
  988. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  989. self._handle_version_info(info_data)
  990. # Parse WiFi signal at top level (some printers send it here)
  991. if "wifi_signal" in payload:
  992. wifi_signal = payload["wifi_signal"]
  993. if isinstance(wifi_signal, (int, float)):
  994. self.state.wifi_signal = int(wifi_signal)
  995. elif isinstance(wifi_signal, str):
  996. try:
  997. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  998. except ValueError:
  999. pass # Ignore unparseable wifi_signal strings; field is non-critical
  1000. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  1001. from backend.app.utils.printer_models import has_ethernet
  1002. if has_ethernet(self.model):
  1003. self.state.wired_network = self.state.wifi_signal == -90
  1004. # Parse developer LAN mode from top-level "fun" field
  1005. # Some firmware versions send "fun" at the top level, others inside "print"
  1006. if "fun" in payload:
  1007. try:
  1008. fun_val = payload["fun"]
  1009. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  1010. self.state.developer_mode = (fun_int & 0x20000000) == 0
  1011. except (ValueError, TypeError):
  1012. pass
  1013. if "print" in payload:
  1014. print_data = payload["print"]
  1015. # Check if xcam is nested inside print data
  1016. if "xcam" in print_data:
  1017. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  1018. self._parse_xcam_data(print_data["xcam"])
  1019. # Log when we see gcode_state changes
  1020. if "gcode_state" in print_data:
  1021. logger.debug(
  1022. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  1023. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  1024. )
  1025. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  1026. # new-protocol printers. Verified against OrcaSlicer's
  1027. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  1028. # and live H2D ON/OFF capture 2026-06-20.
  1029. #
  1030. # Hold-timer guard: when the user just toggled via the badge, the
  1031. # next 1-2 push_status frames may still carry the printer's OLD cfg
  1032. # for ~3 s before the firmware reflects the change. Without this
  1033. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  1034. new_backup = parse_ams_filament_backup_from_cfg(print_data.get("cfg"))
  1035. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  1036. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  1037. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  1038. logger.debug(
  1039. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  1040. self.serial_number,
  1041. time.time() - hold_start,
  1042. )
  1043. else:
  1044. logger.info(
  1045. "[%s] AMS Filament Backup: %s",
  1046. self.serial_number,
  1047. "ON" if new_backup else "OFF",
  1048. )
  1049. self.state.ams_filament_backup = new_backup
  1050. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  1051. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  1052. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  1053. if not self._is_dual_nozzle and "device" in print_data:
  1054. dev = print_data.get("device")
  1055. if isinstance(dev, dict):
  1056. ext_info = dev.get("extruder", {}).get("info", [])
  1057. if isinstance(ext_info, list) and len(ext_info) >= 2:
  1058. self._is_dual_nozzle = True
  1059. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  1060. # Handle AMS data that comes inside print key
  1061. if "ams" in print_data:
  1062. try:
  1063. self._handle_ams_data(print_data["ams"])
  1064. except Exception as e:
  1065. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  1066. # Handle vir_slot (H2-series external spool data) — list of external trays
  1067. # Process vir_slot FIRST so it takes priority over vt_tray
  1068. if "vir_slot" in print_data:
  1069. vir_slot = print_data["vir_slot"]
  1070. if isinstance(vir_slot, list) and vir_slot:
  1071. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  1072. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  1073. # Remap id=255→254 for single-slot printers so active detection works.
  1074. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  1075. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  1076. vir_slot[0]["id"] = "254"
  1077. self.state.raw_data["vt_tray"] = vir_slot
  1078. # Handle vt_tray (virtual tray / external spool) data
  1079. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  1080. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  1081. # which would overwrite the correct multi-slot vir_slot data)
  1082. if "vt_tray" in print_data and "vir_slot" not in print_data:
  1083. vt_tray = print_data["vt_tray"]
  1084. existing = self.state.raw_data.get("vt_tray")
  1085. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  1086. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  1087. pass # Keep the vir_slot data
  1088. else:
  1089. if isinstance(vt_tray, dict):
  1090. vt_tray = [vt_tray]
  1091. self.state.raw_data["vt_tray"] = vt_tray
  1092. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  1093. # units, and _handle_ams_data runs before this block — so a change
  1094. # to the external spool alone (e.g. swapping generic TPU for generic
  1095. # ABS on the printer) never re-triggers on_ams_change, leaving a
  1096. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  1097. # external-spool identity changes here and fire the same callback.
  1098. self._maybe_trigger_external_spool_change()
  1099. # Parse ams_status directly from print data (NOT from print.ams)
  1100. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1101. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  1102. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  1103. if "ams_status" in print_data:
  1104. raw_ams_status = print_data["ams_status"]
  1105. if isinstance(raw_ams_status, str):
  1106. try:
  1107. self.state.ams_status = int(raw_ams_status)
  1108. except ValueError:
  1109. self.state.ams_status = 0
  1110. else:
  1111. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  1112. # Compute main and sub status
  1113. self.state.ams_status_sub = self.state.ams_status & 0xFF
  1114. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  1115. # Log when ams_status changes (for filament change tracking debug)
  1116. self._debug_on_change(
  1117. "ams_status:print",
  1118. self.state.ams_status,
  1119. "[%s] ams_status: %s (main=%s, sub=%s)",
  1120. self.serial_number,
  1121. self.state.ams_status,
  1122. self.state.ams_status_main,
  1123. self.state.ams_status_sub,
  1124. )
  1125. # Check for command responses
  1126. if "command" in print_data:
  1127. cmd = print_data.get("command")
  1128. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  1129. if cmd in ("extrusion_cali_sel", "extrusion_cali_set", "extrusion_cali_del", "ams_filament_setting"):
  1130. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  1131. # AMS drying responses are rare (user-initiated only) and the
  1132. # full payload — including `result` and any `reason` code —
  1133. # is the only way to diagnose silent rejections like #1447.
  1134. # INFO level so the body lands in support bundles by default.
  1135. elif cmd == "ams_filament_drying":
  1136. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  1137. # Check for developer mode probe response
  1138. if (
  1139. cmd == "ams_filament_setting"
  1140. and self._dev_mode_probe_seq is not None
  1141. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  1142. ):
  1143. self._handle_dev_mode_probe_response(print_data)
  1144. # Track user-initiated ams_filament_setting responses (#887
  1145. # zombie detection). Reset both the timer AND the unanswered
  1146. # counter on ANY response — the response proves the channel is
  1147. # alive, so the counter must not stay armed even when the
  1148. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  1149. # tick. The original `and self._last_ams_cmd_time > 0` guard
  1150. # caused #1164: one sluggish response (>10s) would set the
  1151. # counter to 1 and zero the timer; the late response arrived
  1152. # but was ignored by this branch (timer is 0); the counter
  1153. # stayed at 1 indefinitely; the very next slow response —
  1154. # possibly hours later, on a totally unrelated command — would
  1155. # take it to 2 and force-reconnect, surfacing as "filament
  1156. # config doesn't reach the printer ~6 changes in".
  1157. elif cmd == "ams_filament_setting":
  1158. self._last_ams_cmd_time = 0.0
  1159. self._ams_cmd_unanswered = 0
  1160. if "command" in print_data and print_data.get("command") == "extrusion_cali_get":
  1161. self._handle_kprofile_response(print_data)
  1162. self._update_state(print_data)
  1163. def _handle_system_response(self, data: dict):
  1164. """Handle system responses including accessories info.
  1165. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  1166. The correct nozzle data comes from push_status, so we don't update
  1167. nozzle type/diameter from get_accessories. We just log the response
  1168. for debugging purposes.
  1169. """
  1170. command = data.get("command")
  1171. if command == "get_accessories":
  1172. # Log response for debugging - but DON'T use it to update nozzle data
  1173. # because it returns stale values (e.g., 'stainless_steel' when the
  1174. # actual nozzle is 'HH01' hardened steel high-flow)
  1175. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  1176. def _handle_version_info(self, data: dict):
  1177. """Handle version info response from get_version command.
  1178. Parses firmware version from the 'ota' module in the module list.
  1179. Also extracts AMS unit firmware versions from AMS modules and stores
  1180. them on the corresponding AMS unit in raw_data so the status route can
  1181. expose them to the frontend.
  1182. AMS module naming conventions (numeric suffix is the AMS unit ID):
  1183. - ``ams/<id>`` – original AMS
  1184. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  1185. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  1186. Message format:
  1187. {
  1188. "command": "get_version",
  1189. "module": [
  1190. {"name": "ota", "sw_ver": "01.08.05.00"},
  1191. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  1192. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  1193. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  1194. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  1195. ...
  1196. ]
  1197. }
  1198. """
  1199. modules = data.get("module", [])
  1200. if not isinstance(modules, list):
  1201. return
  1202. state_changed = False
  1203. for module in modules:
  1204. if not isinstance(module, dict):
  1205. continue
  1206. if module.get("name") == "ota":
  1207. version = module.get("sw_ver")
  1208. if version:
  1209. old_version = self.state.firmware_version
  1210. self.state.firmware_version = version
  1211. if old_version != version:
  1212. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  1213. state_changed = True
  1214. break
  1215. # Extract AMS unit firmware versions from AMS modules.
  1216. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  1217. # Always cache regardless of whether AMS data has arrived yet — get_version
  1218. # often arrives before the first push_status, so caching must be unconditional.
  1219. ams_raw = self.state.raw_data.get("ams")
  1220. for module in modules:
  1221. if not isinstance(module, dict):
  1222. continue
  1223. name = module.get("name", "")
  1224. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  1225. continue
  1226. try:
  1227. ams_id = int(name.split("/", 1)[1])
  1228. except (ValueError, IndexError):
  1229. continue
  1230. sw_ver = module.get("sw_ver", "")
  1231. sn = module.get("sn", "")
  1232. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  1233. module_type = name.split("/", 1)[0]
  1234. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  1235. if sw_ver or sn or module_type:
  1236. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  1237. state_changed = True
  1238. # Also directly update any AMS unit already present in raw_data
  1239. if ams_raw and isinstance(ams_raw, list):
  1240. for ams_unit in ams_raw:
  1241. if not isinstance(ams_unit, dict):
  1242. continue
  1243. try:
  1244. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  1245. except (ValueError, TypeError):
  1246. unit_id = None
  1247. if unit_id == ams_id:
  1248. if sw_ver:
  1249. ams_unit["sw_ver"] = sw_ver
  1250. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  1251. # Only set sn from version info if not already present in AMS data
  1252. if sn and not ams_unit.get("sn"):
  1253. ams_unit["sn"] = sn
  1254. if module_type:
  1255. ams_unit["module_type"] = module_type
  1256. break
  1257. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  1258. # included in the broadcast (not just the printer firmware version).
  1259. if state_changed and self.on_state_change:
  1260. self.on_state_change(self.state)
  1261. # Warn if any AMS unit is still missing serial number or firmware version
  1262. # after processing the version info response. Warn only once per connection
  1263. # to avoid repeated noise on older firmware that doesn't report these fields.
  1264. if ams_raw and isinstance(ams_raw, list):
  1265. for ams_unit in ams_raw:
  1266. if not isinstance(ams_unit, dict):
  1267. continue
  1268. ams_id = ams_unit.get("id", "?")
  1269. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  1270. key = (ams_id, "sn")
  1271. if key not in self._ams_version_warned:
  1272. self._ams_version_warned.add(key)
  1273. logger.warning(
  1274. "[%s] AMS unit %s: serial number not available in version info",
  1275. self.serial_number,
  1276. ams_id,
  1277. )
  1278. if not ams_unit.get("sw_ver"):
  1279. key = (ams_id, "sw_ver")
  1280. if key not in self._ams_version_warned:
  1281. self._ams_version_warned.add(key)
  1282. logger.warning(
  1283. "[%s] AMS unit %s: firmware version not available in version info",
  1284. self.serial_number,
  1285. ams_id,
  1286. )
  1287. def _apply_ams_version_cache(self, ams_list: list) -> None:
  1288. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  1289. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  1290. strings in MQTT payloads. This helper normalizes IDs and fills missing
  1291. sw_ver/sn fields without overwriting values already present.
  1292. """
  1293. if not ams_list or not isinstance(ams_list, list):
  1294. return
  1295. cache = self._ams_version_cache
  1296. if not cache:
  1297. return
  1298. for unit in ams_list:
  1299. if not isinstance(unit, dict):
  1300. continue
  1301. raw_id = unit.get("id")
  1302. try:
  1303. unit_id = int(raw_id) if raw_id is not None else None
  1304. except (ValueError, TypeError):
  1305. unit_id = None
  1306. if unit_id is None:
  1307. continue
  1308. cached = cache.get(unit_id)
  1309. if not cached:
  1310. continue
  1311. sw_ver = cached.get("sw_ver") or ""
  1312. sn = cached.get("sn") or ""
  1313. if sw_ver and not unit.get("sw_ver"):
  1314. unit["sw_ver"] = sw_ver
  1315. # Only set sn if not already present in AMS data
  1316. if sn and not unit.get("sn") and not unit.get("serial_number"):
  1317. unit["sn"] = sn
  1318. module_type = cached.get("module_type") or ""
  1319. if module_type and not unit.get("module_type"):
  1320. unit["module_type"] = module_type
  1321. def _parse_xcam_data(self, xcam_data):
  1322. """Parse xcam data for camera settings and AI detection options."""
  1323. if not isinstance(xcam_data, dict):
  1324. return
  1325. current_time = time.time()
  1326. # Helper to check if we should accept incoming value for a module
  1327. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  1328. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  1329. """Check if we should accept an incoming xcam value.
  1330. OrcaSlicer pattern: After sending a command, ignore incoming data
  1331. for 3 seconds. After that, accept whatever the printer sends.
  1332. """
  1333. if module_name not in self._xcam_hold_start:
  1334. return True # No hold timer, accept incoming
  1335. hold_start = self._xcam_hold_start[module_name]
  1336. elapsed = current_time - hold_start
  1337. if elapsed > self._xcam_hold_time:
  1338. # Hold timer expired - accept incoming and clear hold
  1339. del self._xcam_hold_start[module_name]
  1340. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  1341. return True
  1342. # Within hold period - ignore incoming data
  1343. logger.debug(
  1344. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  1345. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  1346. )
  1347. return False
  1348. # Log all xcam fields for debugging
  1349. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  1350. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  1351. # fields (spaghetti_detector, etc.) are often stale/cached.
  1352. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  1353. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  1354. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  1355. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  1356. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  1357. # Sensitivity values: 0=low, 1=medium, 2=high
  1358. if "cfg" in xcam_data:
  1359. cfg = xcam_data["cfg"]
  1360. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  1361. def decode_detector(start_bit):
  1362. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  1363. sens_bits = (cfg >> start_bit) & 0x3
  1364. enabled = bool((cfg >> (start_bit + 2)) & 1)
  1365. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  1366. return enabled, sensitivity
  1367. # Spaghetti detector (bits 5-7)
  1368. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  1369. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  1370. old_value = self.state.print_options.spaghetti_detector
  1371. if cfg_spaghetti != old_value:
  1372. logger.debug(
  1373. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  1374. )
  1375. self.state.print_options.spaghetti_detector = cfg_spaghetti
  1376. # Check hold timer for sensitivity before accepting
  1377. if "halt_print_sensitivity" not in self._xcam_hold_start:
  1378. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  1379. logger.debug(
  1380. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  1381. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  1382. )
  1383. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  1384. else:
  1385. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  1386. elapsed = current_time - hold_start
  1387. if elapsed <= self._xcam_hold_time:
  1388. logger.debug(
  1389. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  1390. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  1391. )
  1392. else:
  1393. # Hold expired - accept from cfg
  1394. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  1395. logger.debug(
  1396. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  1397. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  1398. )
  1399. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  1400. del self._xcam_hold_start["halt_print_sensitivity"]
  1401. # Pileup detector (bits 8-10)
  1402. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  1403. if should_accept_value("pileup_detector", cfg_pileup):
  1404. if cfg_pileup != self.state.print_options.pileup_detector:
  1405. logger.debug(
  1406. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  1407. )
  1408. self.state.print_options.pileup_detector = cfg_pileup
  1409. # Pileup sensitivity with hold timer
  1410. if "pileup_sensitivity" not in self._xcam_hold_start:
  1411. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  1412. logger.debug(
  1413. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  1414. )
  1415. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  1416. else:
  1417. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  1418. elapsed = current_time - hold_start
  1419. if elapsed > self._xcam_hold_time:
  1420. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  1421. logger.debug(
  1422. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  1423. )
  1424. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  1425. del self._xcam_hold_start["pileup_sensitivity"]
  1426. # Clump/nozzle clumping detector (bits 11-13)
  1427. cfg_clump, cfg_clump_sens = decode_detector(11)
  1428. if should_accept_value("clump_detector", cfg_clump):
  1429. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  1430. logger.debug(
  1431. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  1432. )
  1433. self.state.print_options.nozzle_clumping_detector = cfg_clump
  1434. # Clump sensitivity with hold timer
  1435. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  1436. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  1437. logger.debug(
  1438. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  1439. )
  1440. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  1441. else:
  1442. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  1443. elapsed = current_time - hold_start
  1444. if elapsed > self._xcam_hold_time:
  1445. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  1446. logger.debug(
  1447. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  1448. )
  1449. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  1450. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  1451. # Airprint detector (bits 14-16)
  1452. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  1453. if should_accept_value("airprint_detector", cfg_airprint):
  1454. if cfg_airprint != self.state.print_options.airprint_detector:
  1455. logger.debug(
  1456. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  1457. )
  1458. self.state.print_options.airprint_detector = cfg_airprint
  1459. # Airprint sensitivity with hold timer
  1460. if "airprint_sensitivity" not in self._xcam_hold_start:
  1461. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  1462. logger.debug(
  1463. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  1464. )
  1465. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  1466. else:
  1467. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  1468. elapsed = current_time - hold_start
  1469. if elapsed > self._xcam_hold_time:
  1470. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  1471. logger.debug(
  1472. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  1473. )
  1474. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  1475. del self._xcam_hold_start["airprint_sensitivity"]
  1476. # Camera settings
  1477. if "ipcam_record" in xcam_data:
  1478. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  1479. if "timelapse" in xcam_data:
  1480. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  1481. # Track if timelapse was ever active during this print
  1482. if self.state.timelapse and self._was_running:
  1483. self._timelapse_during_print = True
  1484. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  1485. if "print_halt" in xcam_data:
  1486. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  1487. # Skip halt_print_sensitivity field - it's always stale ("medium")
  1488. # We read the actual sensitivity from cfg bits 5-6 above
  1489. if "first_layer_inspector" in xcam_data:
  1490. new_value = bool(xcam_data.get("first_layer_inspector"))
  1491. if should_accept_value("first_layer_inspector", new_value):
  1492. self.state.print_options.first_layer_inspector = new_value
  1493. if "printing_monitor" in xcam_data:
  1494. new_value = bool(xcam_data.get("printing_monitor"))
  1495. if should_accept_value("printing_monitor", new_value):
  1496. self.state.print_options.printing_monitor = new_value
  1497. if "buildplate_marker_detector" in xcam_data:
  1498. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  1499. if should_accept_value("buildplate_marker_detector", new_value):
  1500. self.state.print_options.buildplate_marker_detector = new_value
  1501. if "allow_skip_parts" in xcam_data:
  1502. new_value = bool(xcam_data.get("allow_skip_parts"))
  1503. if should_accept_value("allow_skip_parts", new_value):
  1504. self.state.print_options.allow_skip_parts = new_value
  1505. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  1506. # individual boolean fields (which are not sent by the printer)
  1507. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  1508. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  1509. if "auto_recovery_step_loss" in xcam_data:
  1510. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  1511. if "filament_tangle_detect" in xcam_data:
  1512. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  1513. @staticmethod
  1514. def _resolve_local_slot_from_mapping(local_slot: int, mapping_raw: list | None) -> int | None:
  1515. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  1516. The MQTT mapping field is an array of snow-encoded values:
  1517. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  1518. Finds entries where the local slot matches, then computes the global tray ID.
  1519. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  1520. """
  1521. if not isinstance(mapping_raw, list) or not mapping_raw:
  1522. return None
  1523. candidates: set[int] = set()
  1524. for value in mapping_raw:
  1525. if not isinstance(value, int) or value >= 65535:
  1526. continue
  1527. ams_hw_id = value >> 8
  1528. slot = value & 0xFF
  1529. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  1530. candidates.add(ams_hw_id * 4 + local_slot)
  1531. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  1532. candidates.add(ams_hw_id)
  1533. if len(candidates) == 1:
  1534. return candidates.pop()
  1535. return None
  1536. def _maybe_trigger_external_spool_change(self):
  1537. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  1538. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  1539. an external-spool-only filament swap would otherwise never re-run the
  1540. inventory reconciliation that unlinks a stale ams_id=255 assignment
  1541. (#2575). The reconciliation reads vt_tray from live status itself, so we
  1542. just need to re-fire the callback with the current merged AMS data.
  1543. """
  1544. import hashlib
  1545. vt_tray = self.state.raw_data.get("vt_tray")
  1546. if not isinstance(vt_tray, list):
  1547. return
  1548. # Identity fields only — deliberately exclude `remain` so a print's
  1549. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  1550. fp_parts = [
  1551. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  1552. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  1553. for vt in vt_tray
  1554. if isinstance(vt, dict)
  1555. ]
  1556. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  1557. if vt_hash == self._previous_vt_tray_hash:
  1558. return
  1559. self._previous_vt_tray_hash = vt_hash
  1560. if self.on_ams_change:
  1561. logger.debug(
  1562. "[%s] External spool (vt_tray) changed, triggering sync callback",
  1563. self.serial_number,
  1564. )
  1565. self.on_ams_change(self.state.raw_data.get("ams") or [])
  1566. def _handle_ams_data(self, ams_data):
  1567. """Handle AMS data changes for Spoolman integration.
  1568. This is called when we receive top-level AMS data in MQTT messages.
  1569. It detects changes and triggers the callback for Spoolman sync.
  1570. """
  1571. import hashlib
  1572. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  1573. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  1574. ams_list = None
  1575. if isinstance(ams_data, dict):
  1576. if "ams" in ams_data:
  1577. ams_list = ams_data["ams"]
  1578. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  1579. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  1580. if non_list_fields:
  1581. self._debug_on_change(
  1582. "ams_dict_fields",
  1583. non_list_fields,
  1584. "[%s] AMS dict fields: %s",
  1585. self.serial_number,
  1586. non_list_fields,
  1587. )
  1588. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  1589. # when checking if we're in filament change mode for tray_now disambiguation
  1590. if "ams_status" in ams_data:
  1591. raw_ams_status = ams_data["ams_status"]
  1592. if isinstance(raw_ams_status, str):
  1593. try:
  1594. self.state.ams_status = int(raw_ams_status)
  1595. except ValueError:
  1596. self.state.ams_status = 0
  1597. else:
  1598. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  1599. # Compute main and sub status
  1600. self.state.ams_status_sub = self.state.ams_status & 0xFF
  1601. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  1602. self._debug_on_change(
  1603. "ams_status:ams",
  1604. self.state.ams_status,
  1605. "[%s] ams_status: %s (main=%s, sub=%s)",
  1606. self.serial_number,
  1607. self.state.ams_status,
  1608. self.state.ams_status_main,
  1609. self.state.ams_status_sub,
  1610. )
  1611. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  1612. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  1613. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  1614. # next compatible slot (#2587). Stored raw here; globalised at the API
  1615. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  1616. # these are local slot numbers (0-3), not global IDs.
  1617. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  1618. if _tk in ams_data:
  1619. _raw = ams_data[_tk]
  1620. if isinstance(_raw, str):
  1621. try:
  1622. _val = int(_raw)
  1623. except ValueError:
  1624. _val = 255
  1625. else:
  1626. _val = _raw if _raw is not None else 255
  1627. prev = getattr(self.state, _attr)
  1628. setattr(self.state, _attr, _val)
  1629. # Log changes only while paused — the moment the operator cares —
  1630. # so a healthy print's normal tar churn doesn't spam the log.
  1631. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  1632. logger.info(
  1633. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  1634. self.serial_number,
  1635. _tk,
  1636. _val,
  1637. )
  1638. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  1639. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  1640. if "tray_now" in ams_data:
  1641. raw_tray_now = ams_data["tray_now"]
  1642. # Convert string to int if needed
  1643. if isinstance(raw_tray_now, str):
  1644. try:
  1645. parsed_tray_now = int(raw_tray_now)
  1646. except ValueError:
  1647. parsed_tray_now = 255
  1648. else:
  1649. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  1650. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  1651. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  1652. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  1653. # — disambiguated below using MQTT mapping field
  1654. ams_map = self.state.ams_extruder_map
  1655. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  1656. # First, check if we have a pending target that matches this slot
  1657. pending_target = self.state.pending_tray_target
  1658. if pending_target is not None:
  1659. pending_slot = pending_target % 4
  1660. if pending_slot == parsed_tray_now:
  1661. # Slot matches our pending target - use the full global ID
  1662. logger.debug(
  1663. f"[{self.serial_number}] H2D tray_now disambiguation: "
  1664. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  1665. )
  1666. self.state.tray_now = pending_target
  1667. # Clear pending target now that load is confirmed
  1668. self.state.pending_tray_target = None
  1669. else:
  1670. # Slot doesn't match our pending target - something changed, use slot as-is
  1671. logger.warning(
  1672. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  1673. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  1674. )
  1675. self.state.tray_now = parsed_tray_now
  1676. # Clear pending target since it's stale
  1677. self.state.pending_tray_target = None
  1678. else:
  1679. # No pending target - use h2d_extruder_snow for accurate disambiguation
  1680. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  1681. active_ext = self.state.active_extruder # 0=right, 1=left
  1682. # Best source: use snow value from device.extruder.info if available
  1683. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  1684. if snow_tray is not None and snow_tray != 255:
  1685. # snow_tray is already normalized to global ID
  1686. # Verify the slot matches what we see in tray_now
  1687. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  1688. snow_slot = snow_tray % 4 if snow_tray < 128 else (0 if snow_tray <= 135 else -1)
  1689. if snow_slot == parsed_tray_now:
  1690. if self.state.tray_now != snow_tray:
  1691. logger.debug(
  1692. f"[{self.serial_number}] H2D tray_now from snow: "
  1693. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  1694. )
  1695. self.state.tray_now = snow_tray
  1696. else:
  1697. # Slot mismatch - snow field may not have updated yet, trust snow
  1698. logger.debug(
  1699. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  1700. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  1701. )
  1702. self.state.tray_now = snow_tray
  1703. else:
  1704. # Fallback: snow not available, use ams_extruder_map (less reliable)
  1705. # Find ALL AMS units on the active extruder
  1706. ams_on_extruder = []
  1707. for ams_id_str, ext_id in ams_map.items():
  1708. if ext_id == active_ext:
  1709. try:
  1710. ams_on_extruder.append(int(ams_id_str))
  1711. except ValueError:
  1712. pass # Skip AMS IDs that aren't valid integers
  1713. if len(ams_on_extruder) == 1:
  1714. # Single AMS on this extruder - unambiguous
  1715. active_ams_id = ams_on_extruder[0]
  1716. if 128 <= active_ams_id <= 135:
  1717. # AMS-HT: single slot per unit, global ID = unit ID
  1718. global_tray_id = active_ams_id
  1719. else:
  1720. global_tray_id = active_ams_id * 4 + parsed_tray_now
  1721. logger.debug(
  1722. f"[{self.serial_number}] H2D tray_now fallback: "
  1723. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  1724. )
  1725. self.state.tray_now = global_tray_id
  1726. elif len(ams_on_extruder) > 1:
  1727. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  1728. current_tray = self.state.tray_now
  1729. # Determine which AMS unit and slot the current tray belongs to
  1730. if 0 <= current_tray <= 15:
  1731. current_ams = current_tray // 4
  1732. current_slot = current_tray % 4
  1733. elif 128 <= current_tray <= 135:
  1734. current_ams = current_tray # AMS-HT: ID = tray ID
  1735. current_slot = 0
  1736. else:
  1737. current_ams = -1
  1738. current_slot = -1
  1739. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  1740. # Current is valid and matches slot - keep it
  1741. logger.debug(
  1742. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  1743. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  1744. )
  1745. else:
  1746. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  1747. if parsed_tray_now > 0:
  1748. candidates = [a for a in ams_on_extruder if a <= 3]
  1749. else:
  1750. candidates = ams_on_extruder
  1751. if len(candidates) == 1:
  1752. cand = candidates[0]
  1753. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  1754. logger.debug(
  1755. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  1756. f"narrowed to AMS {cand} -> global ID {resolved}"
  1757. )
  1758. self.state.tray_now = resolved
  1759. else:
  1760. # Genuinely ambiguous - use slot as-is (will be wrong for non-first AMS)
  1761. logger.warning(
  1762. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on extruder {active_ext}, "
  1763. f"no snow field, using slot {parsed_tray_now} (may be incorrect)"
  1764. )
  1765. self.state.tray_now = parsed_tray_now
  1766. else:
  1767. # No AMS on this extruder - use slot as-is
  1768. logger.warning(
  1769. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  1770. f"using slot {parsed_tray_now}"
  1771. )
  1772. self.state.tray_now = parsed_tray_now
  1773. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  1774. # Single-nozzle printer with tray_now in 0-3 range.
  1775. # #1822: H2S firmware reports tray_now as the AMS's idle
  1776. # slot (typically 0) when the active feed is actually the
  1777. # external spool. X1C / P1S / A1 correctly report 254 in
  1778. # that case; H2S does not. When the slicer-captured
  1779. # ams_mapping is all-external (every entry == -1), the
  1780. # print can only be feeding from the external spool, so
  1781. # promote tray_now to 254. Mixed (e.g. [5, -1]) and
  1782. # AMS-only mappings are NOT overridden — there's no
  1783. # evidence the firmware misreports in those cases. Prints
  1784. # started without a captured mapping (printer-screen start,
  1785. # or before Bambuddy connected) fall through unchanged.
  1786. captured = self._captured_ams_mapping
  1787. if captured and all(s == -1 for s in captured):
  1788. if self.state.tray_now != 254:
  1789. logger.debug(
  1790. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  1791. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  1792. )
  1793. self.state.tray_now = 254
  1794. else:
  1795. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  1796. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  1797. # (snow-encoded) to resolve the correct AMS unit.
  1798. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  1799. try:
  1800. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  1801. except (ValueError, TypeError):
  1802. ams_exist = 0
  1803. num_ams = bin(ams_exist).count("1")
  1804. if num_ams > 1:
  1805. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  1806. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  1807. mapping_raw = self.state.raw_data.get("mapping")
  1808. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  1809. if resolved is not None:
  1810. if resolved != parsed_tray_now:
  1811. logger.debug(
  1812. f"[{self.serial_number}] Multi-AMS tray_now: "
  1813. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  1814. )
  1815. self.state.tray_now = resolved
  1816. else:
  1817. # No mapping available (not printing, or ambiguous) — use as-is.
  1818. # This matches the old behavior and is correct for AMS 0.
  1819. self.state.tray_now = parsed_tray_now
  1820. else:
  1821. # Single AMS — local slot 0-3 equals global ID
  1822. self.state.tray_now = parsed_tray_now
  1823. else:
  1824. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  1825. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  1826. # During filament change, the printer sends 255 first (unload), then the slot.
  1827. # We only clear pending_tray_target explicitly in ams_unload_filament().
  1828. # Trust the printer's reported value.
  1829. self.state.tray_now = parsed_tray_now
  1830. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  1831. # Valid physical trays: 0-15 (regular AMS), 128-135 (AMS-HT), 254 (external spool)
  1832. tn = self.state.tray_now
  1833. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  1834. # Log tray change for mid-print usage splitting. Gate on the
  1835. # print-lifecycle flags (`_was_running` set on first RUNNING /
  1836. # new print, `_completion_triggered` set when on_print_complete
  1837. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  1838. # firmware briefly transitions out of RUNNING during AMS
  1839. # auto-fallback (#957), so a literal-string gate misses the
  1840. # switch and the usage tracker double-credits at completion.
  1841. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  1842. self.state.tray_change_log.append((tn, self.state.layer_num))
  1843. logger.info(
  1844. "[%s] Tray change during print: tray=%d at layer=%d",
  1845. self.serial_number,
  1846. tn,
  1847. self.state.layer_num,
  1848. )
  1849. self.state.last_loaded_tray = self.state.tray_now
  1850. self._debug_on_change(
  1851. "tray_now",
  1852. self.state.tray_now,
  1853. "[%s] tray_now updated: %s",
  1854. self.serial_number,
  1855. self.state.tray_now,
  1856. )
  1857. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  1858. # state when checking filament change mode for H2D disambiguation
  1859. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  1860. # We've already processed the status fields above, so just return if no ams list
  1861. if ams_list is None:
  1862. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  1863. return
  1864. elif isinstance(ams_data, list):
  1865. ams_list = ams_data
  1866. else:
  1867. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  1868. return
  1869. # Merge AMS data instead of replacing, to handle partial updates
  1870. # During prints, the printer may only send updates for active AMS units
  1871. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  1872. existing_ams = self.state.raw_data.get("ams", [])
  1873. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  1874. # Update existing units with new data, add new units
  1875. for ams_unit in ams_list:
  1876. ams_id = ams_unit.get("id")
  1877. if ams_id is not None:
  1878. existing_unit = existing_by_id.get(ams_id)
  1879. if existing_unit and "tray" in ams_unit:
  1880. # Deep merge trays to preserve fields from previous updates
  1881. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  1882. merged_trays = []
  1883. for new_tray in ams_unit.get("tray", []):
  1884. tray_id = new_tray.get("id")
  1885. if tray_id is not None and tray_id in existing_trays:
  1886. # Merge: start with existing, update with new non-empty values
  1887. merged_tray = existing_trays[tray_id].copy()
  1888. # Detect slot-clearing updates (spool removal):
  1889. # When tray_type is explicitly empty, clear everything
  1890. # including RFID data (tag_uid/tray_uuid).
  1891. slot_clearing = new_tray.get("tray_type") == ""
  1892. # Some printers (e.g. H2D) only send {id, state} in
  1893. # incremental updates when a tray is not fully loaded.
  1894. # state=11 means loaded; other values (9=empty,
  1895. # 10=spool present but filament not in feeder) indicate
  1896. # the slot should be cleared. Without this, old
  1897. # tray_type/tray_color persist indefinitely (#784).
  1898. tray_state = new_tray.get("state")
  1899. if (
  1900. tray_state is not None
  1901. and tray_state != 11
  1902. and "tray_type" not in new_tray
  1903. and merged_tray.get("tray_type")
  1904. ):
  1905. logger.info(
  1906. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  1907. self.serial_number,
  1908. ams_id,
  1909. tray_id,
  1910. tray_state,
  1911. )
  1912. slot_clearing = True
  1913. # The incremental update only has {id, state} — inject
  1914. # empty values for all content fields so the merge loop
  1915. # below clears the stale data from merged_tray.
  1916. new_tray.update(
  1917. {
  1918. "tray_type": "",
  1919. "tray_sub_brands": "",
  1920. "tray_color": "",
  1921. "tray_id_name": "",
  1922. "tray_info_idx": "",
  1923. "tag_uid": "0000000000000000",
  1924. "tray_uuid": "00000000000000000000000000000000",
  1925. "remain": 0,
  1926. "k": None,
  1927. "cali_idx": None,
  1928. }
  1929. )
  1930. for key, value in new_tray.items():
  1931. # Fields that should always be updated (even with empty/zero values):
  1932. # - remain, k, id, cali_idx: status indicators where 0 is valid
  1933. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  1934. # tray_id_name: slot content indicators that must be cleared
  1935. # when a spool is removed (fixes #147 - old AMS empty slot)
  1936. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  1937. # They are only cleared during spool removal (slot_clearing=True).
  1938. # Periodic AMS updates often include empty RFID fields which
  1939. # would overwrite valid data from the initial pushall.
  1940. always_update_fields = (
  1941. "remain",
  1942. "k",
  1943. "id",
  1944. "cali_idx",
  1945. "tray_type",
  1946. "tray_sub_brands",
  1947. "tray_info_idx",
  1948. "tray_color",
  1949. "tray_id_name",
  1950. )
  1951. if (
  1952. key in always_update_fields
  1953. or slot_clearing
  1954. or value
  1955. not in (
  1956. None,
  1957. "",
  1958. "0000000000000000",
  1959. "00000000000000000000000000000000",
  1960. )
  1961. ):
  1962. merged_tray[key] = value
  1963. merged_trays.append(merged_tray)
  1964. else:
  1965. merged_trays.append(new_tray)
  1966. # Update ams_unit with merged trays. Spread existing_unit
  1967. # FIRST so top-level fields the partial update omits —
  1968. # dry_time, info (which drives dry_status / dry_sub_status),
  1969. # humidity, temp — are preserved instead of dropped. The
  1970. # printer sends tray-bearing partials that carry no drying
  1971. # fields; without this, dry_time reads as absent → 0 and the
  1972. # falling-edge detector below fires a false "drying complete"
  1973. # (#1462). Mirrors the no-tray branch's merge semantics.
  1974. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  1975. elif existing_unit:
  1976. # Partial update without tray data: merge new fields into existing
  1977. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  1978. ams_unit = {**existing_unit, **ams_unit}
  1979. existing_by_id[ams_id] = ams_unit
  1980. # Convert back to list, sorted by ID for consistent ordering
  1981. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  1982. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  1983. # Shared with the VP bridge cache so the slicer-facing view stays in
  1984. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  1985. # for the full rationale and the printer-shutdown guard.
  1986. if isinstance(ams_data, dict):
  1987. apply_tray_exist_bits(
  1988. merged_ams,
  1989. ams_data.get("tray_exist_bits"),
  1990. power_on_flag=ams_data.get("power_on_flag", True),
  1991. log_label=self.serial_number,
  1992. annotate_exists=True,
  1993. )
  1994. self.state.raw_data["ams"] = merged_ams
  1995. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  1996. self._apply_ams_version_cache(merged_ams)
  1997. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  1998. self.state.last_ams_update = time.time()
  1999. self._debug_on_change(
  2000. "merged_ams",
  2001. (len(ams_list), len(merged_ams)),
  2002. "[%s] Merged AMS data: %s new units, %s total",
  2003. self.serial_number,
  2004. len(ams_list),
  2005. len(merged_ams),
  2006. )
  2007. # Extract ams_extruder_map from each AMS unit's info field
  2008. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  2009. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  2010. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  2011. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  2012. # extruder_id: 0=right/main, 1=left/deputy, 0xE=uninitialized (skip)
  2013. #
  2014. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  2015. # the full map. Merge into existing map to preserve entries from prior updates.
  2016. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  2017. for ams_unit in merged_ams:
  2018. ams_id = ams_unit.get("id")
  2019. info = ams_unit.get("info")
  2020. if ams_id is not None and info is not None:
  2021. try:
  2022. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  2023. info_val = int(str(info), 16)
  2024. # Extract 4 bits starting at bit 8 for extruder assignment
  2025. extruder_id = (info_val >> 8) & 0xF
  2026. if extruder_id == 0xE:
  2027. # 0xE = uninitialized AMS, skip
  2028. continue
  2029. ams_extruder_map[str(ams_id)] = extruder_id
  2030. self._debug_on_change(
  2031. f"ams_info:{ams_id}",
  2032. (info, extruder_id),
  2033. "[%s] AMS %s info=0x%s -> extruder %s",
  2034. self.serial_number,
  2035. ams_id,
  2036. info,
  2037. extruder_id,
  2038. )
  2039. except (ValueError, TypeError):
  2040. pass # Skip AMS units with unparseable info bitmask values
  2041. if ams_extruder_map:
  2042. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  2043. self.state.ams_extruder_map = ams_extruder_map
  2044. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  2045. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  2046. # BambuStudio DevFilaSystem.cpp parses info bits:
  2047. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  2048. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  2049. for ams_unit in merged_ams:
  2050. info = ams_unit.get("info")
  2051. if info is not None:
  2052. try:
  2053. info_val = int(str(info), 16)
  2054. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  2055. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  2056. except (ValueError, TypeError):
  2057. pass # Skip unparseable info values
  2058. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  2059. if "dry_sf_reason" in ams_unit:
  2060. sf_reason = ams_unit["dry_sf_reason"]
  2061. if isinstance(sf_reason, list):
  2062. ams_unit["dry_sf_reason"] = [
  2063. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  2064. ]
  2065. else:
  2066. ams_unit["dry_sf_reason"] = []
  2067. # Persist updated drying fields back to raw_data
  2068. self.state.raw_data["ams"] = merged_ams
  2069. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  2070. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  2071. # — fire the callback so smart-plug auto-off-after-drying can run,
  2072. # and drop our cached target-cycle params so the badge stops claiming
  2073. # an active cycle. Works identically for queue-triggered, ambient,
  2074. # and manual drying because we observe the firmware-reported state.
  2075. for ams_unit in merged_ams:
  2076. try:
  2077. ams_id = int(ams_unit.get("id", -1))
  2078. except (TypeError, ValueError):
  2079. continue
  2080. if ams_id < 0:
  2081. continue
  2082. # Only evaluate the edge when this update carries an explicit
  2083. # dry_time. An absent / unparseable value is NOT zero — treating
  2084. # it as 0 lets a tray-only partial fake a drying-complete edge
  2085. # (#1462). Skip without touching the remembered value so the
  2086. # next update that DOES carry dry_time sees the true previous.
  2087. raw_dry_time = ams_unit.get("dry_time")
  2088. if raw_dry_time is None:
  2089. continue
  2090. try:
  2091. current = int(raw_dry_time)
  2092. except (TypeError, ValueError):
  2093. continue
  2094. previous = self._previous_dry_times.get(ams_id, 0)
  2095. self._previous_dry_times[ams_id] = current
  2096. if previous > 0 and current == 0:
  2097. logger.info(
  2098. "[%s] AMS %d drying complete (dry_time %d → 0)",
  2099. self.serial_number,
  2100. ams_id,
  2101. previous,
  2102. )
  2103. self._drying_targets.pop(ams_id, None)
  2104. if self.on_drying_complete:
  2105. self.on_drying_complete(ams_id)
  2106. # Create a hash of relevant AMS data to detect changes
  2107. ams_hash_data = []
  2108. for ams_unit in ams_list:
  2109. for tray in ams_unit.get("tray", []):
  2110. # Include fields that matter for filament tracking
  2111. ams_hash_data.append(
  2112. f"{ams_unit.get('id')}:{tray.get('id')}:"
  2113. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  2114. )
  2115. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  2116. # Only trigger callback if AMS data actually changed
  2117. if ams_hash != self._previous_ams_hash:
  2118. self._previous_ams_hash = ams_hash
  2119. if self.on_ams_change:
  2120. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  2121. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  2122. # may lack fields like 'remain' that the merged state preserves
  2123. self.on_ams_change(merged_ams)
  2124. def _update_state(self, data: dict):
  2125. """Update printer state from message data."""
  2126. _previous_state = self.state.state
  2127. # Update state fields
  2128. if "gcode_state" in data:
  2129. self.state.state = data["gcode_state"]
  2130. if "gcode_file" in data:
  2131. self.state.gcode_file = data["gcode_file"]
  2132. self.state.current_print = data["gcode_file"]
  2133. if "subtask_name" in data:
  2134. self.state.subtask_name = data["subtask_name"]
  2135. # Prefer subtask_name as current_print if available
  2136. if data["subtask_name"]:
  2137. self.state.current_print = data["subtask_name"]
  2138. if "subtask_id" in data:
  2139. self.state.subtask_id = data["subtask_id"]
  2140. if "mc_percent" in data:
  2141. # Save last non-zero progress for usage tracking (firmware resets to 0 on cancel)
  2142. if self.state.progress > 0:
  2143. self._last_valid_progress = self.state.progress
  2144. self.state.progress = float(data["mc_percent"])
  2145. if "mc_remaining_time" in data:
  2146. self.state.remaining_time = int(data["mc_remaining_time"])
  2147. if "mc_print_sub_stage" in data:
  2148. new_sub_stage = int(data["mc_print_sub_stage"])
  2149. if new_sub_stage != self.state.mc_print_sub_stage:
  2150. logger.debug(
  2151. f"[{self.serial_number}] mc_print_sub_stage changed: "
  2152. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  2153. )
  2154. self.state.mc_print_sub_stage = new_sub_stage
  2155. if "layer_num" in data:
  2156. new_layer = int(data["layer_num"])
  2157. old_layer = self.state.layer_num
  2158. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  2159. if old_layer > 0:
  2160. self._last_valid_layer_num = old_layer
  2161. self.state.layer_num = new_layer
  2162. # Trigger layer change callback if layer increased
  2163. if new_layer > old_layer and self.on_layer_change:
  2164. self.on_layer_change(new_layer)
  2165. # #1867 last-layer finish-photo trigger. A1 Mini (and other
  2166. # firmware variants) skips `stg_cur=22`, so the fallback fires
  2167. # at gcode_state=FINISH — which runs AFTER user End G-code
  2168. # (e.g. SwapMod plate-swap) and captures the wrong plate.
  2169. # Firing on the layer_num→total_layer_num edge captures the
  2170. # last object layer before any end G-code executes.
  2171. total = self.state.total_layers or 0
  2172. if (
  2173. total > 0
  2174. and new_layer >= total
  2175. and old_layer < total
  2176. and self._was_running
  2177. and not self._finish_photo_captured
  2178. and self.on_finish_photo_moment
  2179. ):
  2180. self._finish_photo_captured = True
  2181. logger.info(
  2182. f"[{self.serial_number}] FINISH PHOTO MOMENT (last-layer) — "
  2183. f"layer={new_layer}/{total}, "
  2184. f"timelapse_active={self._timelapse_during_print}"
  2185. )
  2186. self.on_finish_photo_moment(
  2187. {
  2188. "trigger": "last_layer",
  2189. "filename": self._previous_gcode_file or self.state.gcode_file,
  2190. "subtask_name": self.state.subtask_name,
  2191. "timelapse_was_active": self._timelapse_during_print,
  2192. }
  2193. )
  2194. if "total_layer_num" in data:
  2195. # Some firmware (P1S observed) resets `total_layer_num` to 0 at
  2196. # print end — same shape as the `layer_num` reset guarded above.
  2197. # Preserve the last known good value so the usage-tracker split
  2198. # path (#1771) has a denominator that survives the reset frame.
  2199. # Explicit reset to 0 happens on print start (`_handle_print_start`).
  2200. new_total = int(data["total_layer_num"])
  2201. if new_total > 0:
  2202. self.state.total_layers = new_total
  2203. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  2204. # Convert to 0-100 percentage for display
  2205. def parse_fan_speed(value: str | int | None) -> int | None:
  2206. if value is None:
  2207. return None
  2208. try:
  2209. speed = int(value)
  2210. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  2211. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  2212. if speed <= 15:
  2213. return round(speed * 100 / 15)
  2214. # If already a percentage (0-255 scale from some printers), convert
  2215. elif speed <= 255:
  2216. return round(speed * 100 / 255)
  2217. return speed
  2218. except (ValueError, TypeError):
  2219. return None
  2220. # Log fan fields once for debugging
  2221. if not hasattr(self, "_fan_fields_logged"):
  2222. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  2223. if fan_fields:
  2224. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  2225. self._fan_fields_logged = True
  2226. if "cooling_fan_speed" in data:
  2227. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  2228. if "big_fan1_speed" in data:
  2229. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  2230. if "big_fan2_speed" in data:
  2231. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  2232. if "heatbreak_fan_speed" in data:
  2233. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  2234. # Calibration stage tracking
  2235. if "stg_cur" in data:
  2236. new_stg = data["stg_cur"]
  2237. prev_stg = self.state.stg_cur
  2238. # Always log ANY stg_cur change for debugging filament operations
  2239. if new_stg != prev_stg:
  2240. logger.debug(
  2241. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  2242. )
  2243. self.state.stg_cur = new_stg
  2244. # #1721 end-of-print finish photo trigger.
  2245. # Stage 22 = "Filament unloading" fires at end-of-print AND
  2246. # during mid-print color swaps. The end-of-print gate
  2247. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  2248. # — those signals only line up at the real end. Edge-only
  2249. # (prev != 22) so the trigger fires once per stage entry.
  2250. if (
  2251. new_stg == 22
  2252. and prev_stg != 22
  2253. and self._was_running
  2254. and not self._finish_photo_captured
  2255. and self.on_finish_photo_moment
  2256. ):
  2257. progress = self.state.progress or 0.0
  2258. layer_num = self.state.layer_num or 0
  2259. total_layers = self.state.total_layers or 0
  2260. remaining = self.state.remaining_time or 0
  2261. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  2262. if is_end_of_print:
  2263. self._finish_photo_captured = True
  2264. logger.info(
  2265. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  2266. f"progress={progress}, layer={layer_num}/{total_layers}, "
  2267. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  2268. )
  2269. self.on_finish_photo_moment(
  2270. {
  2271. "trigger": "stage_22",
  2272. "filename": self._previous_gcode_file or self.state.gcode_file,
  2273. "subtask_name": self.state.subtask_name,
  2274. "timelapse_was_active": self._timelapse_during_print,
  2275. }
  2276. )
  2277. if "stg" in data:
  2278. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  2279. # Temperature data
  2280. temps = {}
  2281. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  2282. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  2283. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  2284. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  2285. # Log ALL keys in print data for H2D temperature discovery
  2286. all_keys = sorted(data.keys())
  2287. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  2288. self._temp_fields_logged = True
  2289. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  2290. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  2291. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  2292. self._vir_slot_logged = True
  2293. # Log nozzle hardware info fields (once)
  2294. nozzle_fields = {
  2295. k: v
  2296. for k, v in data.items()
  2297. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  2298. }
  2299. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  2300. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  2301. self._nozzle_fields_logged = True
  2302. # Parse active extruder from device.extruder.state bit 8
  2303. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  2304. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  2305. if "device" in data and isinstance(data.get("device"), dict):
  2306. device = data["device"]
  2307. # One-shot identification probe: surface whatever the firmware uses to
  2308. # name itself so an unknown model in a support bundle becomes self-
  2309. # diagnosing. INFO level so it shows up without debug logging. Falls
  2310. # back to dumping device.keys() if none of the known fields are present
  2311. # (so a future Bambu rename like `model_name` is still observable).
  2312. if not getattr(self, "_device_id_logged", False):
  2313. id_fields = {
  2314. k: device.get(k)
  2315. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  2316. if k in device
  2317. }
  2318. if id_fields:
  2319. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  2320. else:
  2321. logger.info(
  2322. "[%s] Device identification: no known id fields; device.keys=%s",
  2323. self.serial_number,
  2324. sorted(device.keys()),
  2325. )
  2326. self._device_id_logged = True
  2327. if "extruder" in device and "state" in device["extruder"]:
  2328. state_val = device["extruder"]["state"]
  2329. # Extract bit 8 for extruder position
  2330. new_extruder = (state_val >> 8) & 0x1
  2331. if new_extruder != self.state.active_extruder:
  2332. logger.debug(
  2333. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  2334. )
  2335. self.state.active_extruder = new_extruder
  2336. # Log device.extruder structure for active extruder
  2337. if "device" in data and isinstance(data.get("device"), dict):
  2338. device = data["device"]
  2339. if "extruder" in device:
  2340. ext_data = device["extruder"]
  2341. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  2342. if "state" in ext_data:
  2343. state_val = ext_data["state"]
  2344. # Extract bits 12-14 (3 bits) for switch state
  2345. switch_state = (state_val >> 12) & 0x7
  2346. self._debug_on_change(
  2347. "extruder_state",
  2348. state_val,
  2349. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  2350. self.serial_number,
  2351. state_val,
  2352. switch_state,
  2353. )
  2354. # Log 'cur' field if present (might indicate current/active extruder)
  2355. if "cur" in ext_data:
  2356. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  2357. # Filament Track Switch (FTS) detection — #1162. Presence of
  2358. # device.fila_switch in MQTT means the FTS accessory is installed.
  2359. if "device" in data and isinstance(data.get("device"), dict):
  2360. fs_data = data["device"].get("fila_switch")
  2361. if isinstance(fs_data, dict):
  2362. in_raw = fs_data.get("in")
  2363. out_raw = fs_data.get("out")
  2364. self.state.fila_switch = FilaSwitchState(
  2365. installed=True,
  2366. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2367. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2368. stat=int(fs_data.get("stat", 0) or 0),
  2369. info=int(fs_data.get("info", 0) or 0),
  2370. )
  2371. if "bed_temper" in data:
  2372. temps["bed"] = float(data["bed_temper"])
  2373. if "bed_target_temper" in data:
  2374. temps["bed_target"] = float(data["bed_target_temper"])
  2375. # Check if this is H2D (has device.extruder.info with 2 extruders)
  2376. has_h2d_extruder_info = (
  2377. "device" in data
  2378. and isinstance(data.get("device"), dict)
  2379. and "extruder" in data["device"]
  2380. and isinstance(data["device"]["extruder"].get("info"), list)
  2381. and len(data["device"]["extruder"]["info"]) >= 2
  2382. )
  2383. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  2384. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  2385. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  2386. if "nozzle_temper" in data:
  2387. if has_h2d_extruder_info:
  2388. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  2389. else:
  2390. temps["nozzle"] = float(data["nozzle_temper"])
  2391. if "nozzle_target_temper" in data:
  2392. if has_h2d_extruder_info:
  2393. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  2394. else:
  2395. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  2396. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  2397. if not has_h2d_extruder_info:
  2398. # Try multiple possible field names used by different firmware versions
  2399. if "nozzle_temper_2" in data:
  2400. val = float(data["nozzle_temper_2"])
  2401. if -50 < val < 500: # Valid temp range
  2402. temps["nozzle_2"] = val
  2403. else:
  2404. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  2405. elif "right_nozzle_temper" in data:
  2406. val = float(data["right_nozzle_temper"])
  2407. if -50 < val < 500: # Valid temp range
  2408. temps["nozzle_2"] = val
  2409. else:
  2410. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  2411. if "nozzle_target_temper_2" in data:
  2412. val = float(data["nozzle_target_temper_2"])
  2413. if 0 <= val < 500: # Valid temp range
  2414. temps["nozzle_2_target"] = val
  2415. else:
  2416. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  2417. elif "right_nozzle_target_temper" in data:
  2418. val = float(data["right_nozzle_target_temper"])
  2419. if 0 <= val < 500: # Valid temp range
  2420. temps["nozzle_2_target"] = val
  2421. else:
  2422. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  2423. # Also check for left nozzle as primary (some H2 models)
  2424. if "left_nozzle_temper" in data and "nozzle" not in temps:
  2425. temps["nozzle"] = float(data["left_nozzle_temper"])
  2426. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  2427. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  2428. if "chamber_temper" in data:
  2429. chamber_val = float(data["chamber_temper"])
  2430. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  2431. # Check if we recently set the target locally (within 5 seconds)
  2432. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2433. respect_local = (time.time() - local_set_time) < 5.0
  2434. # H2D protocol: chamber_temper encoding indicates heater state
  2435. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  2436. # - When < 500: direct Celsius current temp only - heater is OFF
  2437. if -50 < chamber_val < 100:
  2438. # Direct value = heater is OFF
  2439. temps["chamber"] = chamber_val
  2440. if not respect_local:
  2441. temps["chamber_target"] = 0.0 # Heater off means target = 0
  2442. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  2443. else:
  2444. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  2445. # Try to decode if it looks like an encoded value
  2446. if chamber_val > 500:
  2447. mqtt_target = int(chamber_val) // 65536
  2448. current = int(chamber_val) % 65536
  2449. logger.debug(
  2450. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  2451. )
  2452. if -50 < current < 100:
  2453. temps["chamber"] = float(current)
  2454. # Store decoded target for later use, but DON'T set chamber_heating here!
  2455. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  2456. # which is the authoritative source the slicer uses.
  2457. if not respect_local:
  2458. if 0 <= mqtt_target <= 60:
  2459. # Store as "decoded" target - may be overridden by explicit target fields
  2460. temps["_chamber_decoded_target"] = float(mqtt_target)
  2461. # Chamber target temperature (set by print file or display)
  2462. if "mc_target_cham" in data:
  2463. mc_target = float(data["mc_target_cham"])
  2464. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  2465. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  2466. if 0 <= mc_target <= 60:
  2467. temps["chamber_target"] = mc_target
  2468. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  2469. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  2470. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  2471. try:
  2472. if "info" in data and isinstance(data["info"], dict):
  2473. info_temp = data["info"].get("temp")
  2474. if info_temp is not None and "chamber" not in temps:
  2475. # Check for encoded value (target * 65536 + current)
  2476. if info_temp > 500:
  2477. # Decode: extract current temperature and target
  2478. target = info_temp // 65536
  2479. current = info_temp % 65536
  2480. temps["chamber"] = float(current)
  2481. # Store decoded target as fallback (may be overridden by ctc.info.target)
  2482. if "_chamber_decoded_target" not in temps:
  2483. temps["_chamber_decoded_target"] = float(target)
  2484. logger.debug(
  2485. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  2486. )
  2487. elif -50 < info_temp < 100:
  2488. # Valid direct temperature - heater is OFF
  2489. temps["chamber"] = float(info_temp)
  2490. temps["chamber_target"] = 0.0 # Direct value means heater off
  2491. self._debug_on_change(
  2492. "info_temp_direct",
  2493. info_temp,
  2494. "[%s] info.temp direct: %s°C (heater OFF)",
  2495. self.serial_number,
  2496. info_temp,
  2497. )
  2498. # H2D series: Dual extruder temps are in device.extruder.info array
  2499. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  2500. if "device" in data and isinstance(data["device"], dict):
  2501. device = data["device"]
  2502. # Parse dual extruder temperatures
  2503. extruder_data = device.get("extruder", {})
  2504. extruder_info = extruder_data.get("info", [])
  2505. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  2506. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  2507. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  2508. # has_h2d_extruder_info requires len(extruder_info) >= 2
  2509. if has_h2d_extruder_info:
  2510. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  2511. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  2512. if "temp" in extruder_info[0]:
  2513. temp_val = extruder_info[0]["temp"]
  2514. if temp_val > 500:
  2515. # Encoded format: temp = target * 65536 + current
  2516. target = temp_val // 65536
  2517. current = temp_val % 65536
  2518. if -50 < current < 500:
  2519. temps["nozzle_2"] = float(current)
  2520. if 0 < target < 500:
  2521. temps["nozzle_2_target"] = float(target)
  2522. temps["nozzle_2_heating"] = target > 0 and current < target
  2523. elif -50 < temp_val < 500:
  2524. # Direct Celsius value = heater is OFF
  2525. temps["nozzle_2"] = float(temp_val)
  2526. temps["nozzle_2_target"] = 0.0
  2527. temps["nozzle_2_heating"] = False
  2528. # Left nozzle (extruder 1) - only for dual nozzle printers
  2529. # H2D protocol: temp field encoding depends on value
  2530. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  2531. # - When < 500: direct Celsius current temp only - heater is OFF
  2532. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  2533. ext1 = extruder_info[1]
  2534. temp_val = ext1["temp"]
  2535. # Check if we recently set the target locally (within 5 seconds)
  2536. # If so, don't let MQTT data overwrite it
  2537. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  2538. respect_local_target = (time.time() - local_set_time) < 5.0
  2539. if temp_val > 500:
  2540. # Encoded format: temp = target * 65536 + current
  2541. target = temp_val // 65536
  2542. current = temp_val % 65536
  2543. if 0 < target < 500 and not respect_local_target:
  2544. temps["nozzle_target"] = float(target)
  2545. if -50 < current < 500:
  2546. temps["nozzle"] = float(current)
  2547. # Heating = encoded AND we're using the MQTT target (not local override)
  2548. # If local target is being respected, use local target to determine heating
  2549. if respect_local_target:
  2550. local_target = self.state.temperatures.get("nozzle_target", 0)
  2551. temps["nozzle_heating"] = local_target > 0 and current < local_target
  2552. else:
  2553. temps["nozzle_heating"] = target > 0 and current < target
  2554. elif -50 < temp_val < 500:
  2555. # Direct Celsius = heater is OFF (or at target with heater off)
  2556. temps["nozzle"] = float(temp_val)
  2557. if not respect_local_target:
  2558. temps["nozzle_target"] = 0.0
  2559. temps["nozzle_heating"] = False # Direct = not heating
  2560. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  2561. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  2562. if has_h2d_extruder_info:
  2563. for ext_info in extruder_info:
  2564. ext_id = ext_info.get("id")
  2565. snow = ext_info.get("snow")
  2566. if ext_id is not None and snow is not None and ext_id <= 1:
  2567. # Normalize H2D snow value to global tray ID
  2568. ams_id = snow >> 8
  2569. slot = snow & 0xFF
  2570. if 0 <= ams_id <= 3:
  2571. # Regular AMS slot
  2572. global_tray = ams_id * 4 + (slot & 0x03)
  2573. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2574. if old_val != global_tray:
  2575. logger.debug(
  2576. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2577. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  2578. )
  2579. self.state.h2d_extruder_snow[ext_id] = global_tray
  2580. elif ams_id == 254 or ams_id == 255:
  2581. # External spool or unloaded
  2582. normalized = 254 if slot != 255 else 255
  2583. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2584. if old_val != normalized:
  2585. logger.debug(
  2586. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2587. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  2588. )
  2589. self.state.h2d_extruder_snow[ext_id] = normalized
  2590. elif 128 <= ams_id <= 135:
  2591. # External spool with hub mapping
  2592. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2593. if old_val != ams_id:
  2594. logger.debug(
  2595. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2596. f"raw={snow} -> external hub {ams_id}"
  2597. )
  2598. self.state.h2d_extruder_snow[ext_id] = ams_id
  2599. # Parse bed heating state from device.bed.info.temp encoding
  2600. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  2601. bed_data = device.get("bed", {})
  2602. bed_info = bed_data.get("info", {})
  2603. if "temp" in bed_info:
  2604. temp_val = bed_info["temp"]
  2605. if temp_val > 500:
  2606. target = temp_val // 65536
  2607. current = temp_val % 65536
  2608. temps["bed_heating"] = target > 0 and current < target
  2609. else:
  2610. temps["bed_heating"] = False
  2611. # Parse chamber temp from device.ctc.info.temp if not already set
  2612. ctc_data = device.get("ctc", {})
  2613. ctc_info = ctc_data.get("info", {})
  2614. # Parse airduct mode (0=cooling, 1=heating)
  2615. airduct_data = device.get("airduct", {})
  2616. if "modeCur" in airduct_data:
  2617. new_mode = airduct_data["modeCur"]
  2618. if new_mode != self.state.airduct_mode:
  2619. logger.debug(
  2620. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  2621. )
  2622. self.state.airduct_mode = new_mode
  2623. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  2624. # Check if we recently set the target locally (within 5 seconds)
  2625. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2626. respect_local_target = (time.time() - local_set_time) < 5.0
  2627. # Log ctc_info contents for debugging
  2628. if ctc_info:
  2629. self._debug_on_change(
  2630. "ctc_info_keys",
  2631. tuple(ctc_info.keys()),
  2632. "[%s] ctc_info keys: %s",
  2633. self.serial_number,
  2634. list(ctc_info.keys()),
  2635. )
  2636. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  2637. # (what the slicer shows). This OVERRIDES any previously decoded target.
  2638. explicit_target = None
  2639. if "target" in ctc_info:
  2640. target_val = ctc_info["target"]
  2641. logger.debug(
  2642. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  2643. )
  2644. # Filter out invalid values (valid chamber target is 0-60°C)
  2645. if 0 <= target_val <= 60 and not respect_local_target:
  2646. explicit_target = float(target_val)
  2647. temps["chamber_target"] = explicit_target # Override any previous value
  2648. logger.debug(
  2649. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  2650. )
  2651. # Parse chamber temp from ctc.info.temp - may be encoded
  2652. if "temp" in ctc_info and "chamber" not in temps:
  2653. temp_val = ctc_info["temp"]
  2654. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  2655. if temp_val > 500:
  2656. # Encoded value: decode target and current
  2657. decoded_target = temp_val // 65536
  2658. current = temp_val % 65536
  2659. temps["chamber"] = float(current)
  2660. logger.debug(
  2661. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  2662. )
  2663. # Determine which target to use for heating state:
  2664. # Priority: local target > explicit target > decoded target
  2665. if respect_local_target:
  2666. local_target = self.state.temperatures.get("chamber_target", 0)
  2667. temps["chamber_heating"] = local_target > 0 and current < local_target
  2668. elif explicit_target is not None:
  2669. # Use explicit ctc.info.target - this is what slicer sees
  2670. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  2671. else:
  2672. # Fallback to decoded target only if no explicit target available
  2673. if not respect_local_target and "chamber_target" not in temps:
  2674. temps["chamber_target"] = float(decoded_target)
  2675. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  2676. else:
  2677. # Direct value (not encoded) - heater is OFF
  2678. temps["chamber"] = float(temp_val)
  2679. temps["chamber_heating"] = False
  2680. except Exception as e:
  2681. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  2682. if temps:
  2683. # Handle chamber_target: prefer explicit over decoded
  2684. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  2685. # No explicit target available, use decoded target from chamber_temper
  2686. temps["chamber_target"] = temps["_chamber_decoded_target"]
  2687. # Remove internal temp key before merging
  2688. temps.pop("_chamber_decoded_target", None)
  2689. # Merge new temps into existing, preserving valid values when new ones are filtered out
  2690. for key, value in temps.items():
  2691. self.state.temperatures[key] = value
  2692. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  2693. if "bed" in temps and self.on_bed_temp_update:
  2694. self.on_bed_temp_update(temps["bed"])
  2695. # Calculate chamber_heating after all targets are known
  2696. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  2697. if "chamber" in temps and "chamber_heating" not in temps:
  2698. current = self.state.temperatures.get("chamber", 0)
  2699. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2700. respect_local = (time.time() - local_set_time) < 5.0
  2701. if respect_local:
  2702. # Use locally-set target
  2703. target = self.state.temperatures.get("chamber_target", 0)
  2704. else:
  2705. # Use explicit/decoded target from MQTT
  2706. target = self.state.temperatures.get("chamber_target", 0)
  2707. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  2708. self._debug_on_change(
  2709. "chamber_heating",
  2710. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  2711. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  2712. self.serial_number,
  2713. target,
  2714. current,
  2715. self.state.temperatures["chamber_heating"],
  2716. respect_local,
  2717. )
  2718. # Debug: log chamber value if it was updated
  2719. if "chamber" in temps:
  2720. self._debug_on_change(
  2721. "chamber_temp",
  2722. (
  2723. self.state.temperatures.get("chamber"),
  2724. self.state.temperatures.get("chamber_target"),
  2725. self.state.temperatures.get("chamber_heating"),
  2726. ),
  2727. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  2728. self.serial_number,
  2729. self.state.temperatures.get("chamber"),
  2730. self.state.temperatures.get("chamber_target"),
  2731. self.state.temperatures.get("chamber_heating"),
  2732. )
  2733. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  2734. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  2735. if "nozzle" in temps and "nozzle_heating" not in temps:
  2736. current = self.state.temperatures.get("nozzle", 0)
  2737. target = self.state.temperatures.get("nozzle_target", 0)
  2738. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  2739. # Parse HMS (Health Management System) errors
  2740. if "hms" in data:
  2741. hms_list = data["hms"]
  2742. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  2743. self.state.hms_errors = []
  2744. if isinstance(hms_list, list):
  2745. for hms in hms_list:
  2746. if isinstance(hms, dict):
  2747. # HMS format: {"attr": attribute_code, "code": error_code}
  2748. # attr contains module/severity info, code contains error number
  2749. # Both are needed to construct the wiki URL
  2750. attr = hms.get("attr", 0)
  2751. code = hms.get("code", 0)
  2752. if isinstance(attr, str):
  2753. attr = int(attr.replace("0x", ""), 16) if attr else 0
  2754. if isinstance(code, str):
  2755. code = int(code.replace("0x", ""), 16) if code else 0
  2756. # Severity is in attr byte 1 (bits 8-15)
  2757. severity = (attr >> 8) & 0xF
  2758. # Module is in attr byte 3 (bits 24-31)
  2759. module = (attr >> 24) & 0xFF
  2760. # Skip non-error status codes — all real HMS errors
  2761. # have code >= 0x4000. Lower values are status/phase
  2762. # indicators that some firmware sends during normal printing.
  2763. if code < 0x4000:
  2764. continue
  2765. # Skip user-action echoes — the printer firmware emits these
  2766. # as part of normal user-cancel sequences. They're not faults
  2767. # and shouldn't count toward "X problem" badges or surface as
  2768. # red pips on the printer card. Backend's notification path
  2769. # already suppresses 0500_400E for the same reason.
  2770. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  2771. if short_code in _HMS_USER_ACTION_CODES:
  2772. continue
  2773. # Catalog has both 8-char keys (base class) and 16-char keys
  2774. # (specific variants). The full 16-char identifier preserves
  2775. # the 32 bits of `attr_low` + `code_high` that the short_code
  2776. # discards — that's the firmware's matching key, so try it
  2777. # first and fall back to the short form.
  2778. full_code = f"{attr:08X}{code:08X}"
  2779. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  2780. if not actions:
  2781. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  2782. self.state.hms_errors.append(
  2783. HMSError(
  2784. code=f"0x{code:x}" if code else "0x0",
  2785. attr=attr,
  2786. module=module,
  2787. severity=severity if severity > 0 else 2,
  2788. actions=actions,
  2789. job_id=self.state.subtask_id,
  2790. full_code=full_code,
  2791. )
  2792. )
  2793. # Parse print_error - this is a different error format than HMS
  2794. # print_error is a 32-bit integer where:
  2795. # - High 16 bits contain module info (e.g., 0x0500)
  2796. # - Low 16 bits contain error code (e.g., 0x8061)
  2797. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  2798. if "print_error" in data:
  2799. print_error = data["print_error"]
  2800. if print_error and print_error != 0:
  2801. # Extract components: MMMMEEEE -> MMMM_EEEE
  2802. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  2803. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  2804. # Values below 0x4000 are status/phase indicators, not real errors.
  2805. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  2806. # Some firmware sends low values like 0x0002 during normal printing.
  2807. if error < 0x4000:
  2808. pass # Skip — not a real error
  2809. else:
  2810. # Store in a format that matches the community error database
  2811. # attr stores the full 32-bit value for reconstruction
  2812. # code stores the short format string for lookup
  2813. short_code = f"{module:04X}_{error:04X}"
  2814. logger.debug(
  2815. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  2816. )
  2817. # Same user-action filter as the hms[] branch above — print_error
  2818. # carries the same cancel echoes (e.g. 0500_400E) and they must
  2819. # not surface as faults on the printer card.
  2820. if short_code in _HMS_USER_ACTION_CODES:
  2821. pass # cancel echo — silently drop
  2822. else:
  2823. # Only add if not already in HMS errors (avoid duplicates)
  2824. existing_short_codes = set()
  2825. for e in self.state.hms_errors:
  2826. # Extract short code from existing errors
  2827. e_module = (e.attr >> 16) & 0xFFFF
  2828. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  2829. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  2830. if short_code not in existing_short_codes:
  2831. # Bambu's HMS catalog keys by 3-letter device code (the SN
  2832. # prefix) and a 16-char short error code without the
  2833. # underscore separator we store internally.
  2834. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  2835. # Bambu pushes the current job as `subtask_id` on the
  2836. # state stream; the HMS-action commands echo it back as
  2837. # `job_id`. The error payload itself doesn't carry the
  2838. # id, so snapshot it from the live state at parse time
  2839. # and freeze it on the HMSError so subsequent
  2840. # job changes don't invalidate the action.
  2841. job_id = self.state.subtask_id
  2842. logger.debug(
  2843. "[%s, %s] HMS available actions: %s (job_id=%s)",
  2844. self.serial_number[:3],
  2845. short_code.replace("_", ""),
  2846. actions,
  2847. job_id,
  2848. )
  2849. self.state.hms_errors.append(
  2850. HMSError(
  2851. code=f"0x{error:x}",
  2852. attr=print_error, # Store full value for display
  2853. module=module >> 8, # High byte of module (e.g., 0x05)
  2854. severity=3, # Warning level for print_error
  2855. actions=actions,
  2856. job_id=job_id,
  2857. # print_error is already 32-bit — `f"{print_error:08X}"`
  2858. # is the firmware's matching key with no truncation.
  2859. full_code=f"{print_error:08X}",
  2860. )
  2861. )
  2862. # Parse home_flag first so SD-card detection below can prefer it.
  2863. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  2864. # bit 23 = door-open (X1 family only).
  2865. home_flag = None
  2866. if "home_flag" in data:
  2867. home_flag = data["home_flag"]
  2868. if home_flag < 0:
  2869. home_flag = home_flag & 0xFFFFFFFF
  2870. # SD card presence: the only remaining consumer is the firmware-update
  2871. # precondition check (firmware_update.py). Use the top-level `sdcard`
  2872. # field when present with a permissive truthy check covering the
  2873. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  2874. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  2875. # when a card is inserted, which caused the badge to flap before the
  2876. # badge was removed entirely.
  2877. if "sdcard" in data:
  2878. raw_sdcard = data["sdcard"]
  2879. if isinstance(raw_sdcard, str):
  2880. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  2881. else:
  2882. self.state.sdcard = bool(raw_sdcard)
  2883. if home_flag is not None:
  2884. store_to_sdcard = bool((home_flag >> 11) & 1)
  2885. if store_to_sdcard != self.state.store_to_sdcard:
  2886. logger.debug(
  2887. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  2888. )
  2889. self.state.store_to_sdcard = store_to_sdcard
  2890. # Door open detection — source depends on printer family:
  2891. # X1 series (X1, X1C, X1E): home_flag bit 23
  2892. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  2893. # Both share the same bitmask (0x00800000) but live in different fields.
  2894. model_upper = (self.model or "").upper().strip()
  2895. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  2896. if is_x1_family and home_flag is not None:
  2897. door_open = (home_flag & 0x00800000) != 0
  2898. if door_open != self.state.door_open:
  2899. logger.debug(
  2900. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  2901. self.serial_number,
  2902. self.state.door_open,
  2903. door_open,
  2904. home_flag,
  2905. )
  2906. self.state.door_open = door_open
  2907. elif not is_x1_family and "stat" in data:
  2908. try:
  2909. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  2910. door_open = (stat_value & 0x00800000) != 0
  2911. if door_open != self.state.door_open:
  2912. logger.debug(
  2913. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  2914. self.serial_number,
  2915. self.state.door_open,
  2916. door_open,
  2917. stat_value,
  2918. )
  2919. self.state.door_open = door_open
  2920. except (ValueError, TypeError):
  2921. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  2922. # Parse timelapse status (recording active during print)
  2923. if "timelapse" in data:
  2924. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  2925. self.state.timelapse = data["timelapse"] is True
  2926. # Track if timelapse was ever active during this print
  2927. if self.state.timelapse and self._was_running:
  2928. self._timelapse_during_print = True
  2929. # Parse ipcam/live view status
  2930. if "ipcam" in data:
  2931. ipcam_data = data["ipcam"]
  2932. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  2933. if isinstance(ipcam_data, dict):
  2934. # Check ipcam_record field for live view status
  2935. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  2936. # Check timelapse field (H2D sends it here, not in xcam)
  2937. if "timelapse" in ipcam_data:
  2938. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  2939. if timelapse_enabled != self.state.timelapse:
  2940. logger.debug(
  2941. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  2942. )
  2943. self.state.timelapse = timelapse_enabled
  2944. # Track if timelapse was ever active during this print
  2945. if self.state.timelapse and self._was_running:
  2946. self._timelapse_during_print = True
  2947. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  2948. else:
  2949. self.state.ipcam = ipcam_data is True
  2950. # Parse WiFi signal strength (dBm)
  2951. if "wifi_signal" in data:
  2952. wifi_signal = data["wifi_signal"]
  2953. self._debug_on_change(
  2954. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  2955. )
  2956. if isinstance(wifi_signal, (int, float)):
  2957. self.state.wifi_signal = int(wifi_signal)
  2958. elif isinstance(wifi_signal, str):
  2959. # Handle string format like "-52dBm"
  2960. try:
  2961. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2962. except ValueError:
  2963. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2964. # Detect ethernet connection: printers on ethernet with WiFi disabled
  2965. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  2966. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  2967. from backend.app.utils.printer_models import has_ethernet
  2968. if has_ethernet(self.model):
  2969. self.state.wired_network = self.state.wifi_signal == -90
  2970. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  2971. if "spd_lvl" in data:
  2972. new_speed = data["spd_lvl"]
  2973. if new_speed != self.state.speed_level:
  2974. logger.debug(
  2975. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  2976. )
  2977. self.state.speed_level = new_speed
  2978. # Parse skipped objects from printer status (s_obj field)
  2979. # This allows us to restore skipped objects state after reconnection
  2980. if "s_obj" in data:
  2981. s_obj = data["s_obj"]
  2982. if isinstance(s_obj, list):
  2983. # Update skipped objects from printer's list
  2984. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  2985. if new_skipped != self.state.skipped_objects:
  2986. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  2987. self.state.skipped_objects = new_skipped
  2988. # Parse chamber light status from lights_report
  2989. if "lights_report" in data:
  2990. lights = data["lights_report"]
  2991. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  2992. if isinstance(lights, list):
  2993. for light in lights:
  2994. if isinstance(light, dict) and light.get("node") == "chamber_light":
  2995. new_light_state = light.get("mode") == "on"
  2996. if new_light_state != self.state.chamber_light:
  2997. logger.debug(
  2998. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  2999. )
  3000. self.state.chamber_light = new_light_state
  3001. break
  3002. # Parse nozzle hardware info (single nozzle printers)
  3003. if "nozzle_type" in data:
  3004. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  3005. if "nozzle_diameter" in data:
  3006. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  3007. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  3008. # Left nozzle
  3009. if "left_nozzle_type" in data:
  3010. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  3011. if "left_nozzle_diameter" in data:
  3012. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  3013. # Right nozzle
  3014. if "right_nozzle_type" in data:
  3015. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  3016. if "right_nozzle_diameter" in data:
  3017. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  3018. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  3019. if "nozzle_type_2" in data:
  3020. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  3021. if "nozzle_diameter_2" in data:
  3022. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  3023. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  3024. if "device" in data and isinstance(data["device"], dict):
  3025. device = data["device"]
  3026. nozzle_data = device.get("nozzle", {})
  3027. nozzle_info = nozzle_data.get("info", [])
  3028. if isinstance(nozzle_info, list):
  3029. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  3030. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  3031. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  3032. # for hover cards on both the L/R indicator and the nozzle rack card.
  3033. if nozzle_info:
  3034. self.state.nozzle_rack = sorted(
  3035. [
  3036. {
  3037. "id": n.get("id", i),
  3038. "type": str(n.get("type", "")),
  3039. "diameter": str(n.get("diameter", "")),
  3040. "wear": n.get("wear"),
  3041. "stat": n.get("stat"),
  3042. # H2C uses "tm", H2D uses "max_temp"
  3043. "max_temp": n.get("max_temp") or n.get("tm", 0),
  3044. # H2C uses "sn", H2D uses "serial_number"
  3045. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  3046. # H2C uses "color_m", H2D uses "filament_colour"
  3047. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  3048. # H2C uses "fila_id", H2D uses "filament_id"
  3049. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  3050. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  3051. }
  3052. for i, n in enumerate(nozzle_info)
  3053. ],
  3054. key=lambda x: x["id"],
  3055. )
  3056. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  3057. self._nozzle_rack_logged = True
  3058. logger.debug(
  3059. "[%s] Nozzle info: %d entries, IDs: %s",
  3060. self.serial_number,
  3061. len(nozzle_info),
  3062. [n.get("id") for n in nozzle_info],
  3063. )
  3064. for nozzle in nozzle_info:
  3065. idx = nozzle.get("id", 0)
  3066. if idx < len(self.state.nozzles):
  3067. if "type" in nozzle and nozzle["type"]:
  3068. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  3069. if "diameter" in nozzle:
  3070. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  3071. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  3072. # (these fields aren't sent in every MQTT push, only when changed)
  3073. ams_data = self.state.raw_data.get("ams")
  3074. vt_tray_data = self.state.raw_data.get("vt_tray")
  3075. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  3076. mapping_data = self.state.raw_data.get("mapping")
  3077. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  3078. # as a dict but consumers expect a list. Without this, the dev mode probe
  3079. # below can release the GIL (via publish), letting the event-loop thread
  3080. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  3081. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  3082. data["vt_tray"] = [data["vt_tray"]]
  3083. self.state.raw_data = data
  3084. # Restore preserved fields BEFORE any work that may release the GIL
  3085. # (e.g. _probe_developer_mode publishes an MQTT message).
  3086. if ams_data is not None:
  3087. self.state.raw_data["ams"] = ams_data
  3088. if vt_tray_data is not None:
  3089. self.state.raw_data["vt_tray"] = vt_tray_data
  3090. if ams_extruder_map_data is not None:
  3091. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  3092. if mapping_data is not None and "mapping" not in data:
  3093. self.state.raw_data["mapping"] = mapping_data
  3094. # Parse developer LAN mode from "fun" field
  3095. if "fun" in data:
  3096. try:
  3097. fun_val = data["fun"]
  3098. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  3099. self.state.developer_mode = (fun_int & 0x20000000) == 0
  3100. except (ValueError, TypeError):
  3101. pass
  3102. elif self.state.developer_mode is None and not self._dev_mode_probed:
  3103. # No "fun" field — A1/P1 series never send it, so we need to probe.
  3104. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  3105. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  3106. # after connect to let the MQTT session stabilize — probing too early
  3107. # can destabilize some firmware MQTT brokers (#887).
  3108. if not self._dev_mode_needs_probe and len(data) > 30:
  3109. # First full status without "fun" — mark that probe is needed
  3110. self._dev_mode_needs_probe = True
  3111. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  3112. self._probe_developer_mode()
  3113. elif self._dev_mode_needs_probe:
  3114. logger.debug(
  3115. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  3116. self.serial_number,
  3117. time.monotonic() - self._connect_time,
  3118. )
  3119. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  3120. # Probe was sent but no response yet — check for timeout.
  3121. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  3122. # may deliver status pushes but silently drop commands (#887).
  3123. elapsed = time.monotonic() - self._dev_mode_probe_time
  3124. if elapsed > 10.0:
  3125. self._dev_mode_probe_failures += 1
  3126. logger.warning(
  3127. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  3128. self.serial_number,
  3129. elapsed,
  3130. self._dev_mode_probe_failures,
  3131. )
  3132. self._dev_mode_probe_seq = None
  3133. if self._dev_mode_probe_failures >= 2:
  3134. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  3135. else:
  3136. # Allow retry on next full status message
  3137. self._dev_mode_probed = False
  3138. # Zombie session detection: if an ams_filament_setting command has been
  3139. # pending for >10s with no response, the publish path is likely dead (#887).
  3140. if self._last_ams_cmd_time > 0:
  3141. elapsed = time.monotonic() - self._last_ams_cmd_time
  3142. if elapsed > 10.0:
  3143. self._ams_cmd_unanswered += 1
  3144. logger.warning(
  3145. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  3146. self.serial_number,
  3147. elapsed,
  3148. self._ams_cmd_unanswered,
  3149. )
  3150. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  3151. if self._ams_cmd_unanswered >= 2:
  3152. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  3153. self._ams_cmd_unanswered = 0
  3154. # Log mapping data when received (for usage tracking debugging)
  3155. if "mapping" in data:
  3156. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  3157. # Log state transitions for debugging
  3158. if "gcode_state" in data:
  3159. logger.debug(
  3160. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  3161. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  3162. )
  3163. # Detect print start (state changes TO RUNNING with a file)
  3164. current_file = self.state.gcode_file or self.state.current_print
  3165. is_new_print = (
  3166. self.state.state == "RUNNING"
  3167. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  3168. and self._previous_gcode_state != "RUNNING"
  3169. and current_file
  3170. and not self._was_running # Prevent duplicates when resuming from PAUSE
  3171. )
  3172. # Also detect if file changed while running (new print started)
  3173. is_file_change = (
  3174. self.state.state == "RUNNING"
  3175. and current_file
  3176. and current_file != self._previous_gcode_file
  3177. and self._previous_gcode_file is not None
  3178. )
  3179. # Track RUNNING state for more robust completion detection
  3180. running_first_observed = False
  3181. if self.state.state == "RUNNING" and current_file:
  3182. if not self._was_running:
  3183. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  3184. # Check if timelapse was enabled in the same message (xcam parsed before this)
  3185. if self.state.timelapse:
  3186. self._timelapse_during_print = True
  3187. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  3188. # Mark this as the first RUNNING observation of the session.
  3189. # If is_new_print also fires below, on_print_start handles
  3190. # baseline capture and we suppress on_print_running_observed
  3191. # to avoid double-capture. If is_new_print does NOT fire
  3192. # (Bambuddy started mid-print — the #1304 guard suppressed
  3193. # it), main.py needs this hook to catch the restart-recovery
  3194. # case (#1485 follow-up).
  3195. running_first_observed = True
  3196. self._was_running = True
  3197. self._completion_triggered = False
  3198. if is_new_print or is_file_change:
  3199. # Clear any old HMS errors when a new print starts
  3200. self.state.hms_errors = []
  3201. # Reset layer tracking for new print (needed for layer-based timelapse)
  3202. self.state.layer_num = 0
  3203. # Reset total_layers so the previous print's value can't bleed into
  3204. # this print's usage-tracker split before the new push_status arrives
  3205. # with the slicer's total (#1771 follow-on to the preservation guard
  3206. # above at line ~2135 — the guard now ignores firmware-reset 0s, so
  3207. # the explicit reset has to happen here instead).
  3208. self.state.total_layers = 0
  3209. # Reset completion tracking for new print
  3210. self._was_running = True
  3211. self._completion_triggered = False
  3212. # #1721: rearm the end-of-print finish-photo trigger for the new print
  3213. self._finish_photo_captured = False
  3214. # Reset last valid progress/layer for usage tracking
  3215. self._last_valid_progress = 0.0
  3216. self._last_valid_layer_num = 0
  3217. # Clear and seed tray change log for mid-print usage splitting
  3218. self.state.tray_change_log.clear()
  3219. tn = self.state.tray_now
  3220. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  3221. self.state.tray_change_log.append((tn, 0))
  3222. # Initialize timelapse tracking based on current state
  3223. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  3224. # so self.state.timelapse may already be set from this message.
  3225. # We preserve that value instead of blindly resetting to False.
  3226. if self.state.timelapse:
  3227. self._timelapse_during_print = True
  3228. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  3229. else:
  3230. self._timelapse_during_print = False
  3231. if (is_new_print or is_file_change) and self.on_print_start:
  3232. logger.info(
  3233. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  3234. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  3235. )
  3236. self.on_print_start(
  3237. {
  3238. "filename": current_file,
  3239. "subtask_name": self.state.subtask_name,
  3240. "remaining_time": self.state.remaining_time * 60
  3241. if self.state.remaining_time > 0
  3242. else None, # Convert minutes to seconds
  3243. "raw_data": data,
  3244. "ams_mapping": self._captured_ams_mapping,
  3245. }
  3246. )
  3247. elif running_first_observed and self.on_print_running_observed:
  3248. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  3249. # print, so the #1304 first-push guard suppressed on_print_start,
  3250. # but we still need main.py to capture a fresh timelapse baseline
  3251. # before the printer uploads the in-flight MP4. Same payload
  3252. # shape as on_print_start so the consumer can reuse fields.
  3253. logger.info(
  3254. f"[{self.serial_number}] RUNNING observed without PRINT START "
  3255. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  3256. )
  3257. self.on_print_running_observed(
  3258. {
  3259. "filename": current_file,
  3260. "subtask_name": self.state.subtask_name,
  3261. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  3262. "raw_data": data,
  3263. "ams_mapping": self._captured_ams_mapping,
  3264. }
  3265. )
  3266. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  3267. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  3268. # This handles cases where server restarts during a print
  3269. should_trigger_completion = (
  3270. self.state.state in ("FINISH", "FAILED")
  3271. and not self._completion_triggered
  3272. and self.on_print_complete
  3273. and (
  3274. self._previous_gcode_state == "RUNNING" # Normal transition
  3275. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  3276. # Pre-print failure (#1111): printer rejected the job during setup
  3277. # — wrong nozzle size, AMS error, etc. The print never reaches
  3278. # RUNNING, so without this branch neither the RUNNING check nor
  3279. # _was_running match and the queue item stays stuck at "printing".
  3280. # Restricted to FAILED from pre-print states so a stale FAILED on
  3281. # first connection (prev=None) still can't accidentally fire.
  3282. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  3283. )
  3284. )
  3285. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  3286. if (
  3287. self.state.state == "IDLE"
  3288. and self._previous_gcode_state == "RUNNING"
  3289. and not self._completion_triggered
  3290. and self.on_print_complete
  3291. ):
  3292. should_trigger_completion = True
  3293. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  3294. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  3295. if (
  3296. not should_trigger_completion
  3297. and self.state.state in ("FINISH", "FAILED")
  3298. and self._previous_gcode_state != self.state.state
  3299. ):
  3300. logger.info(
  3301. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  3302. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  3303. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  3304. )
  3305. # Mark as triggered so state is clean for the next print cycle
  3306. self._completion_triggered = True
  3307. if should_trigger_completion:
  3308. if self.state.state == "FINISH":
  3309. status = "completed"
  3310. elif self.state.state == "FAILED":
  3311. status = "failed"
  3312. else:
  3313. status = "aborted"
  3314. logger.info(
  3315. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  3316. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  3317. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  3318. f"timelapse_during_print: {self._timelapse_during_print}"
  3319. )
  3320. timelapse_was_active = self._timelapse_during_print
  3321. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  3322. # external-spool-only, HMS halt, or firmware variant that skips
  3323. # the unload phase) fire the finish-photo moment now. Bed has
  3324. # already dropped, framing is worse, but we still capture.
  3325. # Only on successful completion — aborted/failed prints don't
  3326. # produce a meaningful finish photo.
  3327. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  3328. self._finish_photo_captured = True
  3329. logger.info(
  3330. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  3331. f"stage-22 never fired; capturing at FINISH-state transition"
  3332. )
  3333. self.on_finish_photo_moment(
  3334. {
  3335. "trigger": "finish_state",
  3336. "filename": self._previous_gcode_file or current_file,
  3337. "subtask_name": self.state.subtask_name,
  3338. "timelapse_was_active": timelapse_was_active,
  3339. }
  3340. )
  3341. self._completion_triggered = True
  3342. self._was_running = False
  3343. self._timelapse_during_print = False # Reset for next print
  3344. # Include HMS errors for failure reason detection
  3345. hms_errors_data = (
  3346. [
  3347. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  3348. for e in self.state.hms_errors
  3349. ]
  3350. if self.state.hms_errors
  3351. else []
  3352. )
  3353. self.on_print_complete(
  3354. {
  3355. "status": status,
  3356. "filename": self._previous_gcode_file or current_file,
  3357. "subtask_name": self.state.subtask_name,
  3358. "raw_data": data,
  3359. "timelapse_was_active": timelapse_was_active,
  3360. "hms_errors": hms_errors_data,
  3361. "ams_mapping": self._captured_ams_mapping,
  3362. # Last valid progress/layer before firmware reset (for partial usage tracking)
  3363. "last_progress": self._last_valid_progress,
  3364. "last_layer_num": self._last_valid_layer_num,
  3365. }
  3366. )
  3367. self._captured_ams_mapping = None
  3368. self._previous_gcode_state = self.state.state
  3369. if current_file:
  3370. self._previous_gcode_file = current_file
  3371. if self.on_state_change:
  3372. self.on_state_change(self.state)
  3373. def _request_push_all(self):
  3374. """Request full status update from printer."""
  3375. if self._client:
  3376. message = {"pushing": {"command": "pushall"}}
  3377. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3378. def _probe_developer_mode(self):
  3379. """Probe developer mode by sending an ams_filament_setting for the external slot.
  3380. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  3381. For these, we detect developer mode by sending a harmless command and
  3382. checking whether the printer accepts or rejects it:
  3383. - result="success" → developer mode ON (commands accepted)
  3384. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  3385. The probe re-sends the current external slot configuration so it's a no-op
  3386. when the command succeeds. If there's no external slot data yet, we send a
  3387. reset (empty filament) which is also safe.
  3388. """
  3389. if not self._client or not self.state.connected:
  3390. return
  3391. self._dev_mode_probed = True
  3392. self._dev_mode_probe_time = time.monotonic()
  3393. self._sequence_id += 1
  3394. seq = str(self._sequence_id)
  3395. self._dev_mode_probe_seq = seq
  3396. # Build probe command: re-send current external slot config (no-op on success)
  3397. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  3398. current = vt_tray[0] if vt_tray else {}
  3399. command = {
  3400. "print": {
  3401. "command": "ams_filament_setting",
  3402. "ams_id": 255,
  3403. "tray_id": 0,
  3404. "slot_id": 0,
  3405. "tray_info_idx": current.get("tray_info_idx", ""),
  3406. "tray_type": current.get("tray_type", ""),
  3407. "tray_sub_brands": current.get("tray_sub_brands", ""),
  3408. "tray_color": current.get("tray_color", "00000000"),
  3409. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  3410. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  3411. "sequence_id": seq,
  3412. }
  3413. }
  3414. setting_id = current.get("setting_id")
  3415. if setting_id:
  3416. command["print"]["setting_id"] = setting_id
  3417. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  3418. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3419. def _handle_dev_mode_probe_response(self, data: dict):
  3420. """Handle response to the developer mode probe command.
  3421. Sets developer_mode based on whether the printer accepted or rejected the command.
  3422. """
  3423. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  3424. self._dev_mode_probe_failures = 0 # Reset on any response
  3425. result = data.get("result", "")
  3426. reason = data.get("reason", "")
  3427. if result == "failed" and "verify failed" in reason:
  3428. self.state.developer_mode = False
  3429. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  3430. else:
  3431. # Success or any other response — commands are accepted
  3432. self.state.developer_mode = True
  3433. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  3434. if self.on_state_change:
  3435. self.on_state_change(self.state)
  3436. def _request_version(self):
  3437. """Request firmware version info from printer."""
  3438. if self._client:
  3439. self._sequence_id += 1
  3440. message = {
  3441. "info": {
  3442. "sequence_id": str(self._sequence_id),
  3443. "command": "get_version",
  3444. }
  3445. }
  3446. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  3447. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3448. def request_status_update(self) -> bool:
  3449. """Request a full status update from the printer (public API).
  3450. Sends both pushall and get_accessories commands to refresh all data
  3451. including nozzle hardware info.
  3452. Returns:
  3453. True if the request was sent, False if not connected.
  3454. """
  3455. if not self._client or not self.state.connected:
  3456. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  3457. return False
  3458. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  3459. self._request_push_all()
  3460. # Note: get_accessories returns stale nozzle data on H2D.
  3461. # The correct nozzle data comes from push_status response.
  3462. return True
  3463. def _request_accessories(self):
  3464. """Request accessories info (nozzle type, etc.) from printer."""
  3465. if self._client:
  3466. self._sequence_id += 1
  3467. message = {
  3468. "system": {
  3469. "sequence_id": str(self._sequence_id),
  3470. "command": "get_accessories",
  3471. "accessory_type": "none",
  3472. }
  3473. }
  3474. logger.debug("[%s] Requesting accessories info", self.serial_number)
  3475. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3476. def _prime_kprofile_request(self):
  3477. """Send a priming K-profile request on connect.
  3478. Bambu printers often ignore the first K-profile request after connection,
  3479. so we send a dummy request on connect to 'prime' the system.
  3480. """
  3481. if self._client:
  3482. self._sequence_id += 1
  3483. command = {
  3484. "print": {
  3485. "command": "extrusion_cali_get",
  3486. "filament_id": "",
  3487. "nozzle_diameter": "0.4",
  3488. "sequence_id": str(self._sequence_id),
  3489. }
  3490. }
  3491. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  3492. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3493. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  3494. """Connect to the printer MQTT broker.
  3495. Args:
  3496. loop: The asyncio event loop to use for thread-safe callbacks.
  3497. If not provided, will try to get the running loop.
  3498. """
  3499. self._loop = loop
  3500. BambuMQTTClient._client_instance_counter += 1
  3501. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  3502. self._client = mqtt.Client(
  3503. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  3504. client_id=client_id,
  3505. protocol=mqtt.MQTTv311,
  3506. )
  3507. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  3508. # tracking (#1164). The default ceiling of 20 wedges sessions after
  3509. # ~16-20 cumulative commands; lifting it well above any realistic
  3510. # session count keeps QoS=1 working without changing wire-protocol
  3511. # behaviour across printer models.
  3512. self._client.max_inflight_messages_set(1000)
  3513. self._client.username_pw_set("bblp", self.access_code)
  3514. self._client.on_connect = self._on_connect
  3515. self._client.on_disconnect = self._on_disconnect
  3516. self._client.on_subscribe = self._on_subscribe
  3517. self._client.on_message = self._on_message
  3518. # TLS setup - Bambu uses self-signed certs
  3519. ssl_context = ssl.create_default_context()
  3520. ssl_context.check_hostname = False
  3521. ssl_context.verify_mode = ssl.CERT_NONE
  3522. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  3523. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  3524. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  3525. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  3526. # bare-metal installs whose build allows TLS 1.0.
  3527. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  3528. self._client.tls_set_context(ssl_context)
  3529. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  3530. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  3531. # Keepalive: paho sends PINGREQs at this interval, broker considers
  3532. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  3533. # real network loss (45s), not so aggressive that transient hiccups
  3534. # trigger false disconnects. Stale detection (60s no messages) handles
  3535. # the P1S/P1P firmware bug where the broker stops publishing but the
  3536. # TCP connection stays alive.
  3537. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  3538. self._client.loop_start()
  3539. def start_print(
  3540. self,
  3541. filename: str,
  3542. plate_id: int = 1,
  3543. ams_mapping: list[int] | None = None,
  3544. bed_levelling: bool = True,
  3545. flow_cali: bool = False,
  3546. vibration_cali: bool = True,
  3547. layer_inspect: bool = False,
  3548. timelapse: bool = False,
  3549. use_ams: bool = True,
  3550. nozzle_offset_cali: bool = False,
  3551. nozzle_mapping: str | None = None,
  3552. ):
  3553. """Start a print job on the printer.
  3554. The file should already be uploaded to the printer's root directory via FTP.
  3555. Args:
  3556. filename: Name of the uploaded file
  3557. plate_id: Plate number to print (default 1)
  3558. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  3559. Global tray ID = (ams_id * 4) + slot_id, external = 254
  3560. timelapse: Record timelapse video
  3561. bed_levelling: Auto bed levelling before print
  3562. flow_cali: Flow/pressure advance calibration
  3563. vibration_cali: Vibration compensation calibration
  3564. layer_inspect: First layer AI inspection
  3565. use_ams: Use AMS for automatic filament changes
  3566. nozzle_offset_cali: Run nozzle offset calibration before print
  3567. (dual-nozzle printers only — silently ignored on single-nozzle).
  3568. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  3569. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  3570. AND the printer is dual-nozzle, parsed and injected as the
  3571. `nozzle_mapping` array on the dispatched project_file so the
  3572. firmware honours the user's slicer pick instead of falling
  3573. back to "last matching nozzle" auto-pick. Silently ignored
  3574. on single-nozzle printers.
  3575. """
  3576. if self._client and self.state.connected:
  3577. # Bambu print command format — matches Bambu Studio's format.
  3578. # The calibration/leveling fields (timelapse, bed_leveling,
  3579. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  3580. # every model. An earlier revision integer-encoded them for the H2
  3581. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  3582. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  3583. # sends plain booleans, and the integer encoding made the H2S
  3584. # silently skip flow-dynamics calibration (#1478). use_ams is the
  3585. # one field that genuinely must stay boolean: H2D Pro firmware
  3586. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  3587. # what actually caused the wrong-extruder routing behind #1386.
  3588. # Dual-nozzle routing for external spool (254 = deputy/left,
  3589. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  3590. # H2 firmware family but is single-nozzle, despite sharing serial
  3591. # prefix "094" with H2D. Prefer runtime detection from
  3592. # device.extruder.info (set in _handle_push_status); fall back to
  3593. # model name for the brief window after connect before push data
  3594. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  3595. # as the primary signal.
  3596. from backend.app.utils.printer_models import is_dual_nozzle_model
  3597. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  3598. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  3599. ams_mapping2 = []
  3600. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  3601. # ams_mapping and relies on ams_mapping2 for external spool details.
  3602. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  3603. # with 0700_8012 "Failed to get AMS mapping table".
  3604. flat_ams_mapping = []
  3605. if ams_mapping is not None:
  3606. for tray_id in ams_mapping:
  3607. # Ensure tray_id is an integer (may be string from JSON)
  3608. tray_id = int(tray_id) if tray_id is not None else -1
  3609. if tray_id == -1:
  3610. # Unmapped filament slot
  3611. flat_ams_mapping.append(-1)
  3612. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  3613. elif tray_id >= 254:
  3614. # External/virtual spool. BambuStudio convention:
  3615. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  3616. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  3617. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  3618. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  3619. # for external spool, but BambuStudio always sends ams_id=255
  3620. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  3621. # firmware to target AMS tray 0 instead of external spool, leading
  3622. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  3623. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  3624. flat_ams_mapping.append(-1)
  3625. ext_ams_id = tray_id if is_dual_nozzle else 255
  3626. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  3627. elif tray_id >= 128:
  3628. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  3629. flat_ams_mapping.append(tray_id)
  3630. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  3631. else:
  3632. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  3633. ams_id = tray_id // 4
  3634. slot_id = tray_id % 4
  3635. flat_ams_mapping.append(tray_id)
  3636. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  3637. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  3638. # printers — the mapping is authoritative about whether this print
  3639. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  3640. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  3641. # H2S falls through here now (#1386): it is single-nozzle and was
  3642. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  3643. # without an AMS attached.
  3644. #
  3645. # Two symmetric corrections:
  3646. #
  3647. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  3648. # use_ams=True even if it arrived False. A print sent to a Virtual
  3649. # Printer is sliced against the VP, which advertises no AMS, so the
  3650. # slicer sends use_ams=false and that gets stamped on the queue item
  3651. # — but at dispatch the scheduler colour-matches a real printer and
  3652. # resolves a real AMS slot. Without this, the stale False reaches the
  3653. # printer, which ignores the mapped slot and aborts at layer 0 on the
  3654. # empty external spool ("not enough filament"). Diagnosed by
  3655. # @Sawtaytoes (#2595, PR #2596).
  3656. #
  3657. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  3658. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  3659. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  3660. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  3661. # status-load race that persisted [-1] (#2589) — and treating it as
  3662. # external silently started the print against an empty feed. A genuine
  3663. # external selection is >=254; unresolved is -1; a loaded tray is
  3664. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  3665. # (or is recomputed upstream) instead of silently going external, and
  3666. # never gets force-enabled by (a) either.
  3667. if ams_mapping and not is_dual_nozzle:
  3668. has_real_tray = any(t is not None and 0 <= int(t) <= 253 for t in ams_mapping)
  3669. all_external = all(t is None or int(t) >= 254 for t in ams_mapping)
  3670. if has_real_tray and not use_ams:
  3671. use_ams = True
  3672. logger.info(
  3673. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  3674. self.serial_number,
  3675. )
  3676. elif use_ams and all_external:
  3677. use_ams = False
  3678. logger.info(
  3679. "[%s] All filament slots use external spool — setting use_ams=False",
  3680. self.serial_number,
  3681. )
  3682. # Unique per-submission identity fields. Hardcoded "0" values caused
  3683. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  3684. # continuations of the same job: the printer reuses gcode_start_time
  3685. # from the prior print with task_id=0, so observers latch onto a stale
  3686. # timestamp and report compounding durations on repeat replays (#1011).
  3687. # BambuStudio mints fresh IDs per submission; matching that behavior
  3688. # makes the printer emit a clean state-transition for each job.
  3689. # md5 is left empty — firmware historically accepts "" as "skip
  3690. # validation" (unlike Studio, we don't have the file's real md5 here
  3691. # without re-reading the upload, and sending a synthetic wrong digest
  3692. # risks activation of md5 verification on some firmwares).
  3693. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  3694. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  3695. # overflows and every submission ends up with the same task_id from
  3696. # the printer's perspective — the printer then treats a fresh dispatch
  3697. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  3698. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  3699. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  3700. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  3701. # Remember it so on_print_start can persist a restart-stable id on
  3702. # the archive even before the printer echoes subtask_id back (#1485).
  3703. self.last_dispatch_subtask_id = submission_id
  3704. command = {
  3705. "print": {
  3706. "sequence_id": "20000",
  3707. "command": "project_file",
  3708. "param": f"Metadata/plate_{plate_id}.gcode",
  3709. "url": f"ftp://{filename}",
  3710. "file": filename,
  3711. "md5": "",
  3712. "bed_type": "auto",
  3713. "timelapse": timelapse,
  3714. "bed_leveling": bed_levelling,
  3715. "auto_bed_leveling": 1 if bed_levelling else 0,
  3716. "flow_cali": flow_cali,
  3717. "vibration_cali": vibration_cali,
  3718. "layer_inspect": layer_inspect,
  3719. "use_ams": use_ams,
  3720. "cfg": "0",
  3721. # extrude_cali_flag gates flow-dynamics calibration:
  3722. # 1 = run it, 0 = printer skips entirely (#1478 evidence).
  3723. # 2 = "skip and reuse stored PA" was previously believed to
  3724. # suppress the stage too, but #1721 testing on H2D 01.x
  3725. # showed stage 8 ("Calibrating dynamic flow") still gets
  3726. # queued when we send 2. A real BambuStudio Send-dialog
  3727. # capture today also showed 0 when the user disables flow
  3728. # calibration. Going with 0 to actually suppress the
  3729. # pre-print calibration stage.
  3730. "extrude_cali_flag": 1 if flow_cali else 0,
  3731. "extrude_cali_manual_mode": 0,
  3732. # 1 = run, 0 = skip (matches BambuStudio's wire today). The
  3733. # earlier 2 = "skip" reading from #1682 didn't actually
  3734. # suppress stage 39 ("Nozzle offset calibration") on H2D
  3735. # 01.x — captured live in #1721. BambuStudio exposes the
  3736. # toggle only for dual-nozzle (H2D/H2D Pro/H2C/X2D); single-
  3737. # nozzle prints still resolve to 0 here so firmware never
  3738. # runs a calibration the head doesn't support.
  3739. "nozzle_offset_cali": 1 if (nozzle_offset_cali and is_dual_nozzle) else 0,
  3740. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  3741. "profile_id": "0",
  3742. "project_id": submission_id,
  3743. "subtask_id": submission_id,
  3744. "task_id": submission_id,
  3745. }
  3746. }
  3747. # P2S-specific parameter adjustments
  3748. # P2S printer doesn't support vibration calibration like X1/P1 series
  3749. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  3750. command["print"]["vibration_cali"] = False
  3751. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  3752. # Add AMS mapping if provided
  3753. if ams_mapping is not None:
  3754. command["print"]["ams_mapping"] = flat_ams_mapping
  3755. command["print"]["ams_mapping2"] = ams_mapping2
  3756. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  3757. # `nozzle_mapping` carries per-filament physical nozzle position
  3758. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  3759. # item; parse here so the wire ships an array, matching
  3760. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  3761. # defensively — single-nozzle firmwares would ignore the field
  3762. # but we err on the side of not emitting unrecognised fields. A
  3763. # parse failure is logged but never blocks the dispatch — the
  3764. # firmware will fall back to its auto-pick path, which is the
  3765. # pre-fix behaviour.
  3766. if is_dual_nozzle and nozzle_mapping:
  3767. try:
  3768. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  3769. except json.JSONDecodeError:
  3770. logger.warning(
  3771. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  3772. "project_file (firmware will auto-pick): %r",
  3773. self.serial_number,
  3774. nozzle_mapping,
  3775. )
  3776. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  3777. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3778. # Record what we dispatched so /cover can pick the right plate
  3779. # thumbnail even when the printer's gcode_file echo is just the
  3780. # 3MF filename without a plate path (#1166). Match the same
  3781. # subtask_name shape we send so the comparison in the cover route
  3782. # works against state.subtask_name reflected back via MQTT.
  3783. self.state.dispatched_plate_id = plate_id
  3784. self.state.dispatched_subtask = command["print"]["subtask_name"]
  3785. return True
  3786. else:
  3787. # Log why we couldn't send the command
  3788. if not self._client:
  3789. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  3790. elif not self.state.connected:
  3791. logger.error(
  3792. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  3793. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  3794. )
  3795. return False
  3796. def stop_print(self) -> bool:
  3797. """Stop the current print job."""
  3798. if self._client and self.state.connected:
  3799. command = {"print": {"command": "stop", "sequence_id": "0"}}
  3800. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3801. logger.info("[%s] Sent stop print command", self.serial_number)
  3802. return True
  3803. return False
  3804. def set_xcam_option(
  3805. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  3806. ) -> bool:
  3807. """Set an xcam (AI detection) option on the printer.
  3808. Args:
  3809. module_name: The xcam module to control (e.g., "spaghetti_detector",
  3810. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  3811. enabled: Whether to enable or disable the feature
  3812. print_halt: Whether to halt print on detection (only applies to some detectors)
  3813. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  3814. Returns:
  3815. True if command was sent, False if not connected
  3816. """
  3817. if not self._client or not self.state.connected:
  3818. return False
  3819. # auto_recovery_step_loss uses a different command format (print.print_option)
  3820. if module_name == "auto_recovery_step_loss":
  3821. return self._set_print_option("auto_recovery", enabled)
  3822. self._sequence_id += 1
  3823. # Build the xcam control command (exact OrcaSlicer format)
  3824. # Key findings from OrcaSlicer source:
  3825. # - Uses "xcam" wrapper (not "print")
  3826. # - print_halt is ALWAYS true (legacy protocol requirement)
  3827. # - Both "control" and "enable" are set to the same value
  3828. # - halt_print_sensitivity controls actual halt behavior
  3829. command = {
  3830. "xcam": {
  3831. "command": "xcam_control_set",
  3832. "sequence_id": str(self._sequence_id),
  3833. "module_name": module_name,
  3834. "control": enabled,
  3835. "enable": enabled, # old protocol compatibility
  3836. "print_halt": True, # ALWAYS true per OrcaSlicer
  3837. }
  3838. }
  3839. # Only add sensitivity if not "never_halt"
  3840. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  3841. # The module_name field determines which detector's sensitivity is being set
  3842. if sensitivity and sensitivity != "never_halt":
  3843. command["xcam"]["halt_print_sensitivity"] = sensitivity
  3844. command_json = json.dumps(command)
  3845. self._client.publish(self.topic_publish, command_json, qos=1)
  3846. logger.debug(
  3847. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  3848. )
  3849. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  3850. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  3851. # This prevents stale MQTT data from immediately overwriting our change
  3852. self._xcam_hold_start[module_name] = time.time()
  3853. # Update local state immediately for responsive UI
  3854. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  3855. # When spaghetti_detector sensitivity is changed, pileup also changes
  3856. if module_name == "spaghetti_detector":
  3857. self.state.print_options.spaghetti_detector = enabled
  3858. self.state.print_options.print_halt = print_halt
  3859. if sensitivity and sensitivity != "never_halt":
  3860. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  3861. self.state.print_options.halt_print_sensitivity = sensitivity
  3862. self.state.print_options.pileup_sensitivity = sensitivity
  3863. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  3864. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  3865. elif module_name == "first_layer_inspector":
  3866. self.state.print_options.first_layer_inspector = enabled
  3867. elif module_name == "printing_monitor":
  3868. self.state.print_options.printing_monitor = enabled
  3869. elif module_name == "buildplate_marker_detector":
  3870. self.state.print_options.buildplate_marker_detector = enabled
  3871. elif module_name == "allow_skip_parts":
  3872. self.state.print_options.allow_skip_parts = enabled
  3873. elif module_name == "pileup_detector":
  3874. self.state.print_options.pileup_detector = enabled
  3875. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  3876. elif module_name == "clump_detector":
  3877. self.state.print_options.nozzle_clumping_detector = enabled
  3878. if sensitivity and sensitivity != "never_halt":
  3879. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  3880. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  3881. elif module_name == "airprint_detector":
  3882. self.state.print_options.airprint_detector = enabled
  3883. if sensitivity and sensitivity != "never_halt":
  3884. self.state.print_options.airprint_sensitivity = sensitivity
  3885. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  3886. elif module_name == "auto_recovery_step_loss":
  3887. self.state.print_options.auto_recovery_step_loss = enabled
  3888. return True
  3889. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  3890. """Set a print option using the print.print_option command.
  3891. This is different from xcam_control_set and is used for options like:
  3892. - auto_recovery
  3893. - air_print_detect
  3894. - filament_tangle_detect
  3895. - nozzle_blob_detect
  3896. - sound_enable
  3897. Args:
  3898. option_name: The option to control (e.g., "auto_recovery")
  3899. enabled: Whether to enable or disable the option
  3900. Returns:
  3901. True if command was sent, False if not connected
  3902. """
  3903. if not self._client or not self.state.connected:
  3904. return False
  3905. self._sequence_id += 1
  3906. command = {
  3907. "print": {
  3908. "command": "print_option",
  3909. "sequence_id": str(self._sequence_id),
  3910. option_name: enabled,
  3911. }
  3912. }
  3913. command_json = json.dumps(command)
  3914. self._client.publish(self.topic_publish, command_json, qos=1)
  3915. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  3916. # Set hold timer
  3917. hold_key = f"print_option_{option_name}"
  3918. self._xcam_hold_start[hold_key] = time.time()
  3919. # Update local state immediately
  3920. if option_name == "auto_recovery":
  3921. self.state.print_options.auto_recovery_step_loss = enabled
  3922. elif option_name == "auto_switch_filament":
  3923. self.state.ams_filament_backup = enabled
  3924. return True
  3925. def set_ams_filament_backup(self, enabled: bool) -> bool:
  3926. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  3927. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  3928. shape from H2D capture 2026-06-20.
  3929. """
  3930. return self._set_print_option("auto_switch_filament", enabled)
  3931. def start_calibration(
  3932. self,
  3933. bed_leveling: bool = False,
  3934. vibration: bool = False,
  3935. motor_noise: bool = False,
  3936. nozzle_offset: bool = False,
  3937. high_temp_heatbed: bool = False,
  3938. ) -> bool:
  3939. """Start printer calibration with selected options.
  3940. Args:
  3941. bed_leveling: Run bed leveling calibration
  3942. vibration: Run vibration compensation calibration
  3943. motor_noise: Run motor noise cancellation calibration
  3944. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  3945. high_temp_heatbed: Run high-temperature heatbed calibration
  3946. Returns:
  3947. True if command was sent, False if not connected
  3948. """
  3949. if not self._client or not self.state.connected:
  3950. return False
  3951. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  3952. # Bit 0: xcam_cali (not exposed in UI)
  3953. # Bit 1: bed_leveling
  3954. # Bit 2: vibration
  3955. # Bit 3: motor_noise
  3956. # Bit 4: nozzle_cali
  3957. # Bit 5: bed_cali (high-temp heatbed)
  3958. # Bit 6: clumppos_cali (not exposed in UI)
  3959. option = 0
  3960. if bed_leveling:
  3961. option |= 1 << 1
  3962. if vibration:
  3963. option |= 1 << 2
  3964. if motor_noise:
  3965. option |= 1 << 3
  3966. if nozzle_offset:
  3967. option |= 1 << 4
  3968. if high_temp_heatbed:
  3969. option |= 1 << 5
  3970. if option == 0:
  3971. logger.warning("[%s] No calibration options selected", self.serial_number)
  3972. return False
  3973. self._sequence_id += 1
  3974. command = {
  3975. "print": {
  3976. "command": "calibration",
  3977. "sequence_id": str(self._sequence_id),
  3978. "option": option,
  3979. }
  3980. }
  3981. command_json = json.dumps(command)
  3982. self._client.publish(self.topic_publish, command_json, qos=1)
  3983. logger.info(
  3984. f"[{self.serial_number}] Starting calibration: "
  3985. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  3986. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  3987. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  3988. )
  3989. return True
  3990. def disconnect(self, timeout: float = 0):
  3991. """Disconnect from the printer."""
  3992. if self._client:
  3993. self._disconnection_event = threading.Event()
  3994. self._client.disconnect()
  3995. self._disconnection_event.wait(timeout=timeout)
  3996. self._client.loop_stop()
  3997. self._client = None
  3998. self.state.connected = False
  3999. def send_command(self, command: dict):
  4000. """Send a command to the printer."""
  4001. if self._client and self.state.connected:
  4002. # Log outgoing message if logging is enabled
  4003. if self._logging_enabled:
  4004. self._message_log.append(
  4005. MQTTLogEntry(
  4006. timestamp=datetime.now(timezone.utc).isoformat(),
  4007. topic=self.topic_publish,
  4008. direction="out",
  4009. payload=command,
  4010. )
  4011. )
  4012. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4013. def enable_logging(self, enabled: bool = True):
  4014. """Enable or disable MQTT message logging."""
  4015. self._logging_enabled = enabled
  4016. # Don't clear logs when stopping - user can manually clear with clear_logs()
  4017. def get_logs(self) -> list[MQTTLogEntry]:
  4018. """Get all logged MQTT messages."""
  4019. return list(self._message_log)
  4020. def clear_logs(self):
  4021. """Clear the message log."""
  4022. self._message_log.clear()
  4023. @property
  4024. def logging_enabled(self) -> bool:
  4025. """Check if logging is enabled."""
  4026. return self._logging_enabled
  4027. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  4028. """Register a handler invoked for every incoming MQTT message.
  4029. Used by the VP MQTT bridge to republish the printer's report pushes to
  4030. slicers connected to a virtual printer in non-proxy mode. Handlers run
  4031. on paho's network thread and must not block; exceptions are caught.
  4032. """
  4033. if handler not in self._raw_message_handlers:
  4034. self._raw_message_handlers.append(handler)
  4035. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  4036. """Unregister a previously-registered raw-message handler."""
  4037. try:
  4038. self._raw_message_handlers.remove(handler)
  4039. except ValueError:
  4040. pass
  4041. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  4042. """Publish a pre-formed payload directly to the printer's MQTT broker.
  4043. Used by the VP MQTT bridge to forward slicer-originated commands without
  4044. going through send_command's sequence-id mangling. Returns False if the
  4045. underlying paho client isn't ready.
  4046. """
  4047. if self._client is None:
  4048. return False
  4049. try:
  4050. info = self._client.publish(topic, payload, qos=qos)
  4051. return info.rc == mqtt.MQTT_ERR_SUCCESS
  4052. except Exception:
  4053. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  4054. return False
  4055. def send_drying_command(
  4056. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  4057. ):
  4058. """Send AMS drying start/stop command.
  4059. Args:
  4060. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  4061. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  4062. duration: Drying duration in hours
  4063. mode: 1=start, 0=stop
  4064. filament: Filament type string (e.g. "PLA", "PETG")
  4065. rotate_tray: Whether to rotate the spool during drying for even heat
  4066. """
  4067. if not self._client:
  4068. return False
  4069. self._sequence_id += 1
  4070. command = {
  4071. "print": {
  4072. "sequence_id": str(self._sequence_id),
  4073. "command": "ams_filament_drying",
  4074. "ams_id": ams_id,
  4075. "temp": temp,
  4076. "cooling_temp": 20 if mode == 1 else 0,
  4077. "duration": duration,
  4078. "humidity": 0,
  4079. "mode": mode,
  4080. "rotate_tray": rotate_tray,
  4081. "filament": filament,
  4082. "close_power_conflict": False,
  4083. }
  4084. }
  4085. # Log the full wire JSON at INFO so support bundles capture exactly
  4086. # what we sent — needed to diagnose silent rejections (#1447) where
  4087. # the printer ACKs the command but never starts/stops drying.
  4088. # Paired with the ams_filament_drying response-payload INFO log so
  4089. # both halves of the conversation land in the bundle by default.
  4090. wire_json = json.dumps(command)
  4091. self._client.publish(self.topic_publish, wire_json, qos=1)
  4092. logger.info(
  4093. "[%s] Sent ams_filament_drying: %s",
  4094. self.serial_number,
  4095. wire_json,
  4096. )
  4097. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  4098. # while drying. Bambu only echoes dry_time on subsequent pushes.
  4099. if mode == 1:
  4100. self._drying_targets[ams_id] = {
  4101. "filament": filament or "",
  4102. "temp": int(temp),
  4103. }
  4104. else:
  4105. self._drying_targets.pop(ams_id, None)
  4106. return True
  4107. def _handle_kprofile_response(self, data: dict):
  4108. """Handle K-profile response from printer."""
  4109. response_nozzle = data.get("nozzle_diameter")
  4110. response_seq_id = data.get("sequence_id", "?")
  4111. filaments = data.get("filaments", [])
  4112. expected_nozzle = getattr(self, "_expected_kprofile_nozzle", None)
  4113. has_pending_request = self._pending_kprofile_response is not None
  4114. # Log all incoming responses when we have a pending request (for debugging)
  4115. if has_pending_request:
  4116. logger.info(
  4117. f"[{self.serial_number}] K-profile response: nozzle={response_nozzle}, "
  4118. f"seq_id={response_seq_id}, {len(filaments)} profiles, expected={expected_nozzle}"
  4119. )
  4120. # If we have a pending request, only accept responses with matching nozzle_diameter
  4121. # The printer broadcasts 0.4mm profiles constantly - we need to wait for the actual response
  4122. if has_pending_request and expected_nozzle and response_nozzle != expected_nozzle:
  4123. # Ignore this broadcast, keep waiting for matching response
  4124. logger.debug(
  4125. f"[{self.serial_number}] Ignoring broadcast: got nozzle={response_nozzle}, waiting for {expected_nozzle}"
  4126. )
  4127. return
  4128. # If no pending request, this is just a broadcast - update state silently and return early
  4129. if not has_pending_request:
  4130. # Still parse profiles to keep state updated, but don't log
  4131. profiles = []
  4132. for f in filaments:
  4133. if isinstance(f, dict):
  4134. try:
  4135. cali_idx = f.get("cali_idx", 0)
  4136. profiles.append(
  4137. KProfile(
  4138. slot_id=cali_idx,
  4139. extruder_id=int(f.get("extruder_id", 0)),
  4140. nozzle_id=str(f.get("nozzle_id", "")),
  4141. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  4142. filament_id=str(f.get("filament_id", "")),
  4143. name=str(f.get("name", "")),
  4144. k_value=str(f.get("k_value", "0.000000")),
  4145. n_coef=str(f.get("n_coef", "0.000000")),
  4146. ams_id=int(f.get("ams_id", 0)),
  4147. tray_id=int(f.get("tray_id", -1)),
  4148. setting_id=f.get("setting_id"),
  4149. )
  4150. )
  4151. except (ValueError, TypeError):
  4152. pass # Skip malformed K-profile entries; remaining profiles still usable
  4153. self.state.kprofiles = profiles
  4154. return
  4155. profiles = []
  4156. for i, f in enumerate(filaments):
  4157. if isinstance(f, dict):
  4158. try:
  4159. # cali_idx is the actual slot/calibration index from the printer
  4160. cali_idx = f.get("cali_idx", i)
  4161. profiles.append(
  4162. KProfile(
  4163. slot_id=cali_idx,
  4164. extruder_id=int(f.get("extruder_id", 0)),
  4165. nozzle_id=str(f.get("nozzle_id", "")),
  4166. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  4167. filament_id=str(f.get("filament_id", "")),
  4168. name=str(f.get("name", "")),
  4169. k_value=str(f.get("k_value", "0.000000")),
  4170. n_coef=str(f.get("n_coef", "0.000000")),
  4171. ams_id=int(f.get("ams_id", 0)),
  4172. tray_id=int(f.get("tray_id", -1)),
  4173. setting_id=f.get("setting_id"),
  4174. )
  4175. )
  4176. except (ValueError, TypeError) as e:
  4177. logger.warning("Failed to parse K-profile: %s", e)
  4178. self.state.kprofiles = profiles
  4179. self._kprofile_response_data = profiles
  4180. # Signal that we received the response (only if we were waiting for one)
  4181. # Use thread-safe method since MQTT callbacks run in a different thread
  4182. # Capture in local var to avoid TOCTOU race: asyncio thread can clear
  4183. # self._pending_kprofile_response between the check and the .set() call
  4184. event = self._pending_kprofile_response
  4185. if event:
  4186. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  4187. if self._loop and self._loop.is_running():
  4188. self._loop.call_soon_threadsafe(event.set)
  4189. else:
  4190. # Fallback for when loop is not available
  4191. event.set()
  4192. async def get_kprofiles(
  4193. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  4194. ) -> list[KProfile]:
  4195. """Request K-profiles from the printer with retry logic.
  4196. Bambu printers sometimes ignore the first K-profile request, so we
  4197. implement retry logic to ensure reliable retrieval.
  4198. Args:
  4199. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  4200. timeout: Timeout in seconds to wait for each response attempt
  4201. max_retries: Maximum number of retry attempts
  4202. Returns:
  4203. List of KProfile objects
  4204. """
  4205. if not self._client or not self.state.connected:
  4206. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  4207. return []
  4208. # Capture current event loop for thread-safe callback
  4209. try:
  4210. self._loop = asyncio.get_running_loop()
  4211. except RuntimeError:
  4212. logger.warning("[%s] No running event loop", self.serial_number)
  4213. return []
  4214. for attempt in range(max_retries):
  4215. # Set up response event for this attempt
  4216. self._sequence_id += 1
  4217. self._pending_kprofile_response = asyncio.Event()
  4218. self._kprofile_response_data = None
  4219. self._expected_kprofile_nozzle = nozzle_diameter # Track which nozzle response we expect
  4220. # Send the command with nozzle_diameter filter
  4221. command = {
  4222. "print": {
  4223. "command": "extrusion_cali_get",
  4224. "filament_id": "",
  4225. "nozzle_diameter": nozzle_diameter,
  4226. "sequence_id": str(self._sequence_id),
  4227. }
  4228. }
  4229. logger.info(
  4230. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries})"
  4231. )
  4232. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  4233. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4234. # Wait for response (response handler already filters by nozzle_diameter)
  4235. try:
  4236. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  4237. profiles = self._kprofile_response_data or []
  4238. logger.info(
  4239. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  4240. )
  4241. return profiles
  4242. except TimeoutError:
  4243. logger.warning(
  4244. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  4245. )
  4246. if attempt < max_retries - 1:
  4247. # Brief delay before retry
  4248. await asyncio.sleep(0.5)
  4249. finally:
  4250. self._pending_kprofile_response = None
  4251. self._expected_kprofile_nozzle = None
  4252. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  4253. return []
  4254. def set_kprofile(
  4255. self,
  4256. filament_id: str,
  4257. name: str,
  4258. k_value: str,
  4259. nozzle_diameter: str = "0.4",
  4260. nozzle_id: str = "HS00-0.4",
  4261. extruder_id: int = 0,
  4262. setting_id: str | None = None,
  4263. slot_id: int = 0,
  4264. cali_idx: int | None = None,
  4265. ) -> bool:
  4266. """Set/update a K-profile on the printer.
  4267. Args:
  4268. filament_id: Bambu filament identifier
  4269. name: Profile name
  4270. k_value: Pressure advance value (e.g., "0.020000")
  4271. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  4272. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  4273. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  4274. setting_id: Existing setting ID for updates, None for new
  4275. slot_id: Calibration index (cali_idx) for the profile
  4276. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  4277. Returns:
  4278. True if command was sent, False otherwise
  4279. """
  4280. if not self._client or not self.state.connected:
  4281. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  4282. return False
  4283. self._sequence_id += 1
  4284. # Build the filament entry - printer uses cali_idx for profile identification
  4285. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  4286. # For edits, use the provided cali_idx or slot_id
  4287. if cali_idx is not None:
  4288. effective_cali_idx = cali_idx
  4289. else:
  4290. effective_cali_idx = -1 if slot_id == 0 else slot_id
  4291. # Generate a setting_id for new profiles (required by printer)
  4292. # Format: "PF" + 17 random digits
  4293. import random
  4294. if not setting_id and slot_id == 0:
  4295. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  4296. filament_entry = {
  4297. "ams_id": 0,
  4298. "cali_idx": effective_cali_idx,
  4299. "extruder_id": extruder_id,
  4300. "filament_id": filament_id,
  4301. "k_value": k_value,
  4302. "n_coef": "0.000000",
  4303. "name": name,
  4304. "nozzle_diameter": nozzle_diameter,
  4305. "nozzle_id": nozzle_id,
  4306. "setting_id": setting_id if setting_id else "",
  4307. "tray_id": -1,
  4308. }
  4309. command = {
  4310. "print": {
  4311. "command": "extrusion_cali_set",
  4312. "filaments": [filament_entry],
  4313. "nozzle_diameter": nozzle_diameter,
  4314. "sequence_id": str(self._sequence_id),
  4315. }
  4316. }
  4317. command_json = json.dumps(command)
  4318. logger.info(
  4319. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  4320. )
  4321. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  4322. self._client.publish(self.topic_publish, command_json, qos=1)
  4323. return True
  4324. def set_kprofiles_batch(
  4325. self,
  4326. profiles: list[dict],
  4327. nozzle_diameter: str = "0.4",
  4328. ) -> bool:
  4329. """Set multiple K-profiles in a single command (for dual-nozzle).
  4330. Args:
  4331. profiles: List of profile dicts, each with:
  4332. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  4333. nozzle_diameter: Common nozzle diameter for all profiles
  4334. Returns:
  4335. True if command was sent, False otherwise
  4336. """
  4337. if not self._client or not self.state.connected:
  4338. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  4339. return False
  4340. import random
  4341. self._sequence_id += 1
  4342. filament_entries = []
  4343. for p in profiles:
  4344. slot_id = p.get("slot_id", 0)
  4345. cali_idx = p.get("cali_idx")
  4346. if cali_idx is not None:
  4347. effective_cali_idx = cali_idx
  4348. else:
  4349. effective_cali_idx = -1 if slot_id == 0 else slot_id
  4350. setting_id = p.get("setting_id")
  4351. if not setting_id and slot_id == 0:
  4352. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  4353. filament_entries.append(
  4354. {
  4355. "ams_id": 0,
  4356. "cali_idx": effective_cali_idx,
  4357. "extruder_id": p.get("extruder_id", 0),
  4358. "filament_id": p.get("filament_id", ""),
  4359. "k_value": p.get("k_value", "0.020000"),
  4360. "n_coef": "0.000000",
  4361. "name": p.get("name", ""),
  4362. "nozzle_diameter": nozzle_diameter,
  4363. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  4364. "setting_id": setting_id if setting_id else "",
  4365. "tray_id": -1,
  4366. }
  4367. )
  4368. command = {
  4369. "print": {
  4370. "command": "extrusion_cali_set",
  4371. "filaments": filament_entries,
  4372. "nozzle_diameter": nozzle_diameter,
  4373. "sequence_id": str(self._sequence_id),
  4374. }
  4375. }
  4376. command_json = json.dumps(command)
  4377. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  4378. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  4379. self._client.publish(self.topic_publish, command_json, qos=1)
  4380. return True
  4381. def delete_kprofile(
  4382. self,
  4383. cali_idx: int,
  4384. filament_id: str,
  4385. nozzle_id: str,
  4386. nozzle_diameter: str = "0.4",
  4387. extruder_id: int = 0,
  4388. setting_id: str | None = None,
  4389. ) -> bool:
  4390. """Delete a K-profile from the printer.
  4391. Args:
  4392. cali_idx: The calibration index (slot_id) of the profile to delete
  4393. filament_id: Bambu filament identifier
  4394. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  4395. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  4396. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  4397. setting_id: Unique setting identifier (for X1C series)
  4398. Returns:
  4399. True if command was sent, False otherwise
  4400. """
  4401. if not self._client or not self.state.connected:
  4402. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  4403. return False
  4404. self._sequence_id += 1
  4405. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  4406. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  4407. # Prefer runtime detection from device.extruder.info; fall back to
  4408. # model name. H2S is single-nozzle but shares serial prefix "094" with
  4409. # H2D, so a prefix-only check misclassified it (#1386).
  4410. from backend.app.utils.printer_models import is_dual_nozzle_model
  4411. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  4412. if is_dual_nozzle:
  4413. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  4414. command = {
  4415. "print": {
  4416. "command": "extrusion_cali_del",
  4417. "sequence_id": str(self._sequence_id),
  4418. "extruder_id": extruder_id,
  4419. "nozzle_id": nozzle_id,
  4420. "filament_id": filament_id,
  4421. "cali_idx": cali_idx,
  4422. "nozzle_diameter": nozzle_diameter,
  4423. }
  4424. }
  4425. else:
  4426. # X1C/P1/A1 format: include all fields like the set command
  4427. # The delete command structure should match what set uses
  4428. command = {
  4429. "print": {
  4430. "command": "extrusion_cali_del",
  4431. "sequence_id": str(self._sequence_id),
  4432. "filament_id": filament_id,
  4433. "cali_idx": cali_idx,
  4434. "setting_id": setting_id if setting_id else "",
  4435. "nozzle_diameter": nozzle_diameter,
  4436. "nozzle_id": nozzle_id,
  4437. "extruder_id": extruder_id,
  4438. }
  4439. }
  4440. command_json = json.dumps(command)
  4441. logger.info(
  4442. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  4443. )
  4444. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  4445. # Use QoS 1 for reliable delivery (at least once)
  4446. self._client.publish(self.topic_publish, command_json, qos=1)
  4447. return True
  4448. # =========================================================================
  4449. # Printer Control Commands
  4450. # =========================================================================
  4451. def pause_print(self) -> bool:
  4452. """Pause the current print job."""
  4453. if not self._client or not self.state.connected:
  4454. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  4455. return False
  4456. command = {"print": {"command": "pause", "sequence_id": "0"}}
  4457. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4458. logger.info("[%s] Sent pause print command", self.serial_number)
  4459. return True
  4460. def resume_print(self) -> bool:
  4461. """Resume a paused print job."""
  4462. if not self._client or not self.state.connected:
  4463. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  4464. return False
  4465. command = {"print": {"command": "resume", "sequence_id": "0"}}
  4466. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4467. logger.info("[%s] Sent resume print command", self.serial_number)
  4468. return True
  4469. def clear_hms_errors(self) -> bool:
  4470. """Clear HMS/print errors on the printer and locally."""
  4471. if not self._client or not self.state.connected:
  4472. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  4473. return False
  4474. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  4475. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4476. self.state.hms_errors = []
  4477. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  4478. return True
  4479. def skip_objects(self, object_ids: list[int]) -> bool:
  4480. """Skip specific objects during a print.
  4481. This command tells the printer to skip printing the specified objects.
  4482. The object IDs come from the slice_info.config file in the 3MF.
  4483. Args:
  4484. object_ids: List of identify_id values from slice_info.config
  4485. Returns:
  4486. True if command was sent, False otherwise
  4487. """
  4488. if not self._client or not self.state.connected:
  4489. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  4490. return False
  4491. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  4492. logger.warning(
  4493. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  4494. )
  4495. return False
  4496. if not object_ids:
  4497. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  4498. return False
  4499. # Validate all IDs are integers
  4500. try:
  4501. obj_list = [int(oid) for oid in object_ids]
  4502. except (ValueError, TypeError) as e:
  4503. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  4504. return False
  4505. self._sequence_id += 1
  4506. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  4507. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4508. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  4509. # Track skipped objects in state
  4510. for oid in obj_list:
  4511. if oid not in self.state.skipped_objects:
  4512. self.state.skipped_objects.append(oid)
  4513. return True
  4514. def send_gcode(self, gcode: str) -> bool:
  4515. """Send G-code command(s) to the printer.
  4516. Multiple commands can be separated by newlines.
  4517. Args:
  4518. gcode: G-code command(s) to send
  4519. Returns:
  4520. True if command was sent, False otherwise
  4521. """
  4522. if not self._client or not self.state.connected:
  4523. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  4524. return False
  4525. self._sequence_id += 1
  4526. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  4527. # Use QoS 1 for reliable delivery (at least once)
  4528. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4529. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  4530. return True
  4531. def set_bed_temperature(self, target: int) -> bool:
  4532. """Set the bed target temperature.
  4533. Args:
  4534. target: Target temperature in Celsius (0 to turn off)
  4535. Returns:
  4536. True if command was sent, False otherwise
  4537. """
  4538. return self.send_gcode(f"M140 S{target}")
  4539. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  4540. """Set the nozzle target temperature.
  4541. Args:
  4542. target: Target temperature in Celsius (0 to turn off)
  4543. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  4544. Returns:
  4545. True if command was sent, False otherwise
  4546. """
  4547. # Use M104 for non-blocking
  4548. # Always use T parameter for H2D compatibility
  4549. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  4550. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  4551. # Track it locally so we can display it correctly
  4552. if result and nozzle == 1:
  4553. self.state.temperatures["nozzle_target"] = float(target)
  4554. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  4555. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  4556. return result
  4557. def set_chamber_temperature(self, target: int) -> bool:
  4558. """Set the chamber target temperature.
  4559. Args:
  4560. target: Target temperature in Celsius (0 to turn off heating)
  4561. Returns:
  4562. True if command was sent, False otherwise
  4563. """
  4564. # M141 sets chamber temperature
  4565. result = self.send_gcode(f"M141 S{target}")
  4566. # Track chamber target locally (MQTT reports encoded values that need filtering)
  4567. if result:
  4568. self.state.temperatures["chamber_target"] = float(target)
  4569. self.state.temperatures["_chamber_target_set_time"] = time.time()
  4570. # Update heating state immediately based on new target
  4571. current_temp = self.state.temperatures.get("chamber", 0)
  4572. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  4573. logger.info(
  4574. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  4575. )
  4576. return result
  4577. def set_print_speed(self, mode: int) -> bool:
  4578. """Set the print speed mode.
  4579. Args:
  4580. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  4581. Returns:
  4582. True if command was sent, False otherwise
  4583. """
  4584. if not self._client or not self.state.connected:
  4585. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  4586. return False
  4587. if mode not in (1, 2, 3, 4):
  4588. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  4589. return False
  4590. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  4591. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4592. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  4593. return True
  4594. def set_fan_speed(self, fan: int, speed: int) -> bool:
  4595. """Set fan speed.
  4596. Args:
  4597. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber)
  4598. speed: Speed 0-255 (0=off, 255=full)
  4599. Returns:
  4600. True if command was sent, False otherwise
  4601. """
  4602. if fan not in (1, 2, 3):
  4603. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  4604. return False
  4605. speed = max(0, min(255, speed)) # Clamp to 0-255
  4606. return self.send_gcode(f"M106 P{fan} S{speed}")
  4607. def set_part_fan(self, speed: int) -> bool:
  4608. """Set part cooling fan speed (0-255)."""
  4609. return self.set_fan_speed(1, speed)
  4610. def set_aux_fan(self, speed: int) -> bool:
  4611. """Set auxiliary fan speed (0-255)."""
  4612. return self.set_fan_speed(2, speed)
  4613. def set_chamber_fan(self, speed: int) -> bool:
  4614. """Set chamber fan speed (0-255)."""
  4615. return self.set_fan_speed(3, speed)
  4616. def set_airduct_mode(self, mode: str) -> bool:
  4617. """Set air conditioning mode (cooling or heating).
  4618. Args:
  4619. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  4620. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  4621. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  4622. closes top exhaust flap
  4623. Returns:
  4624. True if command was sent, False otherwise
  4625. """
  4626. if not self._client or not self.state.connected:
  4627. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  4628. return False
  4629. self._sequence_id += 1
  4630. mode_id = 0 if mode == "cooling" else 1
  4631. command = {
  4632. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  4633. }
  4634. # Use QoS 1 for reliable delivery
  4635. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4636. logger.info(
  4637. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  4638. )
  4639. return True
  4640. def set_chamber_light(self, on: bool) -> bool:
  4641. """Turn chamber light on or off.
  4642. Args:
  4643. on: True to turn on, False to turn off
  4644. Returns:
  4645. True if command was sent, False otherwise
  4646. """
  4647. if not self._client or not self.state.connected:
  4648. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  4649. return False
  4650. mode = "on" if on else "off"
  4651. # Control both chamber lights (some printers like H2D have two)
  4652. for led_node in ["chamber_light", "chamber_light2"]:
  4653. self._sequence_id += 1
  4654. command = {
  4655. "system": {
  4656. "command": "ledctrl",
  4657. "led_node": led_node,
  4658. "led_mode": mode,
  4659. "led_on_time": 500,
  4660. "led_off_time": 500,
  4661. "loop_times": 0,
  4662. "interval_time": 0,
  4663. "sequence_id": str(self._sequence_id),
  4664. }
  4665. }
  4666. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4667. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  4668. return True
  4669. def select_extruder(self, extruder: int) -> bool:
  4670. """Select the active extruder for dual-nozzle printers (H2D).
  4671. Args:
  4672. extruder: Extruder index (0=right, 1=left for H2D)
  4673. Returns:
  4674. True if command was sent, False otherwise
  4675. """
  4676. if extruder not in (0, 1):
  4677. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  4678. return False
  4679. if not self._client or not self.state.connected:
  4680. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  4681. return False
  4682. # H2D extruder switching via select_extruder command
  4683. # Command format captured from OrcaSlicer:
  4684. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  4685. # extruder_index: 0 = RIGHT, 1 = LEFT
  4686. self._sequence_id += 1
  4687. command = {
  4688. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  4689. }
  4690. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4691. logger.info(
  4692. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  4693. )
  4694. return True
  4695. def home_axes(self, axes: str = "XYZ") -> bool:
  4696. """Run the printer's full auto-home sequence.
  4697. The ``axes`` argument is ignored: a bare ``G28`` is always sent so
  4698. Bambu firmware runs its safe multi-step routine (park toolhead →
  4699. home XY → home Z). Partial-axis variants like ``G28 Z`` skip the
  4700. toolhead-park step and can crash the bed into the toolhead on H2C
  4701. / H2D / H2S / X1 where Z-home moves the bed UP — see #1052.
  4702. """
  4703. return self.send_gcode("G28")
  4704. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  4705. """Move an axis by a relative distance.
  4706. Args:
  4707. axis: Axis to move ("X", "Y", or "Z")
  4708. distance: Distance to move in mm (positive or negative)
  4709. speed: Movement speed in mm/min
  4710. Returns:
  4711. True if command was sent, False otherwise
  4712. """
  4713. axis = axis.upper()
  4714. if axis not in ("X", "Y", "Z"):
  4715. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  4716. return False
  4717. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  4718. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  4719. return self.send_gcode(gcode)
  4720. def disable_motors(self) -> bool:
  4721. """Disable all stepper motors.
  4722. Warning: This will cause the printer to lose its position.
  4723. A homing operation will be required before printing.
  4724. Returns:
  4725. True if command was sent, False otherwise
  4726. """
  4727. return self.send_gcode("M18")
  4728. def enable_motors(self) -> bool:
  4729. """Enable all stepper motors.
  4730. Returns:
  4731. True if command was sent, False otherwise
  4732. """
  4733. return self.send_gcode("M17")
  4734. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  4735. """Load filament from a specific AMS tray.
  4736. Args:
  4737. tray_id: Global tray ID — 0..15 for AMS slots, 254 for external spool
  4738. (single-external printers and Ext-L on dual-nozzle H2D),
  4739. 255 for Ext-R on dual-nozzle H2D.
  4740. extruder_id: Unused - kept for API compatibility
  4741. Returns:
  4742. True if command was sent, False otherwise
  4743. """
  4744. if not self._client or not self.state.connected:
  4745. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  4746. return False
  4747. # Build the ams_change_filament command. Encoding differs by target type:
  4748. # - AMS slots (0..15): slot_id is the local slot, curr/tar_temp = -1.
  4749. # - External spool (tray_id=254): legacy capture from a single-extruder
  4750. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  4751. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  4752. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  4753. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  4754. self._sequence_id += 1
  4755. if tray_id == 255:
  4756. ams_id = 255
  4757. slot_id = 0 # extruder index for the right nozzle
  4758. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  4759. if right_temp < 180:
  4760. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  4761. curr_temp = right_temp
  4762. tar_temp = right_temp
  4763. elif tray_id == 254:
  4764. ams_id = 255
  4765. slot_id = 254
  4766. curr_temp = -1
  4767. tar_temp = -1
  4768. else:
  4769. ams_id = tray_id // 4
  4770. slot_id = tray_id % 4
  4771. curr_temp = -1
  4772. tar_temp = -1
  4773. command = {
  4774. "print": {
  4775. "command": "ams_change_filament",
  4776. "sequence_id": str(self._sequence_id),
  4777. "ams_id": ams_id,
  4778. "slot_id": slot_id,
  4779. "target": tray_id,
  4780. "curr_temp": curr_temp,
  4781. "tar_temp": tar_temp,
  4782. }
  4783. }
  4784. command_json = json.dumps(command)
  4785. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  4786. self._client.publish(self.topic_publish, command_json, qos=1)
  4787. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  4788. # Track this load request for H2D dual-nozzle disambiguation
  4789. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  4790. self._last_load_tray_id = tray_id
  4791. self.state.pending_tray_target = tray_id
  4792. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  4793. return True
  4794. def ams_unload_filament(self) -> bool:
  4795. """Unload the currently loaded filament.
  4796. Returns:
  4797. True if command was sent, False otherwise
  4798. """
  4799. if not self._client or not self.state.connected:
  4800. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  4801. return False
  4802. # Get the currently loaded tray info
  4803. tray_now = self.state.tray_now
  4804. logger.info("[%s] Unload requested, tray_now=%s", self.serial_number, tray_now)
  4805. # Determine source ams_id for the unload command
  4806. if tray_now == 255 or tray_now == 254:
  4807. ams_id = 255 # No filament or external spool
  4808. else:
  4809. ams_id = tray_now // 4 # Source AMS
  4810. # Command format from BambuStudio traffic capture:
  4811. # - No extruder_id field
  4812. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  4813. # - slot_id=255 and target=255 for unload
  4814. # Get current nozzle temperature for the unload command
  4815. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  4816. if nozzle_temp < 180:
  4817. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  4818. self._sequence_id += 1
  4819. command = {
  4820. "print": {
  4821. "command": "ams_change_filament",
  4822. "sequence_id": str(self._sequence_id),
  4823. "ams_id": ams_id,
  4824. "slot_id": 255, # 255 = unload marker
  4825. "target": 255, # 255 = unload destination
  4826. "curr_temp": nozzle_temp,
  4827. "tar_temp": nozzle_temp,
  4828. }
  4829. }
  4830. command_json = json.dumps(command)
  4831. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  4832. self._client.publish(self.topic_publish, command_json, qos=1)
  4833. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  4834. # Clear tracked load request since we're unloading
  4835. self._last_load_tray_id = None
  4836. self.state.pending_tray_target = None
  4837. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  4838. return True
  4839. def ams_control(self, action: str) -> bool:
  4840. """Control AMS operations.
  4841. Args:
  4842. action: "resume", "reset", or "pause"
  4843. Returns:
  4844. True if command was sent, False otherwise
  4845. """
  4846. if not self._client or not self.state.connected:
  4847. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  4848. return False
  4849. if action not in ("resume", "reset", "pause"):
  4850. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  4851. return False
  4852. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  4853. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4854. logger.info("[%s] AMS control: %s", self.serial_number, action)
  4855. return True
  4856. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  4857. """Trigger RFID re-read for a specific AMS tray.
  4858. Args:
  4859. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  4860. tray_id: Tray ID within the AMS (0-3)
  4861. Returns:
  4862. Tuple of (success, message)
  4863. """
  4864. if not self._client or not self.state.connected:
  4865. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  4866. return False, "Printer not connected"
  4867. # Check if filament is currently loaded (tray_now != 255)
  4868. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  4869. tray_now = self.state.tray_now
  4870. if tray_now != 255:
  4871. # Decode which tray is loaded for the message
  4872. if tray_now == 254:
  4873. loaded_tray = "external spool"
  4874. elif tray_now >= 0 and tray_now < 128:
  4875. loaded_ams = tray_now // 4
  4876. loaded_slot = tray_now % 4
  4877. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  4878. else:
  4879. loaded_tray = f"tray {tray_now}"
  4880. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  4881. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  4882. # Use ams_get_rfid command to trigger RFID re-read
  4883. # This command is used by Bambu Studio to re-read the RFID tag
  4884. command = {"print": {"command": "ams_get_rfid", "ams_id": ams_id, "slot_id": tray_id, "sequence_id": "0"}}
  4885. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4886. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  4887. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  4888. def ams_set_filament_setting(
  4889. self,
  4890. ams_id: int,
  4891. tray_id: int,
  4892. tray_info_idx: str,
  4893. tray_type: str,
  4894. tray_sub_brands: str,
  4895. tray_color: str,
  4896. nozzle_temp_min: int,
  4897. nozzle_temp_max: int,
  4898. setting_id: str = "",
  4899. ) -> bool:
  4900. """Set AMS tray filament settings (type, color, temperature).
  4901. Note: K value is set separately via extrusion_cali_sel command.
  4902. Args:
  4903. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4904. tray_id: Tray ID within the AMS (0-3)
  4905. tray_info_idx: Filament ID short format (e.g., "GFL05")
  4906. tray_type: Filament type (e.g., "PLA", "PETG")
  4907. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  4908. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  4909. nozzle_temp_min: Minimum nozzle temperature
  4910. nozzle_temp_max: Maximum nozzle temperature
  4911. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  4912. Returns:
  4913. True if command was sent, False otherwise
  4914. """
  4915. if not self._client or not self.state.connected:
  4916. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  4917. return False
  4918. # Calculate mqtt IDs based on AMS type.
  4919. # External-spool convention verified against a BambuStudio→X1C packet capture
  4920. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  4921. # *global* tray index in `tray_id`, not a local position within the virtual
  4922. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  4923. # is what the original code was matching — but the request and response
  4924. # use different semantics for that field. Sending `tray_id: 0` is what
  4925. # the P1S in #1279 rejected with `result: "fail"`.
  4926. if ams_id == 255:
  4927. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4928. if len(vt_tray) > 1:
  4929. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4930. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  4931. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  4932. # captured Studio→H2D exchange confirms the correct value.
  4933. mqtt_ams_id = 254 + tray_id
  4934. mqtt_tray_id = 0
  4935. else:
  4936. # Single external slot (X1C, P1S, A1): global tray_id=254.
  4937. mqtt_ams_id = 255
  4938. mqtt_tray_id = 254
  4939. slot_id = 0
  4940. elif ams_id <= 3:
  4941. mqtt_ams_id = ams_id
  4942. mqtt_tray_id = tray_id
  4943. slot_id = tray_id
  4944. else:
  4945. # AMS-HT: single tray per unit
  4946. mqtt_ams_id = ams_id
  4947. mqtt_tray_id = tray_id
  4948. slot_id = 0
  4949. command = {
  4950. "print": {
  4951. "command": "ams_filament_setting",
  4952. "ams_id": mqtt_ams_id,
  4953. "tray_id": mqtt_tray_id,
  4954. "slot_id": slot_id,
  4955. "tray_info_idx": tray_info_idx,
  4956. "tray_type": tray_type,
  4957. "tray_sub_brands": tray_sub_brands,
  4958. "tray_color": tray_color,
  4959. "nozzle_temp_min": nozzle_temp_min,
  4960. "nozzle_temp_max": nozzle_temp_max,
  4961. "sequence_id": "0",
  4962. }
  4963. }
  4964. # Include setting_id if provided (helps slicer show correct profile)
  4965. if setting_id:
  4966. command["print"]["setting_id"] = setting_id
  4967. command_json = json.dumps(command)
  4968. logger.info(
  4969. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  4970. )
  4971. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  4972. self._client.publish(self.topic_publish, command_json, qos=1)
  4973. self._last_ams_cmd_time = time.monotonic()
  4974. return True
  4975. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  4976. """Reset an AMS slot to empty/unconfigured state.
  4977. Args:
  4978. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4979. tray_id: Tray ID within the AMS (0-3)
  4980. Returns:
  4981. True if command was sent, False otherwise
  4982. """
  4983. if not self._client or not self.state.connected:
  4984. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  4985. return False
  4986. # Calculate mqtt IDs based on AMS type — same convention as
  4987. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  4988. if ams_id == 255:
  4989. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4990. if len(vt_tray) > 1:
  4991. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4992. mqtt_ams_id = 254 + tray_id
  4993. mqtt_tray_id = 0
  4994. else:
  4995. # Single external slot (X1C, P1S, A1): global tray_id=254.
  4996. mqtt_ams_id = 255
  4997. mqtt_tray_id = 254
  4998. slot_id = 0
  4999. elif ams_id <= 3:
  5000. mqtt_ams_id = ams_id
  5001. mqtt_tray_id = tray_id
  5002. slot_id = tray_id
  5003. else:
  5004. # AMS-HT: single tray per unit
  5005. mqtt_ams_id = ams_id
  5006. mqtt_tray_id = tray_id
  5007. slot_id = 0
  5008. command = {
  5009. "print": {
  5010. "command": "ams_filament_setting",
  5011. "ams_id": mqtt_ams_id,
  5012. "tray_id": mqtt_tray_id,
  5013. "slot_id": slot_id,
  5014. "tray_info_idx": "",
  5015. "tray_type": "",
  5016. "tray_sub_brands": "",
  5017. "tray_color": "00000000",
  5018. "nozzle_temp_min": 0,
  5019. "nozzle_temp_max": 0,
  5020. "sequence_id": "0",
  5021. }
  5022. }
  5023. command_json = json.dumps(command)
  5024. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  5025. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  5026. self._client.publish(self.topic_publish, command_json, qos=1)
  5027. self._last_ams_cmd_time = time.monotonic()
  5028. return True
  5029. def extrusion_cali_sel(
  5030. self,
  5031. ams_id: int,
  5032. tray_id: int,
  5033. cali_idx: int,
  5034. filament_id: str,
  5035. nozzle_diameter: str = "0.4",
  5036. ) -> bool:
  5037. """Set calibration profile (K value) for an AMS slot.
  5038. This command selects a K profile from the printer's calibration list.
  5039. Use cali_idx=-1 to use the default K value (0.020).
  5040. Note: Do NOT send setting_id in this command — BambuStudio never includes
  5041. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  5042. Args:
  5043. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  5044. tray_id: Tray ID within the AMS (0-3)
  5045. cali_idx: Calibration profile index (-1 for default)
  5046. filament_id: Filament preset ID (same as tray_info_idx)
  5047. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  5048. Returns:
  5049. True if command was sent, False otherwise
  5050. """
  5051. if not self._client or not self.state.connected:
  5052. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  5053. return False
  5054. # Calculate mqtt IDs based on AMS type.
  5055. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  5056. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  5057. if ams_id == 255:
  5058. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  5059. # ams_filament_setting which uses LOCAL tray_id=0).
  5060. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5061. if len(vt_tray) > 1:
  5062. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  5063. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  5064. mqtt_ams_id = 254 + tray_id
  5065. mqtt_tray_id = 254 + tray_id
  5066. else:
  5067. # Single external slot (X1C, P1S, A1): global tray_id=254
  5068. mqtt_ams_id = 254
  5069. mqtt_tray_id = 254
  5070. slot_id = 0
  5071. elif ams_id <= 3:
  5072. mqtt_ams_id = ams_id
  5073. mqtt_tray_id = ams_id * 4 + tray_id
  5074. slot_id = tray_id
  5075. elif ams_id >= 128 and ams_id <= 135:
  5076. mqtt_ams_id = ams_id
  5077. mqtt_tray_id = tray_id
  5078. slot_id = 0
  5079. else:
  5080. mqtt_ams_id = ams_id
  5081. mqtt_tray_id = tray_id
  5082. slot_id = 0
  5083. command = {
  5084. "print": {
  5085. "command": "extrusion_cali_sel",
  5086. "cali_idx": cali_idx,
  5087. "filament_id": filament_id,
  5088. "nozzle_diameter": nozzle_diameter,
  5089. "ams_id": mqtt_ams_id,
  5090. "tray_id": mqtt_tray_id,
  5091. "slot_id": slot_id,
  5092. "sequence_id": "0",
  5093. }
  5094. }
  5095. command_json = json.dumps(command)
  5096. logger.info(
  5097. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  5098. )
  5099. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  5100. self._client.publish(self.topic_publish, command_json, qos=1)
  5101. return True
  5102. def extrusion_cali_set(
  5103. self,
  5104. tray_id: int,
  5105. k_value: float,
  5106. nozzle_diameter: str = "0.4",
  5107. nozzle_temp: int = 220,
  5108. filament_id: str = "",
  5109. setting_id: str = "",
  5110. name: str = "",
  5111. cali_idx: int = -1,
  5112. ) -> bool:
  5113. """Directly set K value (pressure advance) for a tray.
  5114. Uses the filaments array format required by current firmware.
  5115. Args:
  5116. tray_id: Global tray ID (ams_id * 4 + slot)
  5117. k_value: Pressure advance K value (e.g., 0.020)
  5118. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  5119. nozzle_temp: Nozzle temperature for calibration reference
  5120. filament_id: Filament preset ID (e.g., "GFA02")
  5121. setting_id: Setting ID (e.g., "GFSA02_07")
  5122. name: Profile display name
  5123. cali_idx: Calibration index (-1 for new)
  5124. Returns:
  5125. True if command was sent, False otherwise
  5126. """
  5127. if not self._client or not self.state.connected:
  5128. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  5129. return False
  5130. nozzle_id = f"HS00-{nozzle_diameter}"
  5131. filament_entry = {
  5132. "ams_id": 0,
  5133. "cali_idx": cali_idx,
  5134. "extruder_id": 0,
  5135. "filament_id": filament_id,
  5136. "k_value": f"{k_value:.6f}",
  5137. "n_coef": "1.400000",
  5138. "name": name,
  5139. "nozzle_diameter": nozzle_diameter,
  5140. "nozzle_id": nozzle_id,
  5141. "setting_id": setting_id,
  5142. "tray_id": tray_id,
  5143. }
  5144. command = {
  5145. "print": {
  5146. "command": "extrusion_cali_set",
  5147. "filaments": [filament_entry],
  5148. "nozzle_diameter": nozzle_diameter,
  5149. "sequence_id": str(self._sequence_id),
  5150. }
  5151. }
  5152. command_json = json.dumps(command)
  5153. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  5154. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  5155. self._client.publish(self.topic_publish, command_json, qos=1)
  5156. return True
  5157. def set_timelapse(self, enable: bool) -> bool:
  5158. """Enable or disable timelapse recording.
  5159. Args:
  5160. enable: True to enable, False to disable
  5161. Returns:
  5162. True if command was sent, False otherwise
  5163. """
  5164. if not self._client or not self.state.connected:
  5165. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  5166. return False
  5167. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  5168. # First send the timelapse setting
  5169. timelapse_cmd = {
  5170. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  5171. }
  5172. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  5173. # Request status update
  5174. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5175. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  5176. return True
  5177. def set_liveview(self, enable: bool) -> bool:
  5178. """Enable or disable live view / camera streaming.
  5179. Args:
  5180. enable: True to enable, False to disable
  5181. Returns:
  5182. True if command was sent, False otherwise
  5183. """
  5184. if not self._client or not self.state.connected:
  5185. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  5186. return False
  5187. command = {
  5188. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  5189. }
  5190. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5191. # Request status update
  5192. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  5193. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  5194. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  5195. return True
  5196. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  5197. """Dispatch the user's choice from the HMS-error modal as a printer command.
  5198. Args:
  5199. print_error: Canonical hex identifier for the fault — 8 chars for the
  5200. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  5201. (HMSError.full_code). Carried through unchanged from the route.
  5202. Converted to its DECIMAL string form for the `ignore` /
  5203. `idle_ignore` commands' `err` field, which is what the firmware
  5204. actually compares against the active fault. The pre-#1869
  5205. hex-string `err` was silently rejected because the firmware was
  5206. being asked to match `"05008051"` against int 0x05008051
  5207. (= 83918929 decimal) — see BambuStudio's
  5208. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  5209. `std::to_string(int m_error_code)`.
  5210. action: One of HMSAction's string values.
  5211. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  5212. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  5213. shapes; empty string is the no-job-id sentinel.
  5214. Returns False when the MQTT client is offline or when `action` is unknown
  5215. so the route surfaces it as a 4xx rather than a silent no-op.
  5216. """
  5217. if not self._client or not self.state.connected:
  5218. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  5219. return False
  5220. # Always re-push the full state after a command so the modal's underlying
  5221. # status query reflects the new error list (or absence) on the next tick.
  5222. def publish(payload: dict):
  5223. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  5224. self._client.publish(
  5225. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  5226. )
  5227. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  5228. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  5229. # every command_hms_* call). Our route hands us the hex string —
  5230. # convert. Falls back to the raw input if it's not parseable so the
  5231. # firmware can reject it and the route can surface 502 instead of us
  5232. # raising ValueError mid-dispatch.
  5233. try:
  5234. err_decimal = str(int(print_error, 16))
  5235. except ValueError:
  5236. err_decimal = print_error
  5237. def hms_resume():
  5238. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  5239. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  5240. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  5241. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  5242. # shape historically because it works, and changing it without a
  5243. # field test risks regressing a path that the user has confirmed.
  5244. publish(
  5245. {
  5246. "print": {
  5247. "command": "resume",
  5248. "param": "",
  5249. "sequence_id": "0",
  5250. }
  5251. }
  5252. )
  5253. def hms_stop():
  5254. # Same as hms_resume — plain shape, confirmed working by the user
  5255. # for "Stop Printing".
  5256. publish(
  5257. {
  5258. "print": {
  5259. "command": "stop",
  5260. "param": "",
  5261. "sequence_id": "0",
  5262. }
  5263. }
  5264. )
  5265. def hms_ignore_command():
  5266. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  5267. # what the "Ignore this and Resume" button actually publishes.
  5268. # Distinct from `idle_ignore`: this command has the firmware
  5269. # suppress the next re-check of the named fault AND resume the
  5270. # paused print in a single operation. The previous Bambuddy code
  5271. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  5272. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  5273. # the problem, re-check normally" so the firmware re-detected the
  5274. # wrong plate and re-paused with the same code (#1869).
  5275. #
  5276. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  5277. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  5278. # variant of "don't remind next time" lives on `idle_ignore`'s
  5279. # type=1, not as a separate ignore shape.
  5280. publish(
  5281. {
  5282. "print": {
  5283. "command": "ignore",
  5284. "err": err_decimal,
  5285. "param": "reserve",
  5286. "job_id": job_id or "",
  5287. "sequence_id": "0",
  5288. }
  5289. }
  5290. )
  5291. def hms_idle_ignore(persistent: bool = False):
  5292. # `idle_ignore` is BambuStudio's "dismiss this warning without
  5293. # resuming" command for non-pause warnings — what
  5294. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  5295. # type=0 dismisses once, type=1 suppresses the same warning
  5296. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  5297. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  5298. # NOT via the resume-bearing `ignore` command.
  5299. publish(
  5300. {
  5301. "print": {
  5302. "command": "idle_ignore",
  5303. "err": err_decimal,
  5304. "type": 1 if persistent else 0,
  5305. "sequence_id": "0",
  5306. }
  5307. }
  5308. )
  5309. def ams_control(param: str):
  5310. publish(
  5311. {
  5312. "print": {
  5313. "command": "ams_control",
  5314. "param": param,
  5315. "sequence_id": "0",
  5316. }
  5317. }
  5318. )
  5319. def clean_print_error():
  5320. # Matches the existing `clear_hms_errors` shape — Bambu does not
  5321. # expect `print_error` in the body; the command clears whatever
  5322. # error dialog is currently active on the printer.
  5323. publish(
  5324. {
  5325. "print": {
  5326. "command": "clean_print_error",
  5327. "sequence_id": "0",
  5328. }
  5329. }
  5330. )
  5331. def uiop_close():
  5332. # `err` is the 8-char hex short code (already a string from the
  5333. # frontend), uppercased for consistency with how BambuStudio sends it.
  5334. publish(
  5335. {
  5336. "system": {
  5337. "command": "uiop",
  5338. "name": "print_error",
  5339. "action": "close",
  5340. "source": 1,
  5341. "type": "dialog",
  5342. "err": print_error.upper(),
  5343. "sequence_id": "0",
  5344. }
  5345. }
  5346. )
  5347. match action:
  5348. case (
  5349. HMSAction.RESUME_PRINTING
  5350. | HMSAction.RESUME_PRINTING_DEFECTS
  5351. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  5352. | HMSAction.PROBLEM_SOLVED_RESUME
  5353. | HMSAction.FILAMENT_LOAD_RESUME
  5354. | HMSAction.PROCEED
  5355. ):
  5356. hms_resume()
  5357. case HMSAction.STOP_PRINTING:
  5358. hms_stop()
  5359. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  5360. # All three buttons map to BambuStudio's `command_hms_ignore`
  5361. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  5362. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  5363. # responsibility — the wire shape is identical.
  5364. hms_ignore_command()
  5365. case HMSAction.NO_REMINDER_NEXT_TIME:
  5366. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  5367. # `command_hms_idle_ignore` with type=0
  5368. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  5369. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  5370. # dismisses the dialog.
  5371. hms_idle_ignore(persistent=False)
  5372. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  5373. ams_control("done")
  5374. case (
  5375. HMSAction.RETRY_FILAMENT_EXTRUDED
  5376. | HMSAction.CONTINUE
  5377. | HMSAction.RETRY_PROBLEM_SOLVED
  5378. | HMSAction.DBL_CHECK_RETRY
  5379. ):
  5380. ams_control("resume")
  5381. case HMSAction.ABORT:
  5382. ams_control("abort")
  5383. case HMSAction.OK_BUTTON:
  5384. clean_print_error()
  5385. case HMSAction.DBL_CHECK_OK:
  5386. clean_print_error()
  5387. uiop_close()
  5388. case HMSAction.DBL_CHECK_RESUME:
  5389. # Plain resume — not HMS-aware, no err/job_id.
  5390. publish(
  5391. {
  5392. "print": {
  5393. "command": "resume",
  5394. "param": "",
  5395. "sequence_id": "0",
  5396. }
  5397. }
  5398. )
  5399. case HMSAction.REFRESH_NOZZLE:
  5400. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  5401. case HMSAction.TURN_OFF_FIRE_ALARM:
  5402. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  5403. case HMSAction.STOP_DRYING:
  5404. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  5405. case HMSAction.DISABLE_PURIFICATION:
  5406. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  5407. case (
  5408. HMSAction.CHECK_ASSISTANT
  5409. | HMSAction.JUMP_TO_LIVEVIEW
  5410. | HMSAction.OK_JUMP_RACK
  5411. | HMSAction.REMOVE_CLOSE_BTN
  5412. | HMSAction.LOAD_VIRTUAL_TRAY
  5413. | HMSAction.CANCLE
  5414. | HMSAction.DBL_CHECK_CANCEL
  5415. ):
  5416. # UI-only actions — the printer's own screen handles these; the
  5417. # modal still surfaces them so the user has parity with Studio.
  5418. pass
  5419. case _:
  5420. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  5421. return False
  5422. return True