bambu_mqtt.py 471 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320
  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. from backend.app.services.hms_errors import alert_level_from_print_error, describe_fault
  22. from backend.app.utils.ams_drying import ACTIVE_DRY_STATUSES, DRY_COUNTDOWN_STALL_SECONDS
  23. from backend.app.utils.ams_humidity import ams_humidity_percent
  24. from backend.app.utils.paho_teardown import discard_queued_publishes, retire_paho_client
  25. from backend.app.utils.tray_ids import (
  26. AMS3H_UNIT_ID,
  27. RACK_SLOT_COUNT,
  28. AmsType,
  29. TrayLayout,
  30. ams_type_from_info,
  31. decode_wire_slot,
  32. external_tray_id,
  33. global_tray_id,
  34. is_ams_ht_id,
  35. is_external_tray,
  36. is_rack_ams,
  37. legacy_tray_index,
  38. mapped_trays_with_slot,
  39. reconcile_use_ams,
  40. reports_no_ams,
  41. tray_flag_bit,
  42. unit_ams_type,
  43. unit_label,
  44. )
  45. logger = logging.getLogger(__name__)
  46. # How long a manual load's tray target stays a hint for an H2D's tray_now: long
  47. # enough for a real load to report, short enough that a refused one cannot
  48. # relabel a later print's load of the same slot number (FW-C7).
  49. PENDING_TRAY_TARGET_TTL = 120.0
  50. # AMS module name prefixes used in get_version responses.
  51. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  52. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  53. # "ams_f1/<id>" – AMS Lite (A1, A1 Mini; the A2L reports id 16, stored as 6)
  54. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  55. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  56. # "n10a" – AMS 3H (H3C), no suffix: read as "n10a/<its unit id>"
  57. _AMS_MODULE_PREFIXES = ("ams/", "ams_f1/", "n3f/", "n3s/", "n10a/")
  58. # gcode_state values that mean the printer is not idle and must not be handed a
  59. # new start-print (#2598). The firmware rejects a project_file while busy with
  60. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  61. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  62. # are valid start targets and are deliberately excluded. Mirrors
  63. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  64. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  65. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  66. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  67. # ended the cycle on schedule or aborted it. More than this many minutes still on
  68. # the clock means it was cut short, and the firmware's own reason codes are worth
  69. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  70. # left), and the log said only "drying complete", so the report carried no
  71. # evidence of why. The margin absorbs a stale last observation between AMS
  72. # pushes; it is not a judgement about how short "short" is.
  73. _EARLY_DRY_END_MINUTES = 5
  74. # CONNACK reason codes that mean the printer actively refused our credentials,
  75. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  76. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  77. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  78. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  79. # code (or, on some firmware, the serial used as the username) is wrong.
  80. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  81. # Short, stable slugs recorded on the client and surfaced to the connection
  82. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  83. # frontend picks a localized message key off these.
  84. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  85. CONNECT_ERROR_REFUSED = "refused"
  86. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  87. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  88. OrcaSlicer reads bit 18 of the hex string via
  89. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  90. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  91. that doesn't yield a clean integer so downstream consumers preserve today's
  92. behaviour rather than treating "absent" as "OFF".
  93. """
  94. if not isinstance(cfg_raw, str) or not cfg_raw:
  95. return None
  96. try:
  97. return bool((int(cfg_raw, 16) >> 18) & 1)
  98. except ValueError:
  99. return None
  100. def parse_ams_filament_backup_from_home_flag(home_flag: object) -> bool | None:
  101. """Extract AMS Filament Backup state from a push_status ``print.home_flag`` value.
  102. Bambu Studio reads bit 10 for every family (DeviceManager.cpp
  103. ``parse_home_flag``: ``SetAutoRefillEnabled((flag >> 10) & 0x1)``). It's
  104. the only source on the P1S, P1P, A1 and A1 Mini, which never send ``cfg``
  105. (#3259). On every printer that sends both, the two bits agree in all
  106. captured snapshots, ON and OFF alike. Returns ``None`` for anything that
  107. isn't an integer.
  108. """
  109. if isinstance(home_flag, bool) or not isinstance(home_flag, int):
  110. return None
  111. # Negative values are the 32-bit flag read as signed; bit 10 is the same.
  112. return bool((home_flag >> 10) & 1)
  113. def is_printer_status_frame(print_data: dict) -> bool:
  114. """True when a ``print`` payload is the printer reporting its own state.
  115. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  116. `project_file` ack carries whatever Bambuddy put on the wire — including
  117. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  118. telemetry means reading our own request back as the printer's state
  119. (#3040). Only `push_status` (and the odd firmware that omits `command`
  120. entirely on a status frame) describes the printer.
  121. """
  122. command = print_data.get("command")
  123. return command is None or command == "push_status"
  124. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  125. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  126. # firmware is internally inconsistent about it:
  127. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  128. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  129. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  130. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  131. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  132. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  133. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  134. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  135. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  136. A2L_LITE_PHYSICAL_AMS_ID = 16
  137. A2L_LITE_NORMALIZED_AMS_ID = 6
  138. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  139. def _ams_unit_order(unit: dict) -> tuple[int, str]:
  140. """Sort key for AMS units by id (#3499).
  141. Firmware sends unit ids as strings ("0"), while the A2L AMS Lite's id is
  142. normalised to the int 6, so an A2L with an AMS 2 Pro and an AMS Lite held
  143. both: comparing them raised, and the AMS card stayed empty. Numeric order,
  144. with anything unreadable last.
  145. """
  146. raw = unit.get("id", 0)
  147. try:
  148. return (int(raw), "")
  149. except (TypeError, ValueError):
  150. return (1 << 30, str(raw))
  151. def normalize_am_unit_id(ams_id: int) -> int:
  152. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  153. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  154. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  155. through untouched.
  156. """
  157. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  158. def wire_tray_color(tray_color: str | None) -> str:
  159. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  160. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  161. as a zero, and does it silently: the command response echoes the value you
  162. sent and reports ``result: "success"``, so only the next AMS push shows what
  163. was really stored. Measured on the reporter's machine (#2987), where the
  164. spool's own ``rgba`` is stored lowercase and went out verbatim:
  165. sent 09ff00ff -> AMS reports 09000000
  166. sent ff5100ff -> AMS reports 00510000
  167. sent 090000FF -> AMS reports 090000FF
  168. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  169. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  170. longer matches the spool that asked for it and the assignment is deleted
  171. seconds after being made -- and re-assigning through the slot modal writes
  172. the mangled colour back, because the modal seeds itself from the tray.
  173. Applied here, at the one place the command is built, rather than in each of
  174. the four callers: a caller that forgets is exactly how this arrived.
  175. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  176. blank stays blank, which is how a slot is cleared.
  177. """
  178. return (tray_color or "").strip().lstrip("#").upper()
  179. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  180. """Translate a normalised A2L slot back to the physical wire form.
  181. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  182. (normalised id 6), else ``None`` for every other unit.
  183. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  184. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  185. confirmed by capture: the physical **global** tray value the extrusion_cali
  186. commands put in `tray_id` — we extrapolate it as 16*4+slot = 64-67 to stay
  187. consistent with the physical unit id. BambuStudio's source sends 24+slot
  188. there instead (``GetTrayIndexMap``); a BambuStudio->A2L capture of a cali
  189. command would settle it, and it lives only here. Load's `target` is not this
  190. value: see ``change_filament_wire_ids``.
  191. """
  192. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  193. return None
  194. local_slot = tray_id % 4
  195. return (
  196. A2L_LITE_PHYSICAL_AMS_ID,
  197. local_slot,
  198. legacy_tray_index(A2L_LITE_PHYSICAL_AMS_ID, local_slot),
  199. )
  200. def change_filament_wire_ids(tray_id: int, layout: TrayLayout | None = None) -> tuple[int, int, int]:
  201. """``(ams_id, slot_id, target)`` of ``ams_change_filament`` for an AMS tray.
  202. As BambuStudio's ``command_ams_change_filament`` builds them: a regular AMS
  203. is addressed by unit and local slot with the global tray as target; a unit
  204. id of 16 or more (the A2L AMS-Lite's physical 16, an AMS-HT's 128-135) has
  205. the unit id itself as target. An AMS-HT holds one tray, so its global tray
  206. id is its unit id and its slot is 0.
  207. """
  208. if is_ams_ht_id(tray_id):
  209. return tray_id, 0, tray_id
  210. ams_id, slot_id = (layout or TrayLayout()).slot_key(tray_id)
  211. if (a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  212. return a2l[0], a2l[1], a2l[0]
  213. return ams_id, slot_id, tray_id
  214. # The H3C's AMS 3H is one unit (32, AMS type 6) with nine slots, numbered 28 + k
  215. # (utils.tray_ids). Its tray_now / tray_tar / tray_pre are the raw slot 0-8;
  216. # print.mapping and the snow fields encode a slot as (32 << 8) | k. Commands
  217. # address it as {ams_id: 32, slot_id: k}.
  218. AMS3H_MODULE_NAME = "n10a" # its get_version module (no "/<unit>" suffix)
  219. def _mqtt_int(value: object) -> int | None:
  220. """An MQTT id / number field as an int (they arrive as int or numeric str), else None."""
  221. if isinstance(value, bool) or not isinstance(value, (int, str)):
  222. return None
  223. try:
  224. return int(value)
  225. except ValueError:
  226. return None
  227. # AMS 3H drying (Bambu Studio 02.09, AMSDryControl.cpp): the unit reports
  228. # `zone_info[]` and only a zone with exactly two slots can dry; the others are
  229. # ambient readings. A drying start carries the filament's softening temperature
  230. # as `cooling_temp` (the preset's filament_dev_drying_softening_temperature).
  231. AMS3H_DRY_COOLING_TEMP = {"PLA": 65, "PETG": 75, "ABS": 95, "ASA": 95, "TPU": 70, "PA": 150, "PC": 120}
  232. AMS3H_DRY_COOLING_TEMP_DEFAULT = 50
  233. def ams3h_drying_zone(zone_info: object) -> dict | None:
  234. """The zone of an AMS 3H's `zone_info` that can dry: the first holding exactly two slots."""
  235. if not isinstance(zone_info, list):
  236. return None
  237. for zone in zone_info:
  238. if isinstance(zone, dict) and isinstance(zone.get("zone_slots"), list) and len(zone["zone_slots"]) == 2:
  239. return zone
  240. return None
  241. def ams3h_drying_cooling_temp(filament: str) -> int:
  242. """`cooling_temp` for an AMS 3H drying start: the filament's softening temperature."""
  243. base = (filament or "").upper().split("-")[0].split(" ")[0]
  244. return AMS3H_DRY_COOLING_TEMP.get(base, AMS3H_DRY_COOLING_TEMP_DEFAULT)
  245. def _ams3h_unit_drying_fields(unit: dict) -> dict:
  246. """An AMS 3H's drying state, which lives on its drying zone, lifted onto the unit."""
  247. zone = ams3h_drying_zone(unit.get("zone_info"))
  248. if zone is None:
  249. return {}
  250. fields: dict = {"dry_zone_id": zone.get("zone_id", 0), "dry_zone_slots": list(zone.get("zone_slots") or [])}
  251. for key in ("dry_time", "dry_setting", "dry_sf_reason"):
  252. if key in zone:
  253. fields[key] = zone[key]
  254. if "info" not in unit and "info" in zone:
  255. fields["info"] = zone["info"]
  256. if "humidity_raw" in zone:
  257. fields["dry_zone_humidity_raw"] = zone["humidity_raw"]
  258. if "temp" in zone:
  259. fields["dry_zone_temp"] = zone["temp"]
  260. return fields
  261. def _ams3h_unit_env_fields(unit: dict) -> dict:
  262. """An AMS 3H's humidity and temperature (the unit has none) from its first non-drying zone, as Studio shows it."""
  263. zones = unit.get("zone_info")
  264. if not isinstance(zones, list):
  265. return {}
  266. dry_zone = ams3h_drying_zone(zones)
  267. ambient = next((z for z in zones if isinstance(z, dict) and z is not dry_zone), None)
  268. if ambient is None:
  269. return {}
  270. return {key: ambient[key] for key in ("humidity_raw", "temp") if key in ambient and key not in unit}
  271. def apply_rack_ams_zone_fields(ams_list: object, known_types: dict[int, AmsType] | None = None) -> None:
  272. """Lift a rack AMS's per-zone readings and drying state onto the unit, in place (type from `info`, else ``known_types``)."""
  273. if not isinstance(ams_list, list):
  274. return
  275. for unit in ams_list:
  276. if not isinstance(unit, dict) or not isinstance(unit.get("zone_info"), list):
  277. continue
  278. uid = _mqtt_int(unit.get("id"))
  279. if uid is None:
  280. continue
  281. kind = ams_type_from_info(unit.get("info"))
  282. if kind is None:
  283. kind = (known_types or {}).get(uid, unit_ams_type(uid))
  284. if not is_rack_ams(kind):
  285. continue
  286. unit.update({**_ams3h_unit_env_fields(unit), **_ams3h_unit_drying_fields(unit)})
  287. def resolve_external_spools_in_mapping(
  288. ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool, layout: TrayLayout | None = None
  289. ) -> object:
  290. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  291. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  292. dispatch both write an external spool there as -1 -- the same value as a
  293. slot that isn't fed at all -- and carry the real target only in
  294. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  295. list alone turns "printed from the external spool" into "unmapped", and
  296. usage then lands on whatever tray the fallback guesses.
  297. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  298. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  299. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  300. printers, which have one external spool that the wire always calls 255.
  301. ``{255, 255}`` is the unmapped marker and stays -1.
  302. An A2L AMS-Lite tray is the local slot 0-3 in the flat list and
  303. ``{ams_id: 16, slot_id: n}`` in ``ams_mapping2``; it becomes its normalised
  304. global tray 24+n. Kept local, it read as a regular AMS tray, so usage was
  305. charged to the wrong spool. A rack AMS slot (``{ams_id: 32, slot_id: k}``)
  306. becomes its global tray 28+k, and on a rack printer each external input
  307. 247-255 keeps its own id. Every other entry is left exactly as captured.
  308. Without a usable ``ams_mapping2`` the input is returned unchanged.
  309. """
  310. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  311. return ams_mapping
  312. if len(ams_mapping2) != len(ams_mapping):
  313. return ams_mapping
  314. resolved = list(ams_mapping)
  315. layout = layout or TrayLayout()
  316. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  317. if not isinstance(detail, dict):
  318. continue
  319. ams_id = detail.get("ams_id")
  320. slot_id = detail.get("slot_id")
  321. if ams_id == A2L_LITE_PHYSICAL_AMS_ID and slot_id in (0, 1, 2, 3):
  322. resolved[i] = A2L_LITE_GLOBAL_BASE + slot_id
  323. continue
  324. if (
  325. isinstance(ams_id, int)
  326. and isinstance(slot_id, int)
  327. and not is_external_tray(ams_id, layout.rack)
  328. and is_rack_ams(layout.ams_type(ams_id))
  329. and 0 <= slot_id < RACK_SLOT_COUNT
  330. ):
  331. resolved[i] = layout.global_tray_id(ams_id, slot_id)
  332. continue
  333. if flat != -1 or not is_external_tray(ams_id, layout.rack) or slot_id == 255:
  334. continue
  335. resolved[i] = ams_id if is_dual_nozzle or layout.rack else 254
  336. return resolved
  337. def unit_reported_absent(ams_id, ams_list: list, ams_exist_bits) -> bool:
  338. """Whether a push that doesn't list AMS unit ``ams_id`` says it is unplugged.
  339. ``ams_exist_bits`` (hex) has bit n set for AMS unit n, measured on an X1C
  340. (unit 1 -> "2", none -> "0") and an H2C (units 0, 1, 2 and HT 128 -> "17").
  341. So an AMS unit 0-3 whose bit is clear is gone. An empty unit list with no
  342. bits set means no unit at all, which is what the X1C sends with its AMS
  343. unplugged. Anything else is kept, as the merge always did: a partial push
  344. lists only some units, and the bits of an AMS HT or AMS Lite next to other
  345. units are not measured well enough to read.
  346. """
  347. if ams_exist_bits is None:
  348. return False
  349. try:
  350. bits = int(ams_exist_bits, 16) if isinstance(ams_exist_bits, str) else int(ams_exist_bits)
  351. unit = int(ams_id)
  352. except (TypeError, ValueError):
  353. return False
  354. if bits == 0 and not ams_list:
  355. return True
  356. return 0 <= unit <= 3 and not bits >> unit & 1
  357. def apply_tray_exist_bits(
  358. units: list,
  359. tray_exist_bits_str: str | int | None,
  360. *,
  361. power_on_flag: bool = True,
  362. log_label: str | None = None,
  363. annotate_exists: bool = False,
  364. ) -> int:
  365. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  366. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  367. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  368. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  369. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  370. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  371. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  372. instead of guessing from payload shape (#1322, #147).
  373. Two callers share this helper to keep their views consistent:
  374. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  375. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  376. facing push_status (#1726 — without this the VP would forward stale
  377. per-tray fields for empty slots, and BambuStudio's Sync would render
  378. phantom loaded slots).
  379. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  380. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  381. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  382. so spool removal is detected without requiring a manual reconnect.
  383. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  384. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  385. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  386. authoritative empty signal for the HT — the only working clear path, since
  387. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  388. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  389. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  390. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  391. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  392. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  393. the raw physical id 16 get the same bit base as callers holding the
  394. normalised 6 (#2697).
  395. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  396. way). Ints are tolerated for defensive symmetry but typically not seen
  397. on the wire. ``None`` / empty / unparseable → no-op.
  398. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  399. every processed slot. This is firmware's authoritative "spool physically
  400. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  401. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  402. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  403. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  404. leaves it False so the ``exists`` key never reaches the slicer wire format.
  405. Mutates ``units`` in place. Returns the number of slots cleared.
  406. """
  407. if not tray_exist_bits_str:
  408. return 0
  409. try:
  410. if isinstance(tray_exist_bits_str, int):
  411. tray_exist_bits = tray_exist_bits_str
  412. else:
  413. tray_exist_bits = int(tray_exist_bits_str, 16)
  414. except (ValueError, TypeError):
  415. return 0
  416. if tray_exist_bits == 0 and not power_on_flag:
  417. return 0
  418. if not isinstance(units, list):
  419. return 0
  420. cleared = 0
  421. for ams_unit in units:
  422. if not isinstance(ams_unit, dict):
  423. continue
  424. ams_id_raw = ams_unit.get("id")
  425. if ams_id_raw is None:
  426. continue
  427. try:
  428. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  429. except (ValueError, TypeError):
  430. continue
  431. if not isinstance(ams_id, int):
  432. continue
  433. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  434. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  435. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  436. # the physical 16. Both mean bit base 24, so fold them together here
  437. # rather than relying on every caller to normalise first — reading 16 as
  438. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  439. ams_id = normalize_am_unit_id(ams_id)
  440. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  441. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  442. # A rack AMS (unit 32): its global tray id 28 + slot.
  443. # Anything outside those has no known bit layout — don't guess it.
  444. kind = unit_ams_type(ams_id, ams_unit.get("info"))
  445. if tray_flag_bit(ams_id, 0, kind) is None:
  446. continue
  447. for tray in ams_unit.get("tray", []):
  448. if not isinstance(tray, dict):
  449. continue
  450. tray_id_raw = tray.get("id")
  451. if tray_id_raw is None:
  452. continue
  453. try:
  454. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  455. except (ValueError, TypeError):
  456. continue
  457. if not isinstance(tray_id, int):
  458. continue
  459. global_bit = tray_flag_bit(ams_id, tray_id, kind)
  460. if global_bit is None or global_bit < 0:
  461. continue
  462. slot_exists = (tray_exist_bits >> global_bit) & 1
  463. if annotate_exists:
  464. tray["exists"] = bool(slot_exists)
  465. if slot_exists:
  466. continue
  467. tray["state"] = 9
  468. if tray.get("tray_type"):
  469. if log_label:
  470. logger.debug(
  471. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  472. f"(tray_exist_bits bit {global_bit} = 0)"
  473. )
  474. tray["tray_type"] = ""
  475. tray["tray_sub_brands"] = ""
  476. tray["tray_color"] = ""
  477. tray["tray_id_name"] = ""
  478. tray["tag_uid"] = "0000000000000000"
  479. tray["tray_uuid"] = "00000000000000000000000000000000"
  480. tray["tray_info_idx"] = ""
  481. tray["remain"] = 0
  482. cleared += 1
  483. return cleared
  484. def _external_slot_to_merge(pushed: object, existing: object) -> dict | None:
  485. """The one cached external slot a pushed ``vt_tray`` dict updates, or None (#3513).
  486. It updates the slot when it names no slot or the cached one's. A push that
  487. empties the slot (``tray_type`` ``""``) replaces it, so a removed spool
  488. keeps no preset, K value or temperatures, as does one naming another slot.
  489. """
  490. if not isinstance(pushed, dict) or not isinstance(existing, list) or len(existing) != 1:
  491. return None
  492. cached = existing[0]
  493. if not isinstance(cached, dict) or pushed.get("tray_type") == "":
  494. return None
  495. if "id" in pushed and str(pushed["id"]) != str(cached.get("id")):
  496. return None
  497. return cached
  498. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  499. #
  500. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  501. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  502. # rack position is never mistakable for the nozzle on the other carriage.
  503. #
  504. # Extruder indices are a different namespace that happens to overlap these
  505. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  506. # Nothing below may pass a value from one namespace to the other untranslated;
  507. # doing exactly that is what #2800 was.
  508. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  509. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  510. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  511. #
  512. # Briefly changed to the plate's own slot count on the strength of a single
  513. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  514. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  515. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  516. # a calibration job, so the length varies with whatever Studio is doing rather
  517. # than with the filament count -- which makes it the wrong thing to derive.
  518. _RACK_WIRE_SLOTS = 32
  519. # The two carriages, as extruder indices in the form the queue stores (already
  520. # translated through the file's physical_extruder_map).
  521. #
  522. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  523. #
  524. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  525. # extruder 1, AMS 1 and 2 feed extruder 0;
  526. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  527. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  528. # and that print completed. So extruder 1 is the fixed hotend and extruder
  529. # 0 is the rack;
  530. # - our own constants were internally inconsistent about it: physical nozzle
  531. # id N sits on extruder N (see the L/R split in PrintersPage), and
  532. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  533. # extruder index of 0.
  534. #
  535. # These were the other way round until then, which is what dispatched a plate
  536. # to the carriage that had not been levelled and printed its first layer in
  537. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  538. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  539. # which *wire* worked, and the extruder indices were only inferred from it by
  540. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  541. # wire result stands; the inference from it did not.
  542. _FIXED_EXTRUDER_ID = 1
  543. _RACK_EXTRUDER_ID = 0
  544. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  545. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  546. # outright, which would not start the job at all. Native BambuStudio captures
  547. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  548. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  549. _FIXED_NOZZLE_ID = 1
  550. def resolve_rack_nozzle_mapping(
  551. slot_extruders: list[int],
  552. rack_nozzle_id: int | None,
  553. ) -> list[int] | None:
  554. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  555. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  556. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  557. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  558. reports as live.
  559. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  560. when the mapping cannot be resolved with confidence -- in which case the
  561. caller omits the field entirely and the firmware falls back to its own
  562. nozzle pick, exactly as it did before this translation existed. Omitting
  563. is deliberately the failure mode: a *wrong* physical ID makes the printer
  564. level with one nozzle and print with another several millimetres off the
  565. bed, which is far worse than letting the firmware choose.
  566. Returns None specifically when:
  567. - a slot needs the rack but the printer has not reported a live rack
  568. position (mid-swap, or a stale connection);
  569. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  570. for a plate sliced for the fixed hotend only (#2800 capture), so this
  571. matches it rather than naming a nozzle it does not have to name;
  572. - a slot names a carriage that is neither of the two an H2C has, which
  573. means the file was mapped for a machine this translation does not model;
  574. - the plate needs more slots than the wire format carries;
  575. - the input is not a list of whole numbers.
  576. Total by construction: it raises nothing, because the only caller is
  577. building an MQTT print command with no exception handler above it and the
  578. queue item has already been committed as `printing` by then. An
  579. unparseable input has to degrade to "let the firmware pick", not to a job
  580. wedged in a state no print will ever leave.
  581. """
  582. if not isinstance(slot_extruders, list) or not slot_extruders:
  583. return None
  584. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  585. return None
  586. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  587. return None
  588. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  589. return None
  590. # Normalise first so the checks below, and the values that reach the wire,
  591. # are known ints. bool is an int subclass and would otherwise serialise as
  592. # a JSON `true`; None means "slot not printed" and is folded into -1.
  593. normalised: list[int] = []
  594. for extruder in slot_extruders:
  595. if extruder is None:
  596. normalised.append(-1)
  597. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  598. normalised.append(extruder)
  599. else:
  600. return None
  601. if _RACK_EXTRUDER_ID not in normalised:
  602. return None
  603. wire = [-1] * _RACK_WIRE_SLOTS
  604. for index, extruder in enumerate(normalised):
  605. if extruder < 0:
  606. continue
  607. if extruder == _RACK_EXTRUDER_ID:
  608. wire[index] = rack_nozzle_id
  609. elif extruder == _FIXED_EXTRUDER_ID:
  610. wire[index] = _FIXED_NOZZLE_ID
  611. else:
  612. # An H2C has these two carriages and no others. A third index is a
  613. # file mapped for something else, and forwarding it raw would name
  614. # a physical nozzle by an index that does not identify one.
  615. return None
  616. return wire
  617. # A rack position as the operator counts it (and as the printer card and
  618. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  619. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  620. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  621. _RACK_POSITION_BASE = 15
  622. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  623. def rack_position_to_nozzle_id(position: int) -> int | None:
  624. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  625. if not isinstance(position, int) or isinstance(position, bool):
  626. return None
  627. if position not in RACK_POSITIONS:
  628. return None
  629. return _RACK_POSITION_BASE + position
  630. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  631. """Whether a live rack slot can print a group wanting this nozzle.
  632. Mirrors the filter BambuStudio applies in its own picker: the position has
  633. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  634. and flow type. A mismatch here is not cosmetic -- it is the printer being
  635. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  636. """
  637. if not isinstance(slot, dict):
  638. return False
  639. slot_diameter = str(slot.get("diameter") or "").strip()
  640. slot_type = str(slot.get("type") or "").strip()
  641. if not slot_diameter and not slot_type:
  642. return False # empty position
  643. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  644. # the printer does not.
  645. try:
  646. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  647. return False
  648. except (TypeError, ValueError):
  649. return False
  650. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  651. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  652. # printer that omits the code is not thereby ruled ineligible.
  653. wanted = volume_type.strip().lower()
  654. if wanted and slot_type:
  655. is_high_flow = slot_type.upper().startswith("HH")
  656. if wanted.startswith("high flow") != is_high_flow:
  657. return False
  658. return True
  659. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  660. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  661. _RACK_CARRIAGE_NOZZLE_ID = 0
  662. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  663. """Live rack contents keyed by 1-based position, mounted nozzle included.
  664. The firmware omits a rack id entirely while that nozzle is picked up onto
  665. the carriage (#943) -- it does not send an empty placeholder. Taking the
  666. omission at face value would rule the nozzle ineligible for the very print
  667. that wants it, and it is the single most likely position to be picked,
  668. because it is the one the last print left mounted.
  669. The absent id is recoverable only when exactly one is missing: rack ids are
  670. fixed at 16..21, so a single gap alongside a loaded carriage is that
  671. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  672. with four nozzles in six positions looks the same -- so those stay absent
  673. and the caller treats them as empty.
  674. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  675. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  676. """
  677. by_position: dict[int, dict] = {}
  678. carriage: dict | None = None
  679. for slot in rack_slots or []:
  680. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  681. continue
  682. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  683. carriage = slot
  684. continue
  685. position = slot["id"] - _RACK_POSITION_BASE
  686. if position in RACK_POSITIONS:
  687. by_position[position] = slot
  688. missing = [position for position in RACK_POSITIONS if position not in by_position]
  689. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  690. by_position[missing[0]] = carriage
  691. return by_position
  692. def resolve_rack_plan_mapping(
  693. slot_groups: list[int],
  694. groups: dict[int, dict],
  695. choice: dict[int, int],
  696. rack_slots: list[dict],
  697. ) -> tuple[list[int] | None, str | None]:
  698. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  699. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  700. That one can only name the single live rack position, so a plate wanting a
  701. different hotend per group is unresolvable to it. Here each group carries
  702. its own position, which is the operator's choice (#1784) -- the 3MF states
  703. it nowhere, proven by dispatching one plate twice with different picks and
  704. diffing the two files down to float noise.
  705. ``choice`` may be partial or empty; groups it does not name are assigned
  706. from the live rack, preferring a position already loaded with the group's
  707. own filament colour and otherwise taking the lowest eligible one.
  708. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  709. is a sentence naming what could not be satisfied. The caller decides what
  710. to do with a failure, and the two cases differ: a stale *explicit* pick
  711. should stop the print, while a failed auto-assignment should degrade to
  712. letting the firmware choose, exactly as before this existed.
  713. """
  714. if not isinstance(slot_groups, list) or not slot_groups:
  715. return None, "the plate lists no filament slots"
  716. if len(slot_groups) > _RACK_WIRE_SLOTS:
  717. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  718. by_position = _rack_by_position(rack_slots)
  719. # Assign every rack-bound group a position before building the wire, so a
  720. # group can never be handed one an earlier group already took. Explicit
  721. # picks are placed first: an auto-assignment must yield to them rather than
  722. # claim a position the operator asked for.
  723. assigned: dict[int, int] = {}
  724. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  725. for group_id in rack_group_ids:
  726. position = choice.get(group_id)
  727. if position is None:
  728. continue
  729. group = groups[group_id]
  730. if rack_position_to_nozzle_id(position) is None:
  731. return None, f"rack position {position} does not exist"
  732. if position in assigned.values():
  733. return None, f"rack position {position} is picked for more than one filament group"
  734. slot = by_position.get(position)
  735. if slot is None:
  736. return None, f"the printer reports nothing at rack position {position}"
  737. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  738. return None, (
  739. f"rack position {position} holds a "
  740. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  741. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  742. )
  743. assigned[group_id] = position
  744. for group_id in rack_group_ids:
  745. if group_id in assigned:
  746. continue
  747. group = groups[group_id]
  748. eligible = [
  749. position
  750. for position in RACK_POSITIONS
  751. if position not in assigned.values()
  752. and position in by_position
  753. and _rack_slot_is_eligible(
  754. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  755. )
  756. ]
  757. if not eligible:
  758. return None, (
  759. f"no free rack position holds a {group.get('nozzle_diameter')} "
  760. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  761. )
  762. # Prefer a position already carrying this group's colour: picking it
  763. # means the operator does not have to move filament to make the print
  764. # match what they asked for.
  765. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  766. assigned[group_id] = next(
  767. (
  768. position
  769. for position in eligible
  770. if wanted_colour
  771. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  772. == wanted_colour
  773. ),
  774. eligible[0],
  775. )
  776. wire = [-1] * _RACK_WIRE_SLOTS
  777. for index, group_id in enumerate(slot_groups):
  778. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  779. continue # slot this plate does not print
  780. group = groups.get(group_id)
  781. if group is None:
  782. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  783. if not group.get("on_rack"):
  784. wire[index] = _FIXED_NOZZLE_ID
  785. continue
  786. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  787. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  788. return None, f"filament group {group_id} resolved to no rack position"
  789. wire[index] = nozzle_id
  790. if all(value == -1 for value in wire):
  791. return None, "the plate assigns no filament to a nozzle"
  792. return wire, None
  793. @dataclass(frozen=True)
  794. class DryingCycleEnd:
  795. """What Bambuddy saw of one AMS drying cycle, reported when it ends (#2863).
  796. ``peak_minutes`` is the highest ``dry_time`` observed during the cycle and
  797. ``remaining_minutes`` the last one before the drop to 0. ``start_seen`` says
  798. whether the countdown was watched from its first minute; when it was not
  799. (Bambuddy started mid-cycle) the peak is only a lower bound on the length.
  800. ``target_temp`` / ``target_hours`` are known only for cycles Bambuddy itself
  801. started, because the printer never echoes them.
  802. """
  803. ams_id: int
  804. remaining_minutes: int
  805. peak_minutes: int
  806. start_seen: bool
  807. target_temp: int | None = None
  808. target_hours: int | None = None
  809. @dataclass
  810. class MQTTLogEntry:
  811. """Log entry for MQTT message debugging."""
  812. timestamp: str
  813. topic: str
  814. direction: str # "in" or "out"
  815. payload: dict
  816. @dataclass
  817. class HMSError:
  818. """Health Management System error from printer."""
  819. code: str
  820. attr: int # Attribute value for constructing wiki URL
  821. module: int
  822. # Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  823. # 3 notification, 0 invalid. From `code >> 16` for `hms[]` faults, and from
  824. # the error's first hex digit for `print_error` (#2728).
  825. severity: int
  826. # The bundled catalogue's sentence for this fault, resolved once here so
  827. # every surface that reports it — the status response, the WebSocket
  828. # broadcast, the completion payload, notifications — says the same thing.
  829. # None when Bambu publishes no text for the code; see `describe_fault`.
  830. # Replaces a `message` field that was never set or read anywhere.
  831. description: str | None = None
  832. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  833. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  834. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  835. # HMSError without explicitly passing actions can't silently land None on the schema
  836. # boundary and raise ValidationError at routes/printers.py response time.
  837. actions: list[str] = field(default_factory=list)
  838. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  839. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  840. job_id: str | None = None
  841. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  842. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  843. # 32-bit `print_error` path. The frontend echoes this back to
  844. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  845. # used to send caused the firmware to silently reject HMS commands on H2C
  846. # (#1830) and on `hms[]`-sourced faults generally.
  847. full_code: str = ""
  848. def completion_payload(self) -> dict:
  849. """This error as a print-complete payload carries it, for the failure reason."""
  850. return {
  851. "code": self.code,
  852. "attr": self.attr,
  853. "module": self.module,
  854. "severity": self.severity,
  855. # Lets the queue's failure reason label an `hms[]` fault
  856. # with its full code rather than a lossy short one (#2728).
  857. "full_code": self.full_code,
  858. # Carried so the queue's failure reason quotes the same
  859. # sentence the status response and the broadcast do,
  860. # rather than resolving the code a fourth time (#2926).
  861. "description": self.description,
  862. }
  863. def _is_print_error_entry(error: HMSError) -> bool:
  864. """Whether this entry came from the 32-bit `print_error` field, whose
  865. full code has 8 hex digits; an `hms[]` entry's has 16."""
  866. return len(error.full_code) == 8
  867. def _hms_short_code(error: HMSError) -> str:
  868. """The MMMM_EEEE short code of an entry from either source."""
  869. module = (error.attr >> 16) & 0xFFFF
  870. # The low half only: an hms[] code carries its alert level above it
  871. # (0x18061 for 0500_8061), and read whole it never matched, listing the
  872. # fault twice (M-U9).
  873. number = (int(error.code.replace("0x", ""), 16) & 0xFFFF) if error.code else 0
  874. return f"{module:04X}_{number:04X}"
  875. def _hms_short_codes(errors: list) -> set[str]:
  876. return {_hms_short_code(e) for e in errors}
  877. # HMS short codes the firmware emits during normal user-cancel sequences.
  878. # These aren't faults — they're status echoes that confirm the cancel happened.
  879. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  880. # so they don't drive the printer card's "X problem" badge, the red pip, or
  881. # any other consumer that treats hms_errors as the active-fault list.
  882. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  883. {
  884. "0300_400C", # "The task was canceled."
  885. "0500_400E", # "Printing was cancelled."
  886. }
  887. )
  888. # "MQTT command verification failed" — the printer's authorization/authentication
  889. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  890. # command it could not verify. Queries (get_version, extrusion_cali_get,
  891. # pushall) still answer, so the connection looks perfectly healthy while
  892. # project_file, gcode_line and ams_change_filament are all silently dropped —
  893. # which is exactly how it presents: uploads succeed, the printer echoes our
  894. # subtask_id, then sits at IDLE forever (#2732).
  895. #
  896. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  897. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  898. # "0500_0007", which matches nothing in any catalog.
  899. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  900. # Command responses whose content the debug log leaves out (#3531). push_status
  901. # is the printer's status, arriving every second and logged field by field;
  902. # project_file carries the download URL of a print, which may be a signed one.
  903. _COMMANDS_LOGGED_BY_NAME_ONLY: frozenset[str] = frozenset({"push_status", "project_file"})
  904. @dataclass
  905. class KProfile:
  906. """Pressure advance (K) calibration profile from printer."""
  907. slot_id: int
  908. extruder_id: int
  909. nozzle_id: str
  910. nozzle_diameter: str
  911. filament_id: str
  912. name: str
  913. k_value: str
  914. n_coef: str = "0.000000"
  915. ams_id: int = 0
  916. tray_id: int = -1
  917. setting_id: str | None = None
  918. @dataclass
  919. class NozzleInfo:
  920. """Nozzle hardware configuration."""
  921. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  922. nozzle_diameter: str = "" # e.g., "0.4"
  923. def nozzle_print_time_s(value: object) -> int | None:
  924. """A nozzle's accumulated print time from its ``nozzle_info`` entry (#1908).
  925. H2C firmware reports it per nozzle as ``p_t``, in seconds. Older firmware
  926. and other models leave it out, which stays None so the UI hides the row
  927. instead of showing "0h". A bool is an int to Python but never a duration.
  928. """
  929. if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
  930. return None
  931. return int(value)
  932. # What await_cali_ack reports when the printer did not answer a K-profile write
  933. # in time. Not a refusal: firmware that predates the ack never answers.
  934. CALI_ACK_UNCONFIRMED = "no acknowledgement from printer"
  935. class KProfileReadError(Exception):
  936. """The printer's K-profile table could not be read: not connected, or no
  937. answer to any attempt. Not an empty table, which is a printer without
  938. profiles for that nozzle (#3404)."""
  939. # Time the printer has to list a skipped object in s_obj before the skip is
  940. # logged as not confirmed.
  941. SKIP_CONFIRM_TIMEOUT_S = 60.0
  942. # Answers to K-profile commands: they echo the command's own fields (the nozzle
  943. # diameter among them), never the printer's status.
  944. _KPROFILE_COMMAND_ANSWERS = frozenset(
  945. {"extrusion_cali_get", "extrusion_cali_set", "extrusion_cali_del", "extrusion_cali_sel"}
  946. )
  947. @dataclass
  948. class FilaSwitchState:
  949. """Filament Track Switch (FTS) accessory state.
  950. The FTS is an external accessory that mediates filament routing between an
  951. AMS and the printer's extruders. When installed, the AMS no longer has a
  952. fixed extruder assignment — any slot can be routed to any extruder via the
  953. track switch. Detected from print.device.fila_switch in MQTT.
  954. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  955. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  956. stable, operator-visible relationship — it is set on the printer's "Manual
  957. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  958. Field semantics below are taken from BambuStudio's own parser
  959. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  960. """
  961. installed: bool = False
  962. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  963. # the arrays are ordered B-then-A, which is the opposite of how they read.
  964. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  965. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  966. in_slots: list[int] = field(default_factory=list)
  967. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  968. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  969. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  970. # inlet is currently paired with which outlet is not reported at all.
  971. out_extruders: list[int] = field(default_factory=list)
  972. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  973. info: int = 0 # bit 0 = inlet has filament
  974. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  975. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  976. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  977. one of A/B.
  978. """
  979. index = {"A": 1, "B": 0}.get(inlet.upper())
  980. if index is None or index >= len(self.in_slots):
  981. return None
  982. raw = self.in_slots[index]
  983. if raw < 0:
  984. return None
  985. return (raw >> 8) & 0xFF, raw & 0xFF
  986. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  987. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  988. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  989. # as empty everywhere is strictly safer than reading it as the external spool.
  990. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  991. @dataclass
  992. class ExtruderSlot:
  993. """Which AMS slot an extruder is currently fed from.
  994. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  995. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  996. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  997. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  998. ``state.tray_now`` cannot answer this: it is a single value for the whole
  999. printer, so on a dual-nozzle machine with both hotends loaded it names only
  1000. one of them. Unloading a specific slot needs to know which extruder is
  1001. holding it, which is what this is for.
  1002. """
  1003. ams_id: int | None = None
  1004. slot_id: int | None = None
  1005. has_filament: bool = False
  1006. def holds(self, ams_id: int, slot_id: int) -> bool:
  1007. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  1008. return self.ams_id == ams_id and self.slot_id == slot_id
  1009. @dataclass
  1010. class PrintOptions:
  1011. """AI detection and print options from xcam data."""
  1012. # Core AI detectors
  1013. spaghetti_detector: bool = False
  1014. print_halt: bool = False
  1015. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  1016. first_layer_inspector: bool = False
  1017. printing_monitor: bool = False # AI print quality monitoring
  1018. buildplate_marker_detector: bool = False
  1019. allow_skip_parts: bool = False
  1020. # Additional AI detectors - decoded from cfg bitmask
  1021. nozzle_clumping_detector: bool = True
  1022. nozzle_clumping_sensitivity: str = "medium"
  1023. pileup_detector: bool = True
  1024. pileup_sensitivity: str = "medium"
  1025. airprint_detector: bool = True
  1026. airprint_sensitivity: str = "medium"
  1027. auto_recovery_step_loss: bool = True # Uses print.print_option command
  1028. filament_tangle_detect: bool = False
  1029. @dataclass
  1030. class PrinterState:
  1031. connected: bool = False
  1032. state: str = "unknown"
  1033. current_print: str | None = None
  1034. subtask_name: str | None = None
  1035. progress: float = 0.0
  1036. remaining_time: int = 0
  1037. layer_num: int = 0
  1038. total_layers: int = 0
  1039. temperatures: dict = field(default_factory=dict)
  1040. raw_data: dict = field(default_factory=dict)
  1041. gcode_file: str | None = None
  1042. subtask_id: str | None = None
  1043. hms_errors: list = field(default_factory=list) # List of HMSError
  1044. kprofiles: list = field(default_factory=list) # List of KProfile
  1045. sdcard: bool = False # SD card inserted
  1046. # Whether the printer has ever actually told us about `sdcard`. Without this
  1047. # the default False is indistinguishable from a real "no card", and any
  1048. # consumer that treats False as evidence would act on silence — which is how
  1049. # a storage gate turns into a regression for every printer whose firmware
  1050. # simply doesn't publish the field (#2780).
  1051. sdcard_reported: bool = False
  1052. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  1053. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  1054. # whoever sent it (the slicer or us). Bambu states where the sliced file
  1055. # went: `ftp://<name>` is external storage, which FTPS serves, while
  1056. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  1057. #
  1058. # Two fields, because the two readers need different guarantees.
  1059. # ``current_project_url`` belongs to the print now running and is cleared
  1060. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  1061. # "unknown" rather than inheriting the previous job's answer. That matters:
  1062. # 18% of the print starts in #2780's bundle had no dispatch on the request
  1063. # topic at all (touchscreen reprints, restart recovery), and a stale
  1064. # internal-storage URL would make those skip an FTPS sweep that could have
  1065. # found the file — losing an archive that works today.
  1066. #
  1067. # ``last_project_url`` is sticky and exists for reporting only: the
  1068. # connection diagnostic is usually run *after* the print that prompted it,
  1069. # by which point the per-print value is rightly gone.
  1070. #
  1071. # None means we never saw a dispatch — say nothing, don't guess.
  1072. current_project_url: str | None = None
  1073. last_project_url: str | None = None
  1074. timelapse: bool = False # Timelapse recording active
  1075. ipcam: bool = False # Live view / camera streaming enabled
  1076. wifi_signal: int | None = None # WiFi signal strength in dBm
  1077. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  1078. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  1079. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  1080. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  1081. # right. (The legacy parser below writes left -> [0], but it only ever runs
  1082. # for single-nozzle printers -- every dual-nozzle model reports
  1083. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  1084. # than indexing it directly.
  1085. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  1086. # AI detection and print options
  1087. print_options: PrintOptions = field(default_factory=PrintOptions)
  1088. # Calibration stage tracking (from stg_cur and stg fields)
  1089. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  1090. stg: list = field(default_factory=list) # List of stages to execute
  1091. # Air conditioning mode (0=cooling, 1=heating)
  1092. airduct_mode: int = 0
  1093. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1094. speed_level: int = 2
  1095. # Chamber light on/off
  1096. chamber_light: bool = False
  1097. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  1098. active_extruder: int = 0
  1099. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  1100. tray_now: int = 255
  1101. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  1102. # tray_tar = the slot the paused/loading print now expects
  1103. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  1104. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  1105. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  1106. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  1107. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  1108. tray_tar: int = 255
  1109. tray_pre: int = 255
  1110. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  1111. last_loaded_tray: int = -1
  1112. # Pending load target - used to track what tray we're loading for H2D disambiguation
  1113. pending_tray_target: int | None = None
  1114. # When it was set (time.monotonic): see PENDING_TRAY_TARGET_TTL.
  1115. pending_tray_target_at: float | None = None
  1116. # AMS status for filament change tracking (from print.ams.ams_status field)
  1117. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1118. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  1119. ams_status: int = 0
  1120. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  1121. ams_status_sub: int = 0 # ams_status & 0xFF
  1122. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  1123. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  1124. mc_print_sub_stage: int = 0
  1125. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  1126. ams_mapping: list = field(default_factory=list)
  1127. # The running print's AMS mapping (global tray per filament, -1 = none),
  1128. # as captured from its print command. None when no print has one.
  1129. print_ams_mapping: list | None = None
  1130. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  1131. ams_extruder_map: dict = field(default_factory=dict)
  1132. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  1133. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  1134. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  1135. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  1136. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  1137. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  1138. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  1139. ams_switch_inlet: dict = field(default_factory=dict)
  1140. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  1141. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  1142. # series). Empty elsewhere, which every reader has to tolerate — see
  1143. # ExtruderSlot for why tray_now cannot stand in for it.
  1144. extruder_slots: dict = field(default_factory=dict)
  1145. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  1146. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  1147. # regex used to derive the plate number from the path always falls back to
  1148. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  1149. # Bambuddy dispatches the print itself we know the plate authoritatively;
  1150. # we record it here and prefer it over the gcode_file regex. The subtask
  1151. # field guards against staleness: if the printer is currently running a
  1152. # different subtask (e.g. a Studio-direct dispatch), these values are
  1153. # ignored. Cleared on disconnect.
  1154. dispatched_plate_id: int | None = None
  1155. dispatched_subtask: str | None = None
  1156. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  1157. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  1158. h2d_extruder_snow: dict = field(default_factory=dict)
  1159. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  1160. nozzle_rack: list = field(default_factory=list)
  1161. # H2C rack position currently mounted / being moved to, from
  1162. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  1163. # the six rack slots), not extruder indices, and they are what the
  1164. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  1165. # can tell us which hotend is in the carriage right now, so this is read
  1166. # live rather than derived from the queued job.
  1167. nozzle_rack_src_id: int | None = None
  1168. nozzle_rack_tar_id: int | None = None
  1169. # Timestamp of last AMS data update (for RFID refresh detection)
  1170. last_ams_update: float = 0.0
  1171. # Printable objects for skip object functionality: {identify_id: object_name}
  1172. printable_objects: dict = field(default_factory=dict)
  1173. # Objects that have been skipped during the current print
  1174. skipped_objects: list = field(default_factory=list)
  1175. # Pauses the slicer put into the running print, from its archived 3MF
  1176. # (#2984): threemf_tools.PausePoint, in print order. Empty when unknown.
  1177. pause_points: list = field(default_factory=list)
  1178. # Layers of those pauses a heads-up notification already went out for.
  1179. pause_warned_layers: set = field(default_factory=set)
  1180. # Fan speeds (0-100 percentage, None if not available for this model)
  1181. cooling_fan_speed: int | None = None # Part cooling fan
  1182. big_fan1_speed: int | None = None # Auxiliary fan
  1183. big_fan2_speed: int | None = None # Chamber/exhaust fan
  1184. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  1185. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  1186. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  1187. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  1188. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  1189. left_aux_fan_speed: int | None = None
  1190. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  1191. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  1192. # omits it, which is the case this flag exists to detect.
  1193. #
  1194. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  1195. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  1196. # harmless because only the P2S/X2D badge consults it — those models keep
  1197. # their unconditional "Chamber Fan" badge — but do not read this as
  1198. # "an exhaust kit is fitted" without also checking the model.
  1199. exhaust_fan_present: bool = False
  1200. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  1201. # Used by usage tracker to split filament weight on mid-print tray switch
  1202. tray_change_log: list = field(default_factory=list)
  1203. # Spools assigned to a tray during the current print, and the spool each
  1204. # assigned tray held at its start (services.spool_swaps, #3325).
  1205. spool_change_log: list = field(default_factory=list)
  1206. # Firmware version info (from info.module[name="ota"].sw_ver)
  1207. firmware_version: str | None = None
  1208. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  1209. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  1210. developer_mode: bool | None = None
  1211. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  1212. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  1213. # which uses the old protocol path; field not yet found). Consumers must treat
  1214. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  1215. ams_filament_backup: bool | None = None
  1216. # Stage name mapping from BambuStudio DeviceManager.cpp
  1217. STAGE_NAMES = {
  1218. 0: "Printing",
  1219. 1: "Auto bed leveling",
  1220. 2: "Heatbed preheating",
  1221. 3: "Vibration compensation",
  1222. 4: "Changing filament",
  1223. 5: "M400 pause",
  1224. 6: "Paused (filament ran out)",
  1225. 7: "Heating nozzle",
  1226. 8: "Calibrating dynamic flow",
  1227. 9: "Scanning bed surface",
  1228. 10: "Inspecting first layer",
  1229. 11: "Identifying build plate type",
  1230. 12: "Calibrating Micro Lidar",
  1231. 13: "Homing toolhead",
  1232. 14: "Cleaning nozzle tip",
  1233. 15: "Checking extruder temperature",
  1234. 16: "Paused by the user",
  1235. 17: "Pause (front cover fall off)",
  1236. 18: "Calibrating the micro lidar",
  1237. 19: "Calibrating flow ratio",
  1238. 20: "Pause (nozzle temperature malfunction)",
  1239. 21: "Pause (heatbed temperature malfunction)",
  1240. 22: "Filament unloading",
  1241. 23: "Pause (step loss)",
  1242. 24: "Filament loading",
  1243. 25: "Motor noise cancellation",
  1244. 26: "Pause (AMS offline)",
  1245. 27: "Pause (low speed of the heatbreak fan)",
  1246. 28: "Pause (chamber temperature control problem)",
  1247. 29: "Cooling chamber",
  1248. 30: "Pause (Gcode inserted by user)",
  1249. 31: "Motor noise showoff",
  1250. 32: "Pause (nozzle clumping)",
  1251. 33: "Pause (cutter error)",
  1252. 34: "Pause (first layer error)",
  1253. 35: "Pause (nozzle clog)",
  1254. 36: "Measuring motion precision",
  1255. 37: "Enhancing motion precision",
  1256. 38: "Measure motion accuracy",
  1257. 39: "Nozzle offset calibration",
  1258. 40: "High temperature auto bed leveling",
  1259. 41: "Auto Check: Quick Release Lever",
  1260. 42: "Auto Check: Door and Upper Cover",
  1261. 43: "Laser Calibration",
  1262. 44: "Auto Check: Platform",
  1263. 45: "Confirming BirdsEye Camera location",
  1264. 46: "Calibrating BirdsEye Camera",
  1265. 47: "Auto bed leveling - phase 1",
  1266. 48: "Auto bed leveling - phase 2",
  1267. 49: "Heating chamber",
  1268. 50: "Cooling heatbed",
  1269. 51: "Printing calibration lines",
  1270. 52: "Auto Check: Material",
  1271. 53: "Live View Camera Calibration",
  1272. 54: "Waiting for heatbed temperature",
  1273. 55: "Auto Check: Material Position",
  1274. 56: "Cutting Module Offset Calibration",
  1275. 57: "Measuring Surface",
  1276. 58: "Thermal Preconditioning",
  1277. 59: "Homing Blade Holder",
  1278. 60: "Calibrating Camera Offset",
  1279. 61: "Calibrating Blade Holder Position",
  1280. 62: "Hotend Pick and Place Test",
  1281. 63: "Waiting for Chamber temperature",
  1282. 64: "Preparing Hotend",
  1283. 65: "Calibrating nozzle clumping detection",
  1284. 66: "Purifying the chamber air",
  1285. 74: "Preparing", # Seen on H2D during print preparation
  1286. 77: "Preparing AMS",
  1287. }
  1288. def get_stage_name(stage: int) -> str:
  1289. """Get human-readable stage name from stage number."""
  1290. try:
  1291. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1292. except TypeError:
  1293. # `stage` is an int by convention only -- it comes straight out of the
  1294. # printer's JSON, and an unhashable value there would otherwise raise
  1295. # from inside the f-string that builds the stage-change log line, which
  1296. # is evaluated on every transition whatever the log level is set to.
  1297. # Labelling a value must not be able to abort the state update.
  1298. return f"Unknown stage ({stage})"
  1299. # #2547 end-of-print telemetry probe.
  1300. #
  1301. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1302. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1303. # but fires on no model in the field: across 247 support bundles there is not a
  1304. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1305. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1306. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1307. #
  1308. # We can't design a replacement from bundles we already have, because out of
  1309. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1310. # every other stage/action field is dropped unread. The obvious candidates
  1311. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1312. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1313. # own. Dumping the raw values for the window between the last object layer and
  1314. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1315. # anything — marks that moment.
  1316. #
  1317. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1318. # Nothing identifying, and nothing that could carry an access code.
  1319. _END_OF_PRINT_PROBE_FIELDS = (
  1320. "gcode_state",
  1321. "state",
  1322. "print_error",
  1323. "stg_cur",
  1324. "stg",
  1325. "stg_cd",
  1326. "mc_print_stage",
  1327. "mc_print_sub_stage",
  1328. "mc_action",
  1329. "mc_stage",
  1330. "print_real_action",
  1331. "print_gcode_action",
  1332. "spd_lvl",
  1333. "mc_percent",
  1334. "mc_remaining_time",
  1335. "layer_num",
  1336. "total_layer_num",
  1337. "home_flag",
  1338. "prepare_per",
  1339. )
  1340. # Frame budget for one print's probe. A long final layer can hold the window
  1341. # open for minutes at ~1 frame/second; this stops a single print from filling
  1342. # the log the user then has to upload.
  1343. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1344. # States that close the window. FINISH is the interesting one — the probe's
  1345. # whole job is to show what happened in the run-up to it.
  1346. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1347. class BambuMQTTClient:
  1348. """MQTT client for Bambu Lab printer communication."""
  1349. MQTT_PORT = 8883
  1350. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1351. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1352. _request_topic_cache: dict[str, bool] = {}
  1353. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1354. # the request topic. A SUBACK failure is the broker answering the question;
  1355. # a disconnect is only circumstantial, and any drop inside the window looks
  1356. # identical -- a network blip, the printer rebooting, the container being
  1357. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1358. # the rest of the process on a printer that supports it perfectly well
  1359. # (#2953). Require the drop to repeat before believing it; a printer that
  1360. # really does refuse the topic answers the same way every time and pays one
  1361. # extra reconnect for it.
  1362. _request_topic_probe_failures: dict[str, int] = {}
  1363. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1364. # Counter for generating unique MQTT client IDs across instances.
  1365. _client_instance_counter: int = 0
  1366. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1367. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1368. # every few seconds (and register_assignment_verification nudges a fresh
  1369. # pushall), so this only has to survive a couple of idle push intervals.
  1370. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1371. def __init__(
  1372. self,
  1373. ip_address: str,
  1374. serial_number: str,
  1375. access_code: str,
  1376. model: str | None = None,
  1377. on_state_change: Callable[[PrinterState], None] | None = None,
  1378. on_print_start: Callable[[dict], None] | None = None,
  1379. on_print_complete: Callable[[dict], None] | None = None,
  1380. on_ams_change: Callable[[list], None] | None = None,
  1381. on_layer_change: Callable[[int], None] | None = None,
  1382. on_print_progress: Callable[[int], None] | None = None,
  1383. on_bed_temp_update: Callable[[float], None] | None = None,
  1384. on_drying_complete: Callable[[int], None] | None = None,
  1385. on_drying_cycle_end: Callable[[DryingCycleEnd], None] | None = None,
  1386. on_print_running_observed: Callable[[dict], None] | None = None,
  1387. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1388. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1389. on_tray_change: Callable[[int, int], None] | None = None,
  1390. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1391. ):
  1392. self.ip_address = ip_address
  1393. self.serial_number = serial_number
  1394. self.access_code = access_code
  1395. self.model = model
  1396. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1397. self._debug_last: dict[str, object] = {}
  1398. self.on_state_change = on_state_change
  1399. self.on_print_start = on_print_start
  1400. self.on_print_complete = on_print_complete
  1401. self.on_ams_change = on_ams_change
  1402. # Fired when an AMS is moved to the switch's other inlet, which changes
  1403. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1404. self.on_fts_inlet_change = on_fts_inlet_change
  1405. self.on_layer_change = on_layer_change
  1406. # #2547: fired when `mc_percent` advances during a running print.
  1407. # `on_layer_change` stops firing the instant the final layer starts, so
  1408. # it is blind to the last few percent of a print — which is exactly the
  1409. # window the finish-photo frame bank needs to keep refreshing through.
  1410. # Progress is the one field that keeps ticking there and then freezes
  1411. # before the end G-code runs, so banking on it stays inside the print.
  1412. self.on_print_progress = on_print_progress
  1413. self.on_bed_temp_update = on_bed_temp_update
  1414. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1415. # the drying cycle just finished (auto- or manually-triggered).
  1416. # Receives the AMS id of the unit that finished drying.
  1417. self.on_drying_complete = on_drying_complete
  1418. # #2863: fired on the same edge with what was seen of the cycle, so the
  1419. # spools in that AMS can be stamped as dried.
  1420. self.on_drying_cycle_end = on_drying_cycle_end
  1421. # #1485 follow-up: fired the first time we see RUNNING state in a
  1422. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1423. # print, the #1304 first-push guard skipped the start event). Lets
  1424. # main.py capture a fresh timelapse baseline at restart-recovery
  1425. # time so the completion-time snapshot-diff still works. Receives
  1426. # the same shape as on_print_start (filename / subtask_name /
  1427. # remaining_time / raw_data / ams_mapping).
  1428. self.on_print_running_observed = on_print_running_observed
  1429. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1430. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1431. # with the process, and a long print outliving a restart would
  1432. # otherwise lose the segment boundaries the usage tracker splits on.
  1433. # Receives (global_tray_id, layer_num).
  1434. self.on_tray_change = on_tray_change
  1435. # #1721: fired the moment the printer enters the end-of-print
  1436. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1437. # we've hit the last layer / remaining_time<=0). This is the
  1438. # framing #1397 was after — toolhead parked, bed not yet
  1439. # dropped — but reached via a clean state signal instead of
  1440. # the per-layer M622 J1 macros which caused per-layer nozzle
  1441. # parks on slicer profiles with Timelapse Type = Smooth.
  1442. # A FINISH-state fallback below fires this same callback if
  1443. # stage 22 never arrives (cancel mid-print, external-spool-
  1444. # only prints, HMS halt before unload, firmware variants).
  1445. self.on_finish_photo_moment = on_finish_photo_moment
  1446. # #2582: fired after a spool assignment (ams_filament_setting +
  1447. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1448. # push landed or a timeout elapses without it. Receives
  1449. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1450. # tell the user "loaded" vs "assignment didn't take" instead of the
  1451. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1452. # feel random. See _check_assignment_verifications.
  1453. self.on_assignment_verified = on_assignment_verified
  1454. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1455. # value is the desired end-state we just pushed plus a monotonic
  1456. # deadline. Populated by register_assignment_verification, drained by
  1457. # _check_assignment_verifications on every AMS push.
  1458. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1459. # Per-AMS previous dry_time, used to detect the falling edge above.
  1460. # Seeded lazily as we observe each AMS unit.
  1461. self._previous_dry_times: dict[int, int] = {}
  1462. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1463. # A live cycle's countdown ticks once a minute; a command the firmware
  1464. # accepted but never actually started (observed on an H2D mid-print
  1465. # with two AMS-HT cycles already running: the third unit's timer sat
  1466. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1467. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1468. # reported as dry_countdown_stalled so the UI can stop claiming an
  1469. # active cycle that is not running.
  1470. self._dry_time_changed_at: dict[int, float] = {}
  1471. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1472. # last start. Bambu does not echo these back in the per-tick AMS push
  1473. # — only the dry_time countdown — so we cache what we sent to drive
  1474. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1475. self._drying_targets: dict[int, dict[str, object]] = {}
  1476. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1477. # ends a cycle far short of its duration, which on the telemetry alone
  1478. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1479. # log would otherwise blame the printer for our own decision (#2770).
  1480. self._drying_stops_sent: set[int] = set()
  1481. # Per-AMS record of the cycle in progress: the highest dry_time seen,
  1482. # whether its first minute was observed, and the target we sent for it.
  1483. # The target is copied here when the countdown starts because a stop
  1484. # drops _drying_targets before the cycle ends (#2863).
  1485. self._dry_cycles: dict[int, dict[str, object]] = {}
  1486. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1487. # for, so each is reported once rather than on every transition into it.
  1488. self._unnamed_stages_seen: set[int] = set()
  1489. self.state = PrinterState()
  1490. self._client: mqtt.Client | None = None
  1491. self._loop: asyncio.AbstractEventLoop | None = None
  1492. self._previous_gcode_state: str | None = None
  1493. self._previous_gcode_file: str | None = None
  1494. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1495. # #3485: the first state after startup was PAUSE with a print loaded,
  1496. # e.g. a printer in power-loss recovery when Bambuddy came back. Its
  1497. # PAUSE -> RUNNING is that print resuming, not a new one.
  1498. self._paused_at_startup: bool = False
  1499. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1500. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1501. # #1721: one-shot guard so the end-of-print stage-22 detector
  1502. # and the FINISH-state fallback don't both fire on the same
  1503. # print. Reset to False on every print start.
  1504. self._finish_photo_captured: bool = False
  1505. # #2702: one-shot re-request of the layer total. Armed at print start
  1506. # when the starting frame carried no `total_layer_num`, spent on the
  1507. # first layer advance that still has no denominator. Bambu firmware
  1508. # only re-sends *changed* fields, so a total we never received (or
  1509. # dropped) is only recoverable via a full pushall.
  1510. self._total_layers_refresh_armed: bool = False
  1511. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1512. # window has run for a print so a late FINISH re-send can't reopen it.
  1513. self._eop_probe_armed: bool = True
  1514. self._eop_probe_open: bool = False
  1515. self._eop_probe_frames: int = 0
  1516. self._eop_probe_last: dict = {}
  1517. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1518. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1519. # #3317: the layer the previous print ended on. Right after a print
  1520. # starts, the printer can send one frame that still carries it (H2S:
  1521. # `layer_num` 357 with `mc_percent` 0, then 0 a second later). Taken at
  1522. # face value, the 0 that follows saved 357 as this print's last layer,
  1523. # and a print failing at layer 0 was charged as finished. Frames with
  1524. # this value are ignored until the new print reports another layer.
  1525. self._stale_layer_num: int = 0
  1526. # The subtask_id minted for the most recent start_print() command. The
  1527. # printer echoes it back in status, but often not within the first few
  1528. # seconds — so on_print_start uses this as the id source when the
  1529. # printer hasn't reported it yet, letting queue/scheduled archives
  1530. # persist a restart-stable id from the moment they dispatch (#1485).
  1531. self.last_dispatch_subtask_id: str | None = None
  1532. # The printer's answer to the last print start it refused, as (result,
  1533. # reason); cleared when the next start is sent. The start watchdog
  1534. # reads it to stop waiting for a print that will not come.
  1535. self.last_start_refusal: tuple[str, str | None] | None = None
  1536. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1537. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1538. self._logging_enabled: bool = False
  1539. self._last_message_time: float = 0.0 # Track when we last received a message
  1540. # Bambuddy's own FTP uploads to this printer (#3538): an A1 publishes
  1541. # nothing while it receives a large file, which is not a stale link.
  1542. self._uploads_in_flight: int = 0
  1543. self._last_upload_end: float = 0.0
  1544. # Count of report-topic messages received since the last (re)connect.
  1545. # Lets check_staleness() distinguish "printer never sent a status
  1546. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1547. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1548. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1549. self._report_messages_since_connect: int = 0
  1550. self._zero_report_hint_logged: bool = False
  1551. # Set by mark_power_off() to the gcode_state held just before we
  1552. # optimistically forced the printer to "unknown" (#2629). Restored on
  1553. # the next inbound message, because message traffic proves the power
  1554. # was never actually cut. None whenever no power-off is presumed.
  1555. self._state_before_power_off: str | None = None
  1556. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1557. # printer's pushes verbatim to slicers connected to a virtual printer).
  1558. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1559. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1560. self._disconnection_event: threading.Event | None = None
  1561. self._previous_ams_hash: str | None = None # Track AMS changes
  1562. # Track external-spool (vt_tray) identity changes separately: the AMS
  1563. # hash above covers only AMS units, so an external-spool-only filament
  1564. # swap would never re-trigger inventory reconciliation (#2575).
  1565. self._previous_vt_tray_hash: str | None = None
  1566. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1567. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1568. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1569. # Track which (ams_id, field) warnings have already been emitted this connection
  1570. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1571. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1572. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1573. # keyed by the sequence_id we sent, so two concurrent requests for
  1574. # different nozzle sizes can't steal each other's response (#1748).
  1575. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1576. self._sequence_id: int = 0
  1577. self._pending_kprofile_requests: dict[str, dict] = {}
  1578. # The printer's calibration table, one bucket per nozzle diameter.
  1579. #
  1580. # An extrusion_cali_get response is the complete table for *one* nozzle
  1581. # size, and the printer answers whoever asks — including BambuStudio,
  1582. # whose queries land on the same report topic we subscribe to. Assigning
  1583. # each response straight to state.kprofiles therefore let any single
  1584. # answer stand for the whole printer: a GitHub backup probing
  1585. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1586. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1587. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1588. # card because H2-series trays carry no `k` of their own — the slot's
  1589. # K value is resolved from cali_idx against exactly this list.
  1590. #
  1591. # Keyed by diameter so a response only ever replaces the bucket it
  1592. # actually describes; state.kprofiles is then the union across buckets.
  1593. # An empty answer for a nozzle the printer doesn't have empties that
  1594. # bucket alone.
  1595. self._kprofiles_by_nozzle: dict[str, list] = {}
  1596. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1597. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1598. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1599. # by await_cali_ack.
  1600. self._pending_cali_acks: dict[str, dict | None] = {}
  1601. # Objects sent in skip_objects that the printer's s_obj list has not
  1602. # shown yet: object id -> when it was sent. And the ids of each
  1603. # command by its sequence_id, for its answer.
  1604. self._unconfirmed_skips: dict[int, float] = {}
  1605. self._skip_commands: dict[str, list[int]] = {}
  1606. # Acks for RFID re-reads (ams_get_rfid, and the M620 R gcode_line
  1607. # fallback), keyed the same way. Drained by ams_refresh_tray (#3206).
  1608. self._pending_rfid_acks: dict[str, dict | None] = {}
  1609. # Identifies the one project_file *we* dispatched, so its echo on the
  1610. # topic can be told apart from a slicer's. One-shot: consumed by the
  1611. # first frame that matches. See _project_file_key.
  1612. self._own_project_file_key: str | None = None
  1613. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1614. # Key: module_name, Value: timestamp when command was sent
  1615. self._xcam_hold_start: dict[str, float] = {}
  1616. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1617. # True once the printer has sent `cfg`; from then on AMS Filament Backup
  1618. # is read from cfg only, never from home_flag (#3259).
  1619. self._backup_cfg_seen: bool = False
  1620. # True once a full status report arrived without `cfg`; from then on
  1621. # home_flag bit 10 is read from every status frame (#3259).
  1622. self._backup_home_flag_trusted: bool = False
  1623. # Whether the frame being handled carried the nozzles' snow: only then
  1624. # may snow overrule the slot the same frame reports as tray_now.
  1625. self._snow_in_frame = False
  1626. # The captured ams_mapping lives on the state (print_ams_mapping), so
  1627. # the status the card reads carries it; see _captured_ams_mapping.
  1628. # The destination of the dispatch it was captured from.
  1629. self._captured_mapping_url: str | None = None
  1630. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1631. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1632. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1633. self._has_a2l_am_unit: bool = False
  1634. # Rack AMS units already logged as detected (once per unit).
  1635. self._rack_ams_logged: set[int] = set()
  1636. self._tray_layout_key: tuple | None = None
  1637. self._tray_layout = TrayLayout()
  1638. # Why the last connection attempt was refused by the printer, or None
  1639. # when we have never seen a CONNACK failure since the last success.
  1640. # Without this a rejected access code was completely invisible: paho
  1641. # reports the follow-up disconnect as the generic "Unspecified error"
  1642. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1643. # printer stuck in a reconnect loop looked identical whether it was
  1644. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1645. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1646. # string, kept for the log line only.
  1647. self.last_connect_error: str | None = None
  1648. self.last_connect_error_name: str | None = None
  1649. # Request topic subscription tracking
  1650. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1651. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1652. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1653. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1654. self._request_topic_sub_mid: int | None = None
  1655. self._request_topic_sub_time: float = 0.0
  1656. self._request_topic_confirmed: bool = False
  1657. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1658. # we probe by sending an ams_filament_setting and checking the response.
  1659. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1660. self._dev_mode_probed: bool = False
  1661. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1662. self._dev_mode_probe_seq: str | None = None
  1663. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1664. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1665. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1666. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1667. # the printer reports it until the fault clears, so when a later hms[]
  1668. # arrives without it (user enabled Developer Mode and restarted the
  1669. # printer) we drop back to "unknown" and let the probe re-run instead of
  1670. # leaving a permanently-wrong False behind (#2732).
  1671. self._dev_mode_from_hms: bool = False
  1672. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1673. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1674. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1675. self._stale_reconnecting: bool = False
  1676. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1677. # when the frontend polls status faster than paho can reconnect.
  1678. self._last_stale_reconnect: float = 0.0
  1679. # Zombie session detection via ams_filament_setting response tracking (#887).
  1680. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1681. # that develop later (telemetry flows but publishes silently fail).
  1682. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1683. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1684. @property
  1685. def topic_subscribe(self) -> str:
  1686. return f"device/{self.serial_number}/report"
  1687. @property
  1688. def topic_publish(self) -> str:
  1689. return f"device/{self.serial_number}/request"
  1690. @property
  1691. def report_messages_since_connect(self) -> int:
  1692. """Count of report-topic messages received since the latest (re)connect.
  1693. Exposed for the connection diagnostic so it can distinguish "MQTT
  1694. broker accepted us but the printer never published" (typically a
  1695. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1696. bridge that happens to be idle right now. Zero immediately after a
  1697. fresh connect is normal; zero after a full status push cycle is the
  1698. wrong-serial failure mode.
  1699. """
  1700. return self._report_messages_since_connect
  1701. # Maximum time (seconds) without a message before considering connection stale
  1702. STALE_TIMEOUT = 60.0
  1703. def begin_upload(self) -> None:
  1704. """Bambuddy starts an FTP upload to this printer (#3538)."""
  1705. self._uploads_in_flight += 1
  1706. def end_upload(self) -> None:
  1707. """The upload is over; the printer gets STALE_TIMEOUT from now to speak."""
  1708. self._uploads_in_flight = max(0, self._uploads_in_flight - 1)
  1709. self._last_upload_end = time.time()
  1710. def is_stale(self) -> bool:
  1711. """Check if the connection is stale (no messages for too long).
  1712. Not while Bambuddy is uploading to the printer, nor within
  1713. STALE_TIMEOUT after: an A1 says nothing over MQTT while it receives a
  1714. large file, and the forced reconnect that silence used to trigger
  1715. landed just before the print command, which then found the printer
  1716. disconnected and failed the job (#3538).
  1717. """
  1718. if self._last_message_time == 0:
  1719. return False # Never received a message yet
  1720. if self._uploads_in_flight > 0:
  1721. return False
  1722. time_since_last = time.time() - max(self._last_message_time, self._last_upload_end)
  1723. return time_since_last > self.STALE_TIMEOUT
  1724. def mark_power_off(self) -> bool:
  1725. """Presume the printer lost power (smart plug switched off).
  1726. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1727. The presumption is undone by ``_on_message`` if the printer keeps
  1728. talking — inbound traffic proves the power was never cut (#2629).
  1729. Returns True when the state was actually changed.
  1730. """
  1731. if not self.state.connected:
  1732. return False
  1733. previous = self.state.state
  1734. # Blank the state BEFORE recording what to restore. This runs on the
  1735. # event loop while _on_message runs on the paho thread, and the restore
  1736. # is a two-step (read saved state, compare against "unknown"). Writing
  1737. # "unknown" first means an interleaved message either sees no saved
  1738. # state yet (and skips, leaving the next message to restore) or sees a
  1739. # consistent pair — never a saved state paired with a live state it
  1740. # then discards, which would strand the printer on "unknown".
  1741. self.state.connected = False
  1742. self.state.state = "unknown"
  1743. # Only the first mark wins: a second call before any message arrives
  1744. # must not overwrite the real state with the "unknown" it just wrote.
  1745. # Nothing to restore if the state was already blank.
  1746. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1747. self._state_before_power_off = previous
  1748. return True
  1749. def _restore_state_after_false_power_off(self) -> bool:
  1750. """Undo a presumed power-off once the printer proves it is alive.
  1751. ``connected`` self-heals on the next message, but ``state`` does not:
  1752. it is only rewritten when a payload carries ``gcode_state``, and the
  1753. steady-state ``push_status`` frames are partial. Without this the
  1754. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1755. and the queue scheduler treats the printer as not idle the whole time
  1756. (#2629). Returns True when a state was restored.
  1757. """
  1758. previous = self._state_before_power_off
  1759. self._state_before_power_off = None
  1760. if previous is None or self.state.state != "unknown":
  1761. return False
  1762. logger.info(
  1763. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1764. self.serial_number,
  1765. previous,
  1766. )
  1767. self.state.state = previous
  1768. return True
  1769. # Minimum seconds between stale reconnect attempts. Frontend polls
  1770. # status every few seconds — without a cooldown, each poll would
  1771. # force-close the socket before paho has time to reconnect.
  1772. STALE_RECONNECT_COOLDOWN = 30.0
  1773. def check_staleness(self) -> bool:
  1774. """Check staleness and update connected state if stale. Returns True if connected."""
  1775. if self.state.connected and self.is_stale():
  1776. # Don't force-close again if we already did recently — give paho
  1777. # time to reconnect and the printer time to send its first message.
  1778. now = time.time()
  1779. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1780. return self.state.connected
  1781. logger.warning(
  1782. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1783. )
  1784. # A connection that keeps going stale without ever receiving a
  1785. # status report is almost always a wrong or mis-cased serial
  1786. # number — the broker accepts the connection and the subscription
  1787. # regardless, but the printer publishes to device/<real-serial>/
  1788. # report, which is case-sensitive. Surface that once so the user
  1789. # has something actionable instead of an endless reconnect loop.
  1790. # Only meaningful once the *current* session has had time to receive
  1791. # something. _report_messages_since_connect is reset by _on_connect,
  1792. # so a reconnect that lands microseconds before this check leaves it
  1793. # at 0 for reasons that have nothing to do with the serial — which is
  1794. # how a healthy P1S ended up being told to go check its serial number
  1795. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1796. # on this session means the hint only fires when the printer really
  1797. # has published nothing to the topic we subscribed to.
  1798. # _connect_time of 0 means we have no timestamp to judge by (never went
  1799. # through _on_connect); fall back to the old unconditional behaviour
  1800. # rather than silently swallowing the hint.
  1801. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1802. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1803. self._zero_report_hint_logged = True
  1804. logger.warning(
  1805. "[%s] Connected and subscribed, but the printer has sent zero "
  1806. "status reports. The most common cause is a wrong or mis-cased "
  1807. "serial number — the device/<serial>/report MQTT topic is "
  1808. "case-sensitive. Verify the serial number configured in Bambuddy "
  1809. "exactly matches the printer.",
  1810. self.serial_number,
  1811. )
  1812. self._last_stale_reconnect = now
  1813. self.state.connected = False
  1814. if self.on_state_change:
  1815. self.on_state_change(self.state)
  1816. # Route based on caller thread — see force_reconnect_stale_session.
  1817. # check_staleness is normally called from FastAPI handlers (async,
  1818. # gets the hard-reset path) but the dispatcher exists for safety.
  1819. self._stale_reconnecting = True
  1820. self._reset_client_for_reconnect()
  1821. return self.state.connected
  1822. def force_reconnect_stale_session(self, reason: str) -> None:
  1823. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1824. # arriving but our publishes don't reach the printer.
  1825. #
  1826. # Two routing paths:
  1827. #
  1828. # Async-context callers (queue dispatch deadline)
  1829. # → full client teardown + fresh client_id. Wipes paho's client-side
  1830. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1831. # `project_file` from the broken session would otherwise replay on
  1832. # reconnect, mixing stale commands into the next dispatch and
  1833. # triggering 0500_4003 SD R/W on the printer.
  1834. #
  1835. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1836. # zombie detection, both inside `_update_state`)
  1837. # → socket-close fallback. There is no running loop on that thread to
  1838. # hand the rebuilt client, so close the socket and let paho's own
  1839. # loop detect the broken connection and auto-reconnect (same
  1840. # instance, same client_id). paho would re-send its old outbox on
  1841. # that reconnect; _on_connect empties it first (#3454).
  1842. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1843. self._stale_reconnecting = True
  1844. self.state.connected = False
  1845. if self.on_state_change:
  1846. self.on_state_change(self.state)
  1847. self._reset_client_for_reconnect()
  1848. def _reset_client_for_reconnect(self) -> None:
  1849. """Route between hard-reset and socket-close based on caller thread.
  1850. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1851. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1852. answers that and identifies the caller in one go — paho's callback
  1853. thread has no loop; every legitimate hard-reset caller (FastAPI
  1854. handlers, background async tasks) does."""
  1855. try:
  1856. loop = asyncio.get_running_loop()
  1857. except RuntimeError:
  1858. loop = None
  1859. if loop is not None:
  1860. self._loop = loop
  1861. self._hard_reset_client()
  1862. else:
  1863. self._socket_close_for_reconnect()
  1864. def _hard_reset_client(self) -> None:
  1865. """Tear down the paho client entirely and rebuild it with a fresh
  1866. client_id, so the broker drops the old session and paho's local
  1867. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1868. Caller is responsible for setting ``_stale_reconnecting`` and
  1869. broadcasting the disconnected state.
  1870. Returns as fast as it can build a client: the old one's teardown is
  1871. handed off rather than waited on, because waiting on it is what
  1872. stopped the event loop in #3068. See ``retire_paho_client``."""
  1873. old_client = self._client
  1874. self._client = None
  1875. if old_client is not None:
  1876. retire_paho_client(old_client, self.serial_number)
  1877. # Skip reconnect if no asyncio loop is available (test environment or
  1878. # pre-init). The next initial connect() call from PrinterManager will
  1879. # set up the client fresh.
  1880. if self._loop is None:
  1881. return
  1882. try:
  1883. self.connect(loop=self._loop)
  1884. except Exception as e:
  1885. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1886. def _socket_close_for_reconnect(self) -> None:
  1887. """Close the underlying socket so paho's loop thread detects the
  1888. broken connection and triggers auto-reconnect on the SAME client
  1889. instance. Safe to call from paho's own network thread (the loop
  1890. polls the socket on every iteration and handles a closed socket
  1891. gracefully). Used as a fallback when hard-reset isn't safe. The old
  1892. outbox is not re-sent: _on_connect empties it first (#3454)."""
  1893. if self._client:
  1894. try:
  1895. sock = self._client.socket()
  1896. if sock:
  1897. sock.close()
  1898. except Exception:
  1899. pass
  1900. def _drop_previous_connection_commands(self, client) -> None:
  1901. """Forget every command queued on an earlier connection (#3454).
  1902. Called first in on_connect, which paho runs before it re-sends its
  1903. old outbox. Makes every printer command at most once per connection;
  1904. a command lost in the seconds before a drop is clicked again."""
  1905. dropped = discard_queued_publishes(client)
  1906. if dropped is None:
  1907. logger.warning(
  1908. "[%s] Cannot clear paho's outbox on reconnect (paho internals changed); "
  1909. "commands from the previous connection may be sent again",
  1910. self.serial_number,
  1911. )
  1912. elif dropped:
  1913. logger.info(
  1914. "[%s] Dropped %d command(s) queued on the previous MQTT connection",
  1915. self.serial_number,
  1916. dropped,
  1917. )
  1918. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1919. if rc == 0:
  1920. # First, before anything here publishes on the new connection.
  1921. self._drop_previous_connection_commands(client)
  1922. self.state.connected = True
  1923. self.last_connect_error = None
  1924. self.last_connect_error_name = None
  1925. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1926. # A dropped-and-restored MQTT session means the presumed power-off was
  1927. # real (or at least that the printer restarted): there is nothing
  1928. # legitimate left to restore, and the printer will send a full status
  1929. # push shortly. Dropping the saved state keeps a stale one from being
  1930. # broadcast ahead of the first real report (#2629, #1679).
  1931. self._state_before_power_off = None
  1932. # Reset per-connection warning state so warnings fire once per (re)connection
  1933. self._ams_version_warned = set()
  1934. # Preserve cached developer_mode across auto-reconnects to avoid
  1935. # re-probing on every reconnect. The probe (ams_filament_setting to
  1936. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1937. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1938. # once when developer_mode is truly unknown (first connect).
  1939. # Reset probe tracking so stale timeout state doesn't carry over.
  1940. self._dev_mode_probed = False
  1941. self._dev_mode_needs_probe = False
  1942. self._dev_mode_probe_seq = None
  1943. self._dev_mode_probe_time = 0.0
  1944. self._dev_mode_probe_failures = 0
  1945. self._connect_time = time.monotonic()
  1946. self._report_messages_since_connect = 0
  1947. self._last_ams_cmd_time = 0.0
  1948. self._ams_cmd_unanswered = 0
  1949. # Drop any assignment verifications that were mid-flight before the
  1950. # reconnect — their deadlines are stale and the tray state we would
  1951. # compare against is about to be re-pushed from scratch (#2582).
  1952. # Dropping is silent (no failure event) on purpose.
  1953. self._pending_assignments.clear()
  1954. client.subscribe(self.topic_subscribe)
  1955. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1956. if self._request_topic_supported:
  1957. result, mid = client.subscribe(self.topic_publish)
  1958. if result == mqtt.MQTT_ERR_SUCCESS:
  1959. self._request_topic_sub_mid = mid
  1960. self._request_topic_sub_time = time.time()
  1961. self._request_topic_confirmed = False
  1962. else:
  1963. logger.warning(
  1964. "[%s] Failed to send request topic subscription",
  1965. self.serial_number,
  1966. )
  1967. self._request_topic_supported = False
  1968. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1969. # Request full status update (includes nozzle info in push_status response)
  1970. self._request_push_all()
  1971. # Request firmware version info
  1972. self._request_version()
  1973. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1974. # The correct nozzle data comes from push_status.
  1975. # Prime K-profile request (Bambu printers often ignore first request)
  1976. self._prime_kprofile_request()
  1977. # Immediately broadcast connection state change
  1978. if self.on_state_change:
  1979. self.on_state_change(self.state)
  1980. else:
  1981. self.state.connected = False
  1982. self._record_connect_refusal(rc)
  1983. def _record_connect_refusal(self, rc) -> None:
  1984. """Log and remember why the printer refused the MQTT connection.
  1985. The failure branch of ``_on_connect`` used to be a bare
  1986. ``connected = False``, which threw away the only signal that says
  1987. *why* a printer never comes online. The user-visible result was a
  1988. 30-second reconnect loop logging nothing but paho's generic
  1989. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1990. powered-off printer, so "my printer won't print" reports could not be
  1991. triaged without a round trip (#2698).
  1992. Never logs the access code itself; the code is the likely culprit but
  1993. printing it would put a credential in every support bundle.
  1994. """
  1995. code = getattr(rc, "value", rc)
  1996. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1997. self.last_connect_error_name = name
  1998. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1999. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  2000. logger.warning(
  2001. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  2002. "or serial number is wrong — the access code changes every time LAN Only or "
  2003. "Developer Mode is toggled, so re-read it from the printer's screen.",
  2004. self.serial_number,
  2005. name,
  2006. code,
  2007. )
  2008. else:
  2009. self.last_connect_error = CONNECT_ERROR_REFUSED
  2010. logger.warning(
  2011. "[%s] MQTT connection refused by the printer: %s (code %s).",
  2012. self.serial_number,
  2013. name,
  2014. code,
  2015. )
  2016. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  2017. """Handle SUBACK responses to detect request topic subscription rejection."""
  2018. if mid == self._request_topic_sub_mid:
  2019. for rc in reason_code_list:
  2020. if rc.is_failure:
  2021. logger.warning(
  2022. "[%s] Request topic subscription rejected (code=%d: %s). "
  2023. "ams_mapping capture from slicer-initiated prints unavailable.",
  2024. self.serial_number,
  2025. rc.value,
  2026. rc.getName(),
  2027. )
  2028. self._request_topic_supported = False
  2029. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  2030. else:
  2031. logger.info(
  2032. "[%s] Request topic subscription accepted. "
  2033. "ams_mapping capture enabled for slicer-initiated prints.",
  2034. self.serial_number,
  2035. )
  2036. self._request_topic_confirmed = True
  2037. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  2038. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  2039. self._request_topic_sub_mid = None
  2040. self._request_topic_sub_time = 0.0
  2041. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  2042. # Always unblock disconnect() callers, regardless of whether we suppress
  2043. # the state broadcast below. disconnect() sets _disconnection_event and
  2044. # waits on it — every callback path must fire it.
  2045. if self._disconnection_event:
  2046. self._disconnection_event.set()
  2047. # If we intentionally closed the socket for stale reconnect, don't broadcast
  2048. # another state change — check_staleness() already set connected=False and
  2049. # notified the UI. Just log and let paho auto-reconnect.
  2050. if self._stale_reconnecting:
  2051. logger.info(
  2052. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  2053. self.serial_number,
  2054. rc,
  2055. )
  2056. return
  2057. # Ignore spurious disconnect callbacks if we've received a message recently
  2058. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  2059. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  2060. # — only suppress when rc indicates a clean/normal disconnect.
  2061. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  2062. time_since_last_message = time.time() - self._last_message_time
  2063. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  2064. logger.debug(
  2065. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  2066. )
  2067. return
  2068. # Carry the last CONNACK refusal into the disconnect line. paho reports
  2069. # the drop that follows a refused CONNACK as "Unspecified error", so on
  2070. # its own this line says nothing useful about a printer that is looping
  2071. # on bad credentials — and this is the line that fills a support bundle
  2072. # (#2698).
  2073. if self.last_connect_error:
  2074. logger.warning(
  2075. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  2076. self.serial_number,
  2077. rc,
  2078. disconnect_flags,
  2079. self.last_connect_error_name,
  2080. )
  2081. else:
  2082. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  2083. # Detect if request topic subscription caused the disconnect.
  2084. # If we just subscribed and got disconnected before any SUBACK confirmation,
  2085. # the broker likely killed the connection due to the unauthorized subscription.
  2086. if (
  2087. self._request_topic_sub_time > 0
  2088. and not self._request_topic_confirmed
  2089. and time.time() - self._request_topic_sub_time < 10.0
  2090. # A disconnect we asked for says nothing about the subscription.
  2091. and self._disconnection_event is None
  2092. ):
  2093. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  2094. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  2095. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  2096. logger.warning(
  2097. "[%s] Disconnected shortly after request topic subscription %d times. "
  2098. "Disabling request topic for this printer — ams_mapping capture from "
  2099. "slicer-initiated prints is unavailable, and their filament will be "
  2100. "attributed from the printer's own tray reporting instead.",
  2101. self.serial_number,
  2102. failures,
  2103. )
  2104. self._request_topic_supported = False
  2105. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  2106. else:
  2107. logger.info(
  2108. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  2109. "Retrying it on the next connection before giving up.",
  2110. self.serial_number,
  2111. failures,
  2112. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  2113. )
  2114. self._request_topic_sub_mid = None
  2115. self._request_topic_sub_time = 0.0
  2116. self.state.connected = False
  2117. if self.on_state_change:
  2118. self.on_state_change(self.state)
  2119. def _log_message(self, topic: str, direction: str, raw: str) -> None:
  2120. """Record a message for the MQTT Debug log, as it arrived.
  2121. Parsed again from the raw text rather than shared with the handlers:
  2122. processing keeps the payload's "print" dict as the new raw_data and
  2123. writes Bambuddy's merged AMS list and other state into it, so a shared
  2124. dict showed Bambuddy's state instead of what the printer sent (#3356).
  2125. """
  2126. self._message_log.append(
  2127. MQTTLogEntry(
  2128. timestamp=datetime.now(timezone.utc).isoformat(),
  2129. topic=topic,
  2130. direction=direction,
  2131. payload=json.loads(raw),
  2132. )
  2133. )
  2134. def _on_message(self, client, userdata, msg):
  2135. for handler in self._raw_message_handlers:
  2136. try:
  2137. handler(msg.topic, msg.payload)
  2138. except Exception:
  2139. logger.exception(
  2140. "[%s] raw-message handler crashed for topic=%s",
  2141. self.serial_number,
  2142. msg.topic,
  2143. )
  2144. try:
  2145. try:
  2146. raw = msg.payload.decode()
  2147. except UnicodeDecodeError:
  2148. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  2149. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  2150. raw = msg.payload.decode(errors="replace")
  2151. logger.warning(
  2152. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  2153. self.serial_number,
  2154. msg.topic,
  2155. len(msg.payload),
  2156. )
  2157. payload = json.loads(raw)
  2158. # Track last message time - receiving a message proves we're connected
  2159. self._last_message_time = time.time()
  2160. self.state.connected = True
  2161. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  2162. if msg.topic == self.topic_publish:
  2163. # Record it before returning. This topic carries every command
  2164. # travelling *to* the printer, including the ones Bambu Studio
  2165. # sends, and it used to be the one thing an MQTT capture could
  2166. # never show -- which is why "what does Studio put in the drying
  2167. # command?" had no answer from a user's log (#2774). Filed as
  2168. # "out" so the direction filter groups it with our own commands
  2169. # rather than with printer telemetry; anything we send
  2170. # lands twice, once on publish and once on the
  2171. # broker's echo, and the pair is itself evidence the command
  2172. # reached the broker.
  2173. if self._logging_enabled:
  2174. self._log_message(msg.topic, "out", raw)
  2175. self._handle_request_message(payload)
  2176. return
  2177. # Count status reports per connection so check_staleness() can tell
  2178. # "printer never sent a report" apart from a mid-session quiet gap.
  2179. if msg.topic == self.topic_subscribe:
  2180. self._report_messages_since_connect += 1
  2181. # Only report-topic traffic proves the *printer* is alive — the
  2182. # request topic also carries slicer/Bambuddy commands.
  2183. if self._state_before_power_off is not None:
  2184. if self._restore_state_after_false_power_off() and self.on_state_change:
  2185. self.on_state_change(self.state)
  2186. # Log message if logging is enabled
  2187. if self._logging_enabled:
  2188. self._log_message(msg.topic, "in", raw)
  2189. self._process_message(payload)
  2190. except json.JSONDecodeError:
  2191. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  2192. @property
  2193. def _captured_ams_mapping(self):
  2194. """The ams_mapping captured from the current print's command.
  2195. Kept on the state so the status shows it (the slot pills, #1762): the
  2196. printer's own push almost never carries one.
  2197. """
  2198. return self.state.print_ams_mapping
  2199. @_captured_ams_mapping.setter
  2200. def _captured_ams_mapping(self, mapping) -> None:
  2201. self.state.print_ams_mapping = mapping
  2202. def _handle_request_message(self, data: dict) -> None:
  2203. """Intercept print commands on the request topic to capture ams_mapping."""
  2204. print_data = data.get("print", {})
  2205. if not isinstance(print_data, dict):
  2206. return
  2207. command = print_data.get("command", "")
  2208. if command == "project_file":
  2209. # Where the dispatcher put the sliced file. Captured for every
  2210. # project_file, ours included: we publish to this same topic and
  2211. # subscribe to it, so whoever dispatched last wins, which is exactly
  2212. # the print the archive lookup is about to go looking for (#2780).
  2213. url = print_data.get("url")
  2214. if isinstance(url, str) and url:
  2215. self.state.current_project_url = url
  2216. self.state.last_project_url = url
  2217. if "ams_mapping" in print_data:
  2218. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2219. self._captured_mapping_url = url if isinstance(url, str) else None
  2220. logger.info(
  2221. "[%s] Captured ams_mapping from print command: %s",
  2222. self.serial_number,
  2223. self._captured_ams_mapping,
  2224. )
  2225. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  2226. # slicer-launched project_file passes through the request topic,
  2227. # log the full payload so we can diff Studio's field set against
  2228. # ours.
  2229. #
  2230. # This used to read `sequence_id != "20000"`, on the belief that
  2231. # 20000 was ours alone. It is not: 20000 is the slicer convention
  2232. # Bambuddy adopted -- bind_server documents the slicer sending it
  2233. # during detect, and measured on the wire OrcaSlicer dispatched
  2234. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  2235. # counting up from the same base. So the test swallowed whichever
  2236. # slicer dispatch happened to land on 20000, which on a fresh
  2237. # slicer start is the first one. Match our own dispatch instead.
  2238. if self._project_file_key(print_data) == self._own_project_file_key:
  2239. self._own_project_file_key = None
  2240. else:
  2241. logger.info(
  2242. "[%s] External project_file payload: %s",
  2243. self.serial_number,
  2244. json.dumps(print_data),
  2245. )
  2246. def _capture_report_project_file(self, print_data: dict) -> None:
  2247. """Read a print's destination off a ``project_file`` *response* (#1820).
  2248. ``_handle_request_message`` only ever sees the request topic, so a print
  2249. started from the printer's own touchscreen -- which publishes nothing --
  2250. left ``current_project_url`` at None, and the storage verdict fell
  2251. through to the ``sdcard`` fallback for the one case it was written for.
  2252. On an H2S that flag is True (its "card" is the internal eMMC), so the
  2253. verdict came back reachable and the ~110-connection sweep ran in full.
  2254. The printer does announce it: an unsolicited ``project_file`` response
  2255. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  2256. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  2257. This also covers an install nobody had in view: some brokers refuse the
  2258. request-topic subscription, and on those no print of any kind has ever
  2259. populated the field.
  2260. Both kinds of ``project_file`` on this topic are read -- the printer's
  2261. echo of a dispatch and a screen start -- because both name the
  2262. destination in ``url``, which is the only thing the verdict wants. What
  2263. this must NOT do is reuse ``_handle_request_message``'s "External
  2264. project_file payload" diagnostic: our own dispatch is echoed on *both*
  2265. topics, the request-topic echo arrives first and clears
  2266. ``_own_project_file_key``, so by the time this frame lands the key is
  2267. already None and every Bambuddy-started print would log itself as
  2268. someone else's.
  2269. """
  2270. # Same shape as _handle_request_message: the frame is whatever the
  2271. # printer put on the wire, and this is the first thing to touch it.
  2272. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  2273. return
  2274. # A refused dispatch names a file that was never written. Acting on it
  2275. # would pin an archive on a destination nothing ever went to. Logged:
  2276. # nothing else says the printer refused a print it was sent.
  2277. result = str(print_data.get("result") or "")
  2278. if result.upper() != "SUCCESS":
  2279. logger.info(
  2280. "[%s] Printer refused a print start (project_file): result=%s reason=%s url=%s",
  2281. self.serial_number,
  2282. result,
  2283. print_data.get("reason"),
  2284. print_data.get("url"),
  2285. )
  2286. self.last_start_refusal = (result, print_data.get("reason"))
  2287. return
  2288. url = print_data.get("url")
  2289. if not isinstance(url, str) or not url:
  2290. return
  2291. if self.state.current_project_url != url:
  2292. logger.info(
  2293. "[%s] Print destination from the report topic: %s",
  2294. self.serial_number,
  2295. url,
  2296. )
  2297. self.state.current_project_url = url
  2298. self.state.last_project_url = url
  2299. # On a screen start this frame is the only place the mapping appears --
  2300. # no slicer ever sent one. Fill a gap only: when the request topic
  2301. # already captured this print's mapping that copy is the slicer's own,
  2302. # and the echo can arrive without the field at all. A mapping captured
  2303. # for another destination is from a dispatch that never ran (refused,
  2304. # or cancelled before it started, so no completion cleared it).
  2305. stale = self._captured_ams_mapping is not None and self._captured_mapping_url != url
  2306. if (self._captured_ams_mapping is None or stale) and isinstance(print_data.get("ams_mapping"), list):
  2307. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2308. self._captured_mapping_url = url
  2309. logger.info(
  2310. "[%s] Captured ams_mapping from print response: %s",
  2311. self.serial_number,
  2312. self._captured_ams_mapping,
  2313. )
  2314. def _resolve_captured_mapping(self, print_data: dict) -> object:
  2315. """The ``ams_mapping`` of a project_file, with external spools resolved
  2316. from its ``ams_mapping2`` (#3166)."""
  2317. from backend.app.utils.printer_models import is_dual_nozzle_model
  2318. return resolve_external_spools_in_mapping(
  2319. print_data.get("ams_mapping"),
  2320. print_data.get("ams_mapping2"),
  2321. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  2322. self.tray_layout,
  2323. )
  2324. @staticmethod
  2325. def _project_file_key(print_data: dict) -> str:
  2326. """Identity of a project_file dispatch, for telling ours from a slicer's.
  2327. Sequence id alone cannot do it -- every slicer counts up from the same
  2328. 20000 -- so this also carries the file and its destination, which differ
  2329. between any two real dispatches.
  2330. """
  2331. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  2332. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  2333. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  2334. The state dumps in the push_status handler fire whenever their field is
  2335. *present* in the frame — and a full push_status carries every field, so
  2336. they fire on every frame regardless of whether anything changed. Several
  2337. even say "updated" or "changes" in their own comment while doing nothing
  2338. of the sort.
  2339. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  2340. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  2341. minutes: the reporter enabled debug logging as asked and the support
  2342. bundle came back holding under five minutes of history, almost none of it
  2343. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  2344. these dumps.
  2345. Deduplicating on the value keeps every transition — which is the only part
  2346. anyone reads these lines for — and drops the steady-state repetition.
  2347. ``value`` must capture everything interpolated into ``msg``, or a change
  2348. will be swallowed; pass a tuple when the message renders several fields.
  2349. """
  2350. if not logger.isEnabledFor(logging.DEBUG):
  2351. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  2352. # and these clients outlive the toggle. Letting INFO-level frames warm
  2353. # the cache would be self-defeating: the operator turns debug on
  2354. # precisely to see the printer's current state, and a cache already
  2355. # holding every steady-state value would suppress that baseline until
  2356. # something happened to change. On an idle printer the bundle would
  2357. # come back with none of these lines at all.
  2358. #
  2359. # So while debug is off we record nothing and drop whatever we had.
  2360. # Every enable then starts cold and dumps a full baseline on the next
  2361. # frame, exactly as it did before this method existed.
  2362. self._debug_last.clear()
  2363. return
  2364. if self._debug_last.get(key) == value:
  2365. return
  2366. self._debug_last[key] = value
  2367. logger.debug(msg, *args)
  2368. def _process_message(self, payload: dict):
  2369. """Process incoming MQTT message from printer."""
  2370. # Handle top-level AMS data (comes outside of "print" key)
  2371. # Wrap in try/except to prevent breaking the MQTT connection
  2372. if "ams" in payload:
  2373. try:
  2374. self._snow_in_frame = False # a bare AMS frame carries no extruder data
  2375. self._handle_ams_data(payload["ams"])
  2376. except Exception as e:
  2377. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  2378. # Handle xcam data (camera settings and AI detection) at top level
  2379. if "xcam" in payload:
  2380. xcam_data = payload["xcam"]
  2381. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  2382. self._parse_xcam_data(xcam_data)
  2383. # Fire state change callback for top-level xcam (not nested in "print")
  2384. if "print" not in payload and self.on_state_change:
  2385. self.on_state_change(self.state)
  2386. # Handle system responses (accessories info, etc.)
  2387. if "system" in payload:
  2388. system_data = payload["system"]
  2389. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  2390. self._handle_system_response(system_data)
  2391. # Handle info responses (firmware version info from get_version command)
  2392. if "info" in payload:
  2393. info_data = payload["info"]
  2394. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2395. self._handle_version_info(info_data)
  2396. # Parse WiFi signal at top level (some printers send it here)
  2397. if "wifi_signal" in payload:
  2398. wifi_signal = payload["wifi_signal"]
  2399. if isinstance(wifi_signal, (int, float)):
  2400. self.state.wifi_signal = int(wifi_signal)
  2401. elif isinstance(wifi_signal, str):
  2402. try:
  2403. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2404. except ValueError:
  2405. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2406. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2407. from backend.app.utils.printer_models import has_ethernet
  2408. if has_ethernet(self.model):
  2409. self.state.wired_network = self.state.wifi_signal == -90
  2410. # Parse developer LAN mode from top-level "fun" field
  2411. # Some firmware versions send "fun" at the top level, others inside "print"
  2412. if "fun" in payload:
  2413. try:
  2414. fun_val = payload["fun"]
  2415. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2416. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2417. except (ValueError, TypeError):
  2418. pass
  2419. if "print" in payload:
  2420. print_data = payload["print"]
  2421. # Before anything reads the state: this is where a touchscreen-
  2422. # started print announces where its file lives, and the print-start
  2423. # handler asks ~2 s later (#1820).
  2424. self._capture_report_project_file(print_data)
  2425. # Check if xcam is nested inside print data
  2426. if "xcam" in print_data:
  2427. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2428. self._parse_xcam_data(print_data["xcam"])
  2429. # Log when we see gcode_state changes
  2430. if "gcode_state" in print_data:
  2431. logger.debug(
  2432. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2433. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2434. )
  2435. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2436. # new-protocol printers. Verified against OrcaSlicer's
  2437. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2438. # and live H2D ON/OFF capture 2026-06-20.
  2439. #
  2440. # Families without cfg (P1S, P1P, A1, A1 Mini) carry it in home_flag
  2441. # bit 10 (#3259). Trusted once a full status report (the same
  2442. # >30-key test as the developer-mode probe) arrived without cfg;
  2443. # from then on every status frame that carries home_flag is read,
  2444. # so a toggle in the slicer shows up without a Force Refresh (P1S
  2445. # capture: each toggle came in a 4-6 key update frame). Before
  2446. # that nothing is read from small frames, so a cfg printer can't
  2447. # be misread from a frame that arrives ahead of its first cfg.
  2448. # Printers that send cfg keep reading it alone.
  2449. #
  2450. # Hold-timer guard: when the user just toggled via the badge, the
  2451. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2452. # for ~3 s before the firmware reflects the change. Without this
  2453. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2454. # Only from a status frame: a project_file ack echoes our own
  2455. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2456. # stuck on every family that doesn't repeat `cfg` in its periodic
  2457. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2458. new_backup = None
  2459. if is_printer_status_frame(print_data):
  2460. if "cfg" in print_data:
  2461. self._backup_cfg_seen = True
  2462. new_backup = parse_ams_filament_backup_from_cfg(print_data["cfg"])
  2463. elif not self._backup_cfg_seen:
  2464. if len(print_data) > 30:
  2465. self._backup_home_flag_trusted = True
  2466. if self._backup_home_flag_trusted:
  2467. new_backup = parse_ams_filament_backup_from_home_flag(print_data.get("home_flag"))
  2468. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2469. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2470. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2471. logger.debug(
  2472. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2473. self.serial_number,
  2474. time.time() - hold_start,
  2475. )
  2476. else:
  2477. logger.info(
  2478. "[%s] AMS Filament Backup: %s",
  2479. self.serial_number,
  2480. "ON" if new_backup else "OFF",
  2481. )
  2482. self.state.ams_filament_backup = new_backup
  2483. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2484. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2485. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2486. if not self._is_dual_nozzle and "device" in print_data:
  2487. dev = print_data.get("device")
  2488. if isinstance(dev, dict):
  2489. ext_info = dev.get("extruder", {}).get("info", [])
  2490. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2491. self._is_dual_nozzle = True
  2492. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2493. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2494. # out of the AMS info bits, but only means anything once we know a
  2495. # switch is installed. Parsing them the other way round would lose
  2496. # the binding on every frame where the two arrive together.
  2497. self._parse_fila_switch(print_data)
  2498. # Before _handle_ams_data too: an H2D's tray_now is a bare slot that
  2499. # this frame's extruder data places (which nozzle, which AMS).
  2500. self._snow_in_frame = self._parse_extruder_position(print_data)
  2501. self._parse_extruder_slots(print_data)
  2502. # Handle AMS data that comes inside print key
  2503. if "ams" in print_data:
  2504. try:
  2505. self._handle_ams_data(print_data["ams"])
  2506. except Exception as e:
  2507. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2508. # Handle vir_slot (H2-series external spool data) — list of external trays
  2509. # Process vir_slot FIRST so it takes priority over vt_tray
  2510. if "vir_slot" in print_data:
  2511. vir_slot = print_data["vir_slot"]
  2512. if isinstance(vir_slot, list) and vir_slot:
  2513. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2514. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2515. # Remap id=255→254 for single-slot printers so active detection works.
  2516. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2517. # A nozzle-rack printer (H3C) reports one input per hotend,
  2518. # 247-255, kept as reported.
  2519. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2520. vir_slot[0]["id"] = "254"
  2521. self.state.raw_data["vt_tray"] = vir_slot
  2522. # Handle vt_tray (virtual tray / external spool) data
  2523. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2524. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2525. # which would overwrite the correct multi-slot vir_slot data)
  2526. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2527. vt_tray = print_data["vt_tray"]
  2528. existing = self.state.raw_data.get("vt_tray")
  2529. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2530. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2531. pass # Keep the vir_slot data
  2532. elif (cached_slot := _external_slot_to_merge(vt_tray, existing)) is not None:
  2533. # A delta carries only what changed, often without the
  2534. # id: a colour-only change on an A1 mini pushes just
  2535. # {"tray_color": ...}. Stored as it came, it emptied the
  2536. # slot until the next full push (#3513).
  2537. self.state.raw_data["vt_tray"] = [{**cached_slot, **vt_tray}]
  2538. else:
  2539. if isinstance(vt_tray, dict):
  2540. vt_tray = [vt_tray]
  2541. self.state.raw_data["vt_tray"] = vt_tray
  2542. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2543. # units, and _handle_ams_data runs before this block — so a change
  2544. # to the external spool alone (e.g. swapping generic TPU for generic
  2545. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2546. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2547. # external-spool identity changes here and fire the same callback.
  2548. self._maybe_trigger_external_spool_change()
  2549. # The external slot's own read-back: its delta can come without
  2550. # any AMS data, which is where the check otherwise runs (#3513).
  2551. if "vt_tray" in print_data and self._pending_assignments:
  2552. self._check_assignment_verifications()
  2553. # Parse ams_status directly from print data (NOT from print.ams)
  2554. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2555. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2556. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2557. if "ams_status" in print_data:
  2558. raw_ams_status = print_data["ams_status"]
  2559. if isinstance(raw_ams_status, str):
  2560. try:
  2561. self.state.ams_status = int(raw_ams_status)
  2562. except ValueError:
  2563. self.state.ams_status = 0
  2564. else:
  2565. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2566. # Compute main and sub status
  2567. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2568. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2569. # Log when ams_status changes (for filament change tracking debug)
  2570. self._debug_on_change(
  2571. "ams_status:print",
  2572. self.state.ams_status,
  2573. "[%s] ams_status: %s (main=%s, sub=%s)",
  2574. self.serial_number,
  2575. self.state.ams_status,
  2576. self.state.ams_status_main,
  2577. self.state.ams_status_sub,
  2578. )
  2579. # Check for command responses
  2580. if "command" in print_data:
  2581. cmd = print_data.get("command")
  2582. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2583. if cmd not in _COMMANDS_LOGGED_BY_NAME_ONLY:
  2584. # The printer reports back commands sent from its own
  2585. # screen too, and this is the only place their content can
  2586. # be seen: H3C Unload All is one command whose fields are
  2587. # not documented anywhere (#3531).
  2588. logger.debug(
  2589. "[%s] %s content: %s", self.serial_number, cmd, json.dumps(print_data, default=str)[:4000]
  2590. )
  2591. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2592. # INFO, not debug: this is the printer's verdict on a write
  2593. # the user just made, and it was invisible in support
  2594. # bundles for as long as it sat at DEBUG (#2718). Same
  2595. # reasoning as ams_filament_drying below.
  2596. logger.info(
  2597. "[%s] %s response: result=%s reason=%s seq=%s",
  2598. self.serial_number,
  2599. cmd,
  2600. print_data.get("result"),
  2601. print_data.get("reason", ""),
  2602. print_data.get("sequence_id"),
  2603. )
  2604. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2605. ack_seq = str(print_data.get("sequence_id", ""))
  2606. if ack_seq in self._pending_cali_acks:
  2607. self._pending_cali_acks[ack_seq] = print_data
  2608. elif cmd == "skip_objects":
  2609. self._handle_skip_objects_answer(print_data)
  2610. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2611. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2612. # A refused ams_filament_setting is the printer's verdict on
  2613. # a write the user just made, and at DEBUG it never reached
  2614. # a support bundle: #2756 reported six manual Configure Slot
  2615. # attempts on an X1C, each returning HTTP 200 with the
  2616. # read-back still showing the previous profile, and no
  2617. # record of what the printer said about any of them. Same
  2618. # promotion as extrusion_cali_set (#2718) and
  2619. # ams_filament_drying (#1447) — but only on a non-success,
  2620. # because unlike those two this command is not rare: every
  2621. # spool assignment and every K-profile re-apply sends one,
  2622. # so promoting each ack would bury the interesting line.
  2623. #
  2624. # The developer-mode probe is excluded. It sends this exact
  2625. # command to the external slot precisely to see it refused
  2626. # on P1 firmware, so its failure is a normal reading rather
  2627. # than a fault. Its response is still matched below (this
  2628. # runs before _handle_dev_mode_probe_response clears the
  2629. # seq), and user-initiated commands can't be mistaken for
  2630. # it — they publish a hardcoded sequence_id of "0".
  2631. result = print_data.get("result")
  2632. is_dev_mode_probe = (
  2633. self._dev_mode_probe_seq is not None
  2634. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2635. )
  2636. # extrusion_cali_sel too (FW-C3): every RFID re-read
  2637. # re-applies the spool's K-profile and logs "Applied PA
  2638. # profile", so its refusal must reach the bundle beside it.
  2639. # The printer's word, not a verdict: the extrusion_cali_*
  2640. # acks are known to say "fail" for writes that applied.
  2641. if not is_dev_mode_probe and isinstance(result, str) and result.lower() != "success":
  2642. logger.info(
  2643. "[%s] %s refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2644. self.serial_number,
  2645. cmd,
  2646. result,
  2647. print_data.get("reason", ""),
  2648. print_data.get("ams_id"),
  2649. print_data.get("tray_id"),
  2650. )
  2651. # AMS drying responses are rare (user-initiated only) and the
  2652. # full payload — including `result` and any `reason` code —
  2653. # is the only way to diagnose silent rejections like #1447.
  2654. # INFO level so the body lands in support bundles by default.
  2655. elif cmd == "ams_filament_drying":
  2656. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2657. # RFID re-reads are user-initiated and rare, and a refusal was
  2658. # invisible until #3206 (X1Plus answering FAIL / ERROR STATE).
  2659. # gcode_line acks are only of interest when they answer our
  2660. # M620 R fallback, so those are matched by sequence_id alone.
  2661. ack_seq = str(print_data.get("sequence_id", ""))
  2662. if (
  2663. cmd in ("ams_get_rfid", "gcode_line")
  2664. and ack_seq in self._pending_rfid_acks
  2665. and "result" in print_data
  2666. ):
  2667. logger.info(
  2668. "[%s] %s response: result=%s reason=%s seq=%s",
  2669. self.serial_number,
  2670. cmd,
  2671. print_data.get("result"),
  2672. print_data.get("reason", ""),
  2673. ack_seq,
  2674. )
  2675. self._pending_rfid_acks[ack_seq] = print_data
  2676. # Check for developer mode probe response
  2677. if (
  2678. cmd == "ams_filament_setting"
  2679. and self._dev_mode_probe_seq is not None
  2680. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2681. ):
  2682. self._handle_dev_mode_probe_response(print_data)
  2683. # Track user-initiated ams_filament_setting responses (#887
  2684. # zombie detection). Reset both the timer AND the unanswered
  2685. # counter on ANY response — the response proves the channel is
  2686. # alive, so the counter must not stay armed even when the
  2687. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2688. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2689. # caused #1164: one sluggish response (>10s) would set the
  2690. # counter to 1 and zero the timer; the late response arrived
  2691. # but was ignored by this branch (timer is 0); the counter
  2692. # stayed at 1 indefinitely; the very next slow response —
  2693. # possibly hours later, on a totally unrelated command — would
  2694. # take it to 2 and force-reconnect, surfacing as "filament
  2695. # config doesn't reach the printer ~6 changes in".
  2696. elif cmd == "ams_filament_setting":
  2697. self._last_ams_cmd_time = 0.0
  2698. self._ams_cmd_unanswered = 0
  2699. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2700. if is_kprofile_response:
  2701. self._handle_kprofile_response(print_data)
  2702. # An extrusion_cali_get response echoes the *requested* nozzle
  2703. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2704. # installed hardware. Feeding it to _update_state clobbered the real
  2705. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2706. # which then failed the #1899 dispatch guard. The response carries no
  2707. # status telemetry, so skip it; the true nozzle comes from pushall.
  2708. # (Same reasoning as get_accessories in _handle_system_response.)
  2709. # The answers to K-profile writes and selections echo the diameter
  2710. # the command named in the same way, so none of them is status.
  2711. if print_data.get("command") not in _KPROFILE_COMMAND_ANSWERS:
  2712. self._update_state(print_data)
  2713. def _handle_system_response(self, data: dict):
  2714. """Handle system responses including accessories info.
  2715. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2716. The correct nozzle data comes from push_status, so we don't update
  2717. nozzle type/diameter from get_accessories. We just log the response
  2718. for debugging purposes.
  2719. """
  2720. command = data.get("command")
  2721. if command == "get_accessories":
  2722. # Log response for debugging - but DON'T use it to update nozzle data
  2723. # because it returns stale values (e.g., 'stainless_steel' when the
  2724. # actual nozzle is 'HH01' hardened steel high-flow)
  2725. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2726. def _handle_version_info(self, data: dict):
  2727. """Handle version info response from get_version command.
  2728. Parses firmware version from the 'ota' module in the module list.
  2729. Also extracts AMS unit firmware versions from AMS modules and stores
  2730. them on the corresponding AMS unit in raw_data so the status route can
  2731. expose them to the frontend.
  2732. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2733. - ``ams/<id>`` – original AMS
  2734. - ``ams_f1/<id>`` – AMS Lite (#3348)
  2735. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2736. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2737. Message format:
  2738. {
  2739. "command": "get_version",
  2740. "module": [
  2741. {"name": "ota", "sw_ver": "01.08.05.00"},
  2742. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2743. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2744. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2745. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2746. ...
  2747. ]
  2748. }
  2749. """
  2750. modules = data.get("module", [])
  2751. if not isinstance(modules, list):
  2752. return
  2753. state_changed = False
  2754. for module in modules:
  2755. if not isinstance(module, dict):
  2756. continue
  2757. if module.get("name") == "ota":
  2758. version = module.get("sw_ver")
  2759. if version:
  2760. old_version = self.state.firmware_version
  2761. self.state.firmware_version = version
  2762. if old_version != version:
  2763. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2764. state_changed = True
  2765. break
  2766. # Extract AMS unit firmware versions from AMS modules.
  2767. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2768. # Always cache regardless of whether AMS data has arrived yet — get_version
  2769. # often arrives before the first push_status, so caching must be unconditional.
  2770. ams_raw = self.state.raw_data.get("ams")
  2771. for module in modules:
  2772. if not isinstance(module, dict):
  2773. continue
  2774. name = module.get("name", "")
  2775. if name == AMS3H_MODULE_NAME:
  2776. name = f"{name}/{self._ams3h_unit_id()}"
  2777. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2778. continue
  2779. try:
  2780. # The A2L's AMS Lite is unit 16 here but stored as 6, like
  2781. # everywhere else it is ingested.
  2782. ams_id = normalize_am_unit_id(int(name.split("/", 1)[1]))
  2783. except (ValueError, IndexError):
  2784. continue
  2785. sw_ver = module.get("sw_ver", "")
  2786. sn = module.get("sn", "")
  2787. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2788. module_type = name.split("/", 1)[0]
  2789. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2790. if sw_ver or sn or module_type:
  2791. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2792. state_changed = True
  2793. # Also directly update any AMS unit already present in raw_data
  2794. if ams_raw and isinstance(ams_raw, list):
  2795. for ams_unit in ams_raw:
  2796. if not isinstance(ams_unit, dict):
  2797. continue
  2798. try:
  2799. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2800. except (ValueError, TypeError):
  2801. unit_id = None
  2802. if unit_id == ams_id:
  2803. if sw_ver:
  2804. ams_unit["sw_ver"] = sw_ver
  2805. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2806. # Only set sn from version info if not already present in AMS data
  2807. if sn and not ams_unit.get("sn"):
  2808. ams_unit["sn"] = sn
  2809. if module_type:
  2810. ams_unit["module_type"] = module_type
  2811. break
  2812. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2813. # included in the broadcast (not just the printer firmware version).
  2814. if state_changed and self.on_state_change:
  2815. self.on_state_change(self.state)
  2816. # Warn if any AMS unit is still missing serial number or firmware version
  2817. # after processing the version info response. Warn only once per connection
  2818. # to avoid repeated noise on older firmware that doesn't report these fields.
  2819. if ams_raw and isinstance(ams_raw, list):
  2820. for ams_unit in ams_raw:
  2821. if not isinstance(ams_unit, dict):
  2822. continue
  2823. ams_id = ams_unit.get("id", "?")
  2824. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2825. key = (ams_id, "sn")
  2826. if key not in self._ams_version_warned:
  2827. self._ams_version_warned.add(key)
  2828. logger.warning(
  2829. "[%s] AMS unit %s: serial number not available in version info",
  2830. self.serial_number,
  2831. ams_id,
  2832. )
  2833. if not ams_unit.get("sw_ver"):
  2834. key = (ams_id, "sw_ver")
  2835. if key not in self._ams_version_warned:
  2836. self._ams_version_warned.add(key)
  2837. logger.warning(
  2838. "[%s] AMS unit %s: firmware version not available in version info",
  2839. self.serial_number,
  2840. ams_id,
  2841. )
  2842. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2843. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2844. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2845. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2846. sw_ver/sn fields without overwriting values already present.
  2847. """
  2848. if not ams_list or not isinstance(ams_list, list):
  2849. return
  2850. cache = self._ams_version_cache
  2851. if not cache:
  2852. return
  2853. for unit in ams_list:
  2854. if not isinstance(unit, dict):
  2855. continue
  2856. raw_id = unit.get("id")
  2857. try:
  2858. unit_id = int(raw_id) if raw_id is not None else None
  2859. except (ValueError, TypeError):
  2860. unit_id = None
  2861. if unit_id is None:
  2862. continue
  2863. cached = cache.get(unit_id)
  2864. if not cached:
  2865. continue
  2866. sw_ver = cached.get("sw_ver") or ""
  2867. sn = cached.get("sn") or ""
  2868. if sw_ver and not unit.get("sw_ver"):
  2869. unit["sw_ver"] = sw_ver
  2870. # Only set sn if not already present in AMS data
  2871. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2872. unit["sn"] = sn
  2873. module_type = cached.get("module_type") or ""
  2874. if module_type and not unit.get("module_type"):
  2875. unit["module_type"] = module_type
  2876. def _parse_xcam_data(self, xcam_data):
  2877. """Parse xcam data for camera settings and AI detection options."""
  2878. if not isinstance(xcam_data, dict):
  2879. return
  2880. current_time = time.time()
  2881. # Helper to check if we should accept incoming value for a module
  2882. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2883. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2884. """Check if we should accept an incoming xcam value.
  2885. OrcaSlicer pattern: After sending a command, ignore incoming data
  2886. for 3 seconds. After that, accept whatever the printer sends.
  2887. """
  2888. if module_name not in self._xcam_hold_start:
  2889. return True # No hold timer, accept incoming
  2890. hold_start = self._xcam_hold_start[module_name]
  2891. elapsed = current_time - hold_start
  2892. if elapsed > self._xcam_hold_time:
  2893. # Hold timer expired - accept incoming and clear hold
  2894. del self._xcam_hold_start[module_name]
  2895. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2896. return True
  2897. # Within hold period - ignore incoming data
  2898. logger.debug(
  2899. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2900. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2901. )
  2902. return False
  2903. # Log all xcam fields for debugging
  2904. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2905. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2906. # fields (spaghetti_detector, etc.) are often stale/cached.
  2907. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2908. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2909. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2910. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2911. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2912. # Sensitivity values: 0=low, 1=medium, 2=high
  2913. if "cfg" in xcam_data:
  2914. cfg = xcam_data["cfg"]
  2915. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2916. def decode_detector(start_bit):
  2917. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2918. sens_bits = (cfg >> start_bit) & 0x3
  2919. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2920. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2921. return enabled, sensitivity
  2922. # Spaghetti detector (bits 5-7)
  2923. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2924. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2925. old_value = self.state.print_options.spaghetti_detector
  2926. if cfg_spaghetti != old_value:
  2927. logger.debug(
  2928. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2929. )
  2930. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2931. # Check hold timer for sensitivity before accepting
  2932. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2933. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2934. logger.debug(
  2935. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2936. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2937. )
  2938. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2939. else:
  2940. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2941. elapsed = current_time - hold_start
  2942. if elapsed <= self._xcam_hold_time:
  2943. logger.debug(
  2944. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2945. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2946. )
  2947. else:
  2948. # Hold expired - accept from cfg
  2949. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2950. logger.debug(
  2951. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2952. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2953. )
  2954. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2955. del self._xcam_hold_start["halt_print_sensitivity"]
  2956. # Pileup detector (bits 8-10)
  2957. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2958. if should_accept_value("pileup_detector", cfg_pileup):
  2959. if cfg_pileup != self.state.print_options.pileup_detector:
  2960. logger.debug(
  2961. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2962. )
  2963. self.state.print_options.pileup_detector = cfg_pileup
  2964. # Pileup sensitivity with hold timer
  2965. if "pileup_sensitivity" not in self._xcam_hold_start:
  2966. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2967. logger.debug(
  2968. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2969. )
  2970. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2971. else:
  2972. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2973. elapsed = current_time - hold_start
  2974. if elapsed > self._xcam_hold_time:
  2975. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2976. logger.debug(
  2977. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2978. )
  2979. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2980. del self._xcam_hold_start["pileup_sensitivity"]
  2981. # Clump/nozzle clumping detector (bits 11-13)
  2982. cfg_clump, cfg_clump_sens = decode_detector(11)
  2983. if should_accept_value("clump_detector", cfg_clump):
  2984. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2985. logger.debug(
  2986. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2987. )
  2988. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2989. # Clump sensitivity with hold timer
  2990. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2991. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2992. logger.debug(
  2993. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2994. )
  2995. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2996. else:
  2997. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2998. elapsed = current_time - hold_start
  2999. if elapsed > self._xcam_hold_time:
  3000. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  3001. logger.debug(
  3002. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  3003. )
  3004. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  3005. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  3006. # Airprint detector (bits 14-16)
  3007. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  3008. if should_accept_value("airprint_detector", cfg_airprint):
  3009. if cfg_airprint != self.state.print_options.airprint_detector:
  3010. logger.debug(
  3011. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  3012. )
  3013. self.state.print_options.airprint_detector = cfg_airprint
  3014. # Airprint sensitivity with hold timer
  3015. if "airprint_sensitivity" not in self._xcam_hold_start:
  3016. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  3017. logger.debug(
  3018. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  3019. )
  3020. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  3021. else:
  3022. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  3023. elapsed = current_time - hold_start
  3024. if elapsed > self._xcam_hold_time:
  3025. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  3026. logger.debug(
  3027. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  3028. )
  3029. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  3030. del self._xcam_hold_start["airprint_sensitivity"]
  3031. # Camera settings
  3032. if "ipcam_record" in xcam_data:
  3033. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  3034. if "timelapse" in xcam_data:
  3035. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  3036. # Track if timelapse was ever active during this print
  3037. if self.state.timelapse and self._was_running:
  3038. self._timelapse_during_print = True
  3039. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  3040. if "print_halt" in xcam_data:
  3041. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  3042. # Skip halt_print_sensitivity field - it's always stale ("medium")
  3043. # We read the actual sensitivity from cfg bits 5-6 above
  3044. if "first_layer_inspector" in xcam_data:
  3045. new_value = bool(xcam_data.get("first_layer_inspector"))
  3046. if should_accept_value("first_layer_inspector", new_value):
  3047. self.state.print_options.first_layer_inspector = new_value
  3048. if "printing_monitor" in xcam_data:
  3049. new_value = bool(xcam_data.get("printing_monitor"))
  3050. if should_accept_value("printing_monitor", new_value):
  3051. self.state.print_options.printing_monitor = new_value
  3052. if "buildplate_marker_detector" in xcam_data:
  3053. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  3054. if should_accept_value("buildplate_marker_detector", new_value):
  3055. self.state.print_options.buildplate_marker_detector = new_value
  3056. if "allow_skip_parts" in xcam_data:
  3057. new_value = bool(xcam_data.get("allow_skip_parts"))
  3058. if should_accept_value("allow_skip_parts", new_value):
  3059. self.state.print_options.allow_skip_parts = new_value
  3060. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  3061. # individual boolean fields (which are not sent by the printer)
  3062. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  3063. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  3064. if "auto_recovery_step_loss" in xcam_data:
  3065. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  3066. if "filament_tangle_detect" in xcam_data:
  3067. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  3068. @staticmethod
  3069. def _resolve_local_slot_from_mapping(
  3070. local_slot: int, mapping_raw: list | None, units: list[int] | None = None
  3071. ) -> int | None:
  3072. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  3073. The MQTT mapping field is an array of snow-encoded values:
  3074. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  3075. Finds entries where the local slot matches, then computes the global tray ID.
  3076. When several match and ``units`` is given (the AMS units on the active
  3077. extruder of a dual-nozzle printer), only those units' trays count.
  3078. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  3079. """
  3080. if not isinstance(mapping_raw, list) or not mapping_raw:
  3081. return None
  3082. candidates = mapped_trays_with_slot(mapping_raw, local_slot) # global tray ID -> AMS unit
  3083. if len(candidates) > 1 and units:
  3084. candidates = {tray: unit for tray, unit in candidates.items() if unit in units}
  3085. if len(candidates) == 1:
  3086. return next(iter(candidates))
  3087. return None
  3088. def _maybe_trigger_external_spool_change(self):
  3089. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  3090. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  3091. an external-spool-only filament swap would otherwise never re-run the
  3092. inventory reconciliation that unlinks a stale ams_id=255 assignment
  3093. (#2575). The reconciliation reads vt_tray from live status itself, so we
  3094. just need to re-fire the callback with the current merged AMS data.
  3095. """
  3096. import hashlib
  3097. vt_tray = self.state.raw_data.get("vt_tray")
  3098. if not isinstance(vt_tray, list):
  3099. return
  3100. # Identity fields only — deliberately exclude `remain` so a print's
  3101. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  3102. fp_parts = [
  3103. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  3104. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  3105. for vt in vt_tray
  3106. if isinstance(vt, dict)
  3107. ]
  3108. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  3109. if vt_hash == self._previous_vt_tray_hash:
  3110. return
  3111. self._previous_vt_tray_hash = vt_hash
  3112. if self.on_ams_change:
  3113. logger.debug(
  3114. "[%s] External spool (vt_tray) changed, triggering sync callback",
  3115. self.serial_number,
  3116. )
  3117. self.on_ams_change(self.state.raw_data.get("ams") or [])
  3118. def _normalize_a2l_am_units(self, ams_list) -> None:
  3119. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  3120. id 16 -> 6 in place, as early as possible, so every downstream reader —
  3121. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  3122. the DB constraint — sees the normalised id and needs no special-casing.
  3123. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  3124. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  3125. both the dict-wrapped and bare-list AMS shapes.
  3126. """
  3127. if not isinstance(ams_list, list):
  3128. return
  3129. for unit in ams_list:
  3130. if not isinstance(unit, dict):
  3131. continue
  3132. try:
  3133. uid = int(unit.get("id"))
  3134. except (TypeError, ValueError):
  3135. continue
  3136. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  3137. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  3138. if not self._has_a2l_am_unit:
  3139. logger.info(
  3140. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  3141. self.serial_number,
  3142. A2L_LITE_NORMALIZED_AMS_ID,
  3143. )
  3144. self._has_a2l_am_unit = True
  3145. @property
  3146. def tray_layout(self) -> TrayLayout:
  3147. """How this printer numbers its trays (utils.tray_ids); rebuilt only when its units change."""
  3148. raw = self.state.raw_data
  3149. units, vt_trays = raw.get("ams"), raw.get("vt_tray")
  3150. key = (
  3151. tuple((u.get("id"), u.get("info")) for u in units if isinstance(u, dict))
  3152. if isinstance(units, list)
  3153. else (),
  3154. tuple(vt.get("id") for vt in vt_trays if isinstance(vt, dict)) if isinstance(vt_trays, list) else (),
  3155. self.model,
  3156. )
  3157. if key != self._tray_layout_key:
  3158. from backend.app.utils.printer_models import has_ams3h
  3159. self._tray_layout = TrayLayout.from_state(self.state, has_ams3h(self.model))
  3160. self._tray_layout_key = key
  3161. return self._tray_layout
  3162. def _layout_with(self, ams_list: object) -> TrayLayout:
  3163. """``tray_layout`` including the units of a push not merged into the state yet."""
  3164. if not isinstance(ams_list, list) or not any(isinstance(u, dict) for u in ams_list):
  3165. return self.tray_layout
  3166. units = [u for u in ams_list if isinstance(u, dict)]
  3167. known = self.state.raw_data.get("ams")
  3168. if isinstance(known, list):
  3169. units.extend(u for u in known if isinstance(u, dict))
  3170. vt_trays = self.state.raw_data.get("vt_tray")
  3171. return TrayLayout.from_units(units, vt_trays if isinstance(vt_trays, list) else None)
  3172. def _note_rack_ams(self, layout: TrayLayout) -> None:
  3173. """Log a rack AMS the first time this connection sees it."""
  3174. for ams_id, kind in layout.rack_units:
  3175. if ams_id in self._rack_ams_logged:
  3176. continue
  3177. self._rack_ams_logged.add(ams_id)
  3178. logger.info(
  3179. "[%s] Rack AMS detected: unit %s (AMS type %s), global tray ids %s-%s",
  3180. self.serial_number,
  3181. ams_id,
  3182. int(kind),
  3183. global_tray_id(ams_id, 0, kind),
  3184. global_tray_id(ams_id, RACK_SLOT_COUNT - 1, kind),
  3185. )
  3186. def _ams3h_unit_id(self) -> int:
  3187. """The unit id of this printer's AMS 3H (32 on the H3C)."""
  3188. return next((uid for uid, kind in self.tray_layout.rack_units if kind == AmsType.ZMULTI_A), AMS3H_UNIT_ID)
  3189. def _rack_ams_type(self, ams_id: int) -> AmsType | None:
  3190. """The type of unit ``ams_id`` when it is one of this printer's rack AMS units, else None."""
  3191. for uid, kind in self.tray_layout.rack_units:
  3192. if uid == ams_id:
  3193. return kind
  3194. return None
  3195. def _parse_fila_switch(self, data: dict) -> None:
  3196. """Read the Filament Track Switch block out of a print payload — #1162.
  3197. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  3198. separate from the rest of the state update because ``_handle_ams_data``
  3199. needs the answer before it parses the AMS info bits, and that runs first.
  3200. """
  3201. if not isinstance(data.get("device"), dict):
  3202. return
  3203. fs_data = data["device"].get("fila_switch")
  3204. if not isinstance(fs_data, dict):
  3205. return
  3206. in_raw = fs_data.get("in")
  3207. out_raw = fs_data.get("out")
  3208. self.state.fila_switch = FilaSwitchState(
  3209. installed=True,
  3210. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  3211. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  3212. stat=int(fs_data.get("stat", 0) or 0),
  3213. info=int(fs_data.get("info", 0) or 0),
  3214. )
  3215. def _parse_extruder_position(self, data: dict) -> bool:
  3216. """Read which nozzle is active and which tray each nozzle holds.
  3217. From ``device.extruder``: ``state`` bit 8 is the active nozzle, each
  3218. ``info`` entry's ``snow`` names its AMS and slot. Run on a frame before
  3219. its AMS block, because an H2D's tray_now is a bare slot that only the
  3220. extruder data of the same frame places. Returns True when the frame
  3221. carried the active nozzle's snow. A malformed value is skipped, never
  3222. raised: this runs ahead of everything else the frame carries.
  3223. """
  3224. device = data.get("device")
  3225. extruder = device.get("extruder") if isinstance(device, dict) else None
  3226. if not isinstance(extruder, dict):
  3227. return False
  3228. try:
  3229. state_val = int(extruder["state"]) if "state" in extruder else None
  3230. except (TypeError, ValueError):
  3231. state_val = None
  3232. if state_val is not None:
  3233. # Extract bit 8 for extruder position
  3234. new_extruder = (state_val >> 8) & 0x1
  3235. if new_extruder != self.state.active_extruder:
  3236. logger.debug(
  3237. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  3238. )
  3239. self.state.active_extruder = new_extruder
  3240. extruder_info = extruder.get("info")
  3241. if not isinstance(extruder_info, list) or len(extruder_info) < 2:
  3242. return False
  3243. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  3244. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  3245. snow_read: set[int] = set()
  3246. for ext_info in extruder_info:
  3247. if not isinstance(ext_info, dict) or "id" not in ext_info or "snow" not in ext_info:
  3248. continue
  3249. try:
  3250. ext_id = int(ext_info["id"])
  3251. snow = int(ext_info["snow"])
  3252. except (TypeError, ValueError):
  3253. continue
  3254. if ext_id <= 1:
  3255. snow_read.add(ext_id)
  3256. # Normalize H2D snow value to global tray ID (255 = unloaded)
  3257. global_tray = 255 if snow == 0xFFFF else decode_wire_slot(snow)
  3258. if global_tray is None:
  3259. continue
  3260. if self.state.h2d_extruder_snow.get(ext_id) != global_tray:
  3261. logger.debug(
  3262. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: raw={snow} -> global tray {global_tray}"
  3263. )
  3264. self.state.h2d_extruder_snow[ext_id] = global_tray
  3265. return self.state.active_extruder in snow_read
  3266. def _parse_extruder_slots(self, data: dict) -> None:
  3267. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  3268. Absent on printers that do not report the block, in which case the
  3269. previous answer is kept rather than cleared: a partial payload carrying
  3270. only temperatures must not look like "both hotends are now empty".
  3271. """
  3272. device = data.get("device")
  3273. if not isinstance(device, dict):
  3274. return
  3275. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  3276. if not isinstance(info, list) or not info:
  3277. return
  3278. slots: dict[int, ExtruderSlot] = {}
  3279. for entry in info:
  3280. if not isinstance(entry, dict) or "id" not in entry:
  3281. continue
  3282. try:
  3283. ext_id = int(entry["id"])
  3284. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  3285. flags = int(entry.get("info", 0) or 0)
  3286. except (TypeError, ValueError):
  3287. continue
  3288. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  3289. ams_id = slot_id = None
  3290. else:
  3291. ams_id = (snow >> 8) & 0xFF
  3292. slot_id = snow & 0xFF
  3293. slots[ext_id] = ExtruderSlot(
  3294. ams_id=ams_id,
  3295. slot_id=slot_id,
  3296. has_filament=bool(flags & 0b10),
  3297. )
  3298. if slots:
  3299. self.state.extruder_slots = slots
  3300. def _handle_ams_data(self, ams_data):
  3301. """Handle AMS data changes for Spoolman integration.
  3302. This is called when we receive top-level AMS data in MQTT messages.
  3303. It detects changes and triggers the callback for Spoolman sync.
  3304. """
  3305. import hashlib
  3306. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  3307. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  3308. ams_list = None
  3309. if isinstance(ams_data, dict):
  3310. if "ams" in ams_data:
  3311. ams_list = ams_data["ams"]
  3312. self._normalize_a2l_am_units(ams_list)
  3313. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3314. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  3315. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  3316. if non_list_fields:
  3317. self._debug_on_change(
  3318. "ams_dict_fields",
  3319. non_list_fields,
  3320. "[%s] AMS dict fields: %s",
  3321. self.serial_number,
  3322. non_list_fields,
  3323. )
  3324. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  3325. # when checking if we're in filament change mode for tray_now disambiguation
  3326. if "ams_status" in ams_data:
  3327. raw_ams_status = ams_data["ams_status"]
  3328. if isinstance(raw_ams_status, str):
  3329. try:
  3330. self.state.ams_status = int(raw_ams_status)
  3331. except ValueError:
  3332. self.state.ams_status = 0
  3333. else:
  3334. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  3335. # Compute main and sub status
  3336. self.state.ams_status_sub = self.state.ams_status & 0xFF
  3337. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  3338. self._debug_on_change(
  3339. "ams_status:ams",
  3340. self.state.ams_status,
  3341. "[%s] ams_status: %s (main=%s, sub=%s)",
  3342. self.serial_number,
  3343. self.state.ams_status,
  3344. self.state.ams_status_main,
  3345. self.state.ams_status_sub,
  3346. )
  3347. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  3348. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  3349. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  3350. # next compatible slot (#2587). Stored raw here; globalised at the API
  3351. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  3352. # these are local slot numbers (0-3), not global IDs.
  3353. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  3354. if _tk in ams_data:
  3355. _raw = ams_data[_tk]
  3356. if isinstance(_raw, str):
  3357. try:
  3358. _val = int(_raw)
  3359. except ValueError:
  3360. _val = 255
  3361. else:
  3362. _val = _raw if _raw is not None else 255
  3363. prev = getattr(self.state, _attr)
  3364. setattr(self.state, _attr, _val)
  3365. # Log changes only while paused — the moment the operator cares —
  3366. # so a healthy print's normal tar churn doesn't spam the log.
  3367. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  3368. logger.info(
  3369. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  3370. self.serial_number,
  3371. _tk,
  3372. _val,
  3373. )
  3374. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  3375. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  3376. if "tray_now" in ams_data:
  3377. raw_tray_now = ams_data["tray_now"]
  3378. # Convert string to int if needed
  3379. if isinstance(raw_tray_now, str):
  3380. try:
  3381. parsed_tray_now = int(raw_tray_now)
  3382. except ValueError:
  3383. parsed_tray_now = 255
  3384. else:
  3385. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  3386. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  3387. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  3388. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  3389. # — disambiguated below using MQTT mapping field
  3390. ams_map = self.state.ams_extruder_map
  3391. # A rack AMS reports tray_now as its raw slot 0-8 (global 28 +
  3392. # slot). Its units may arrive in this same push, before the merge.
  3393. rack_layout = self._layout_with(ams_list)
  3394. self._note_rack_ams(rack_layout)
  3395. if rack_layout.rack_units and not self._is_dual_nozzle:
  3396. rack_tray = rack_layout.raw_slot_to_global(parsed_tray_now)
  3397. # 255 (nothing on the toolhead, also mid-swap) and any
  3398. # external input id are kept as reported.
  3399. self.state.tray_now = rack_tray if rack_tray is not None else parsed_tray_now
  3400. elif self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3401. # First, check if we have a pending target that matches this slot
  3402. pending_target = self.state.pending_tray_target
  3403. pending_at = self.state.pending_tray_target_at
  3404. if (
  3405. pending_target is not None
  3406. and pending_at is not None
  3407. and time.monotonic() - pending_at > PENDING_TRAY_TARGET_TTL
  3408. ):
  3409. # A load the printer refused or dropped: nothing clears
  3410. # it (tray_now stays 255), and a print loading the same
  3411. # slot number on another AMS long after was shown as
  3412. # this target (FW-C7). Fall through to the snow field.
  3413. self.state.pending_tray_target = None
  3414. self.state.pending_tray_target_at = None
  3415. pending_target = None
  3416. if pending_target is not None:
  3417. # Same slot rule as the snow branch below: an AMS-HT
  3418. # (128-135) has its one tray in slot 0.
  3419. pending_slot = 0 if is_ams_ht_id(pending_target) else pending_target % 4
  3420. if pending_slot == parsed_tray_now:
  3421. # Slot matches our pending target - use the full global ID
  3422. logger.debug(
  3423. f"[{self.serial_number}] H2D tray_now disambiguation: "
  3424. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  3425. )
  3426. self.state.tray_now = pending_target
  3427. # Clear pending target now that load is confirmed
  3428. self.state.pending_tray_target = None
  3429. else:
  3430. # Slot doesn't match our pending target - something changed, use slot as-is
  3431. logger.warning(
  3432. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  3433. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  3434. )
  3435. self.state.tray_now = parsed_tray_now
  3436. # Clear pending target since it's stale
  3437. self.state.pending_tray_target = None
  3438. else:
  3439. # No pending target - use h2d_extruder_snow for accurate disambiguation
  3440. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  3441. active_ext = self.state.active_extruder # 0=right, 1=left
  3442. # Best source: use snow value from device.extruder.info if available
  3443. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  3444. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  3445. snow_slot = (
  3446. None
  3447. if snow_tray is None
  3448. else snow_tray % 4
  3449. if snow_tray < 128
  3450. else (0 if is_ams_ht_id(snow_tray) else -1)
  3451. )
  3452. # A snow from an earlier frame may predate a swap: it
  3453. # names the tray only while it agrees with the slot.
  3454. snow_usable = (
  3455. snow_tray is not None
  3456. and snow_tray != 255
  3457. and (snow_slot == parsed_tray_now or self._snow_in_frame)
  3458. )
  3459. if snow_usable and snow_tray is not None:
  3460. # snow_tray is already normalized to global ID
  3461. if snow_slot == parsed_tray_now:
  3462. if self.state.tray_now != snow_tray:
  3463. logger.debug(
  3464. f"[{self.serial_number}] H2D tray_now from snow: "
  3465. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  3466. )
  3467. self.state.tray_now = snow_tray
  3468. else:
  3469. # Slot mismatch in one frame: the extruder's own
  3470. # report is the complete answer, trust snow
  3471. logger.debug(
  3472. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  3473. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  3474. )
  3475. self.state.tray_now = snow_tray
  3476. else:
  3477. # Fallback: snow not available, use ams_extruder_map (less reliable)
  3478. # Find ALL AMS units on the active extruder
  3479. ams_on_extruder = []
  3480. for ams_id_str, ext_id in ams_map.items():
  3481. if ext_id == active_ext:
  3482. try:
  3483. ams_on_extruder.append(int(ams_id_str))
  3484. except ValueError:
  3485. pass # Skip AMS IDs that aren't valid integers
  3486. # Several AMS (or none the map knows of) leave the
  3487. # slot ambiguous. The printer's own mapping names the
  3488. # trays the running print uses: one of them at this
  3489. # slot is the one feeding (#3242). Only while a print
  3490. # runs: an idle H2 keeps reporting the previous
  3491. # print's mapping.
  3492. mapped_tray = None
  3493. if len(ams_on_extruder) != 1 and self._was_running and not self._completion_triggered:
  3494. mapped_tray = self._resolve_local_slot_from_mapping(
  3495. parsed_tray_now, self.state.raw_data.get("mapping"), ams_on_extruder
  3496. )
  3497. if mapped_tray is not None:
  3498. if self.state.tray_now != mapped_tray:
  3499. logger.debug(
  3500. f"[{self.serial_number}] H2D tray_now: AMS {ams_on_extruder} on extruder "
  3501. f"{active_ext}, slot {parsed_tray_now} -> global ID {mapped_tray} (from mapping)"
  3502. )
  3503. self.state.tray_now = mapped_tray
  3504. elif len(ams_on_extruder) == 1:
  3505. # Single AMS on this extruder - unambiguous
  3506. active_ams_id = ams_on_extruder[0]
  3507. # AMS-HT: single slot per unit, global ID = unit ID
  3508. fallback_tray = global_tray_id(active_ams_id, parsed_tray_now)
  3509. logger.debug(
  3510. f"[{self.serial_number}] H2D tray_now fallback: "
  3511. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {fallback_tray}"
  3512. )
  3513. self.state.tray_now = fallback_tray
  3514. elif len(ams_on_extruder) > 1:
  3515. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  3516. current_tray = self.state.tray_now
  3517. # Determine which AMS unit and slot the current tray belongs to
  3518. if 0 <= current_tray <= 15 or is_ams_ht_id(current_tray):
  3519. # AMS-HT: ID = tray ID, one slot
  3520. current_ams, current_slot = rack_layout.slot_key(current_tray)
  3521. else:
  3522. current_ams = -1
  3523. current_slot = -1
  3524. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  3525. # Current is valid and matches slot - keep it
  3526. logger.debug(
  3527. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3528. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  3529. )
  3530. else:
  3531. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  3532. if parsed_tray_now > 0:
  3533. candidates = [a for a in ams_on_extruder if a <= 3]
  3534. else:
  3535. candidates = ams_on_extruder
  3536. if len(candidates) == 1:
  3537. cand = candidates[0]
  3538. resolved = global_tray_id(cand, parsed_tray_now)
  3539. logger.debug(
  3540. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3541. f"narrowed to AMS {cand} -> global ID {resolved}"
  3542. )
  3543. self.state.tray_now = resolved
  3544. else:
  3545. # Genuinely ambiguous. This is the second between a
  3546. # filament change reaching the AMS report and the
  3547. # extruder's snow, which then names the tray. Using
  3548. # the bare slot would point at AMS 0 and put that
  3549. # tray in the usage change log (#3242), so keep the
  3550. # current tray until snow arrives.
  3551. logger.debug(
  3552. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on "
  3553. f"extruder {active_ext}, slot {parsed_tray_now} is ambiguous without snow, "
  3554. f"keeping {current_tray}"
  3555. )
  3556. else:
  3557. # No AMS on this extruder that the map knows of: the
  3558. # slot can't be placed, keep the current tray (#3242)
  3559. logger.debug(
  3560. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  3561. f"slot {parsed_tray_now} can't be placed without snow, keeping {self.state.tray_now}"
  3562. )
  3563. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3564. # Single-nozzle printer with tray_now in 0-3 range.
  3565. # #1822: H2S firmware reports tray_now as the AMS's idle
  3566. # slot (typically 0) when the active feed is actually the
  3567. # external spool. X1C / P1S / A1 correctly report 254 in
  3568. # that case; H2S does not. When the slicer-captured
  3569. # ams_mapping is all-external (every entry is 254, or -1
  3570. # when the command carried no ams_mapping2 to resolve it
  3571. # from, #3166), the print can only be feeding from the
  3572. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  3573. # AMS-only mappings are NOT overridden — there's no
  3574. # evidence the firmware misreports in those cases. Prints
  3575. # started without a captured mapping (printer-screen start,
  3576. # or before Bambuddy connected) fall through unchanged.
  3577. captured = self._captured_ams_mapping
  3578. if captured and all(s in (-1, 254, 255) for s in captured):
  3579. if self.state.tray_now != 254:
  3580. logger.debug(
  3581. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  3582. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  3583. )
  3584. self.state.tray_now = 254
  3585. else:
  3586. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  3587. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  3588. # (snow-encoded) to resolve the correct AMS unit.
  3589. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  3590. try:
  3591. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  3592. except (ValueError, TypeError):
  3593. ams_exist = 0
  3594. num_ams = bin(ams_exist).count("1")
  3595. if self._has_a2l_am_unit and num_ams <= 1:
  3596. # A2L AMS-Lite (normalised unit 6): the firmware reports
  3597. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  3598. # otherwise usage tracking keys the wrong spool (it would
  3599. # deduct from AMS 0's slot). Confirmed by capture:
  3600. # tray_now="2" while printing physical slot 3.
  3601. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  3602. elif num_ams > 1:
  3603. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  3604. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  3605. if self._has_a2l_am_unit:
  3606. # A2L Lite + a regular AMS attached together is out of
  3607. # scope: the flat mapping ids are unknown for that combo
  3608. # and could collide with AMS 0. Fall through to the
  3609. # mapping-based resolve, but warn — a capture is needed.
  3610. logger.warning(
  3611. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3612. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3613. self.serial_number,
  3614. )
  3615. mapping_raw = self.state.raw_data.get("mapping")
  3616. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3617. if resolved is not None:
  3618. if resolved != parsed_tray_now:
  3619. logger.debug(
  3620. f"[{self.serial_number}] Multi-AMS tray_now: "
  3621. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3622. )
  3623. self.state.tray_now = resolved
  3624. else:
  3625. # No mapping available (not printing, or ambiguous) — use as-is.
  3626. # This matches the old behavior and is correct for AMS 0.
  3627. self.state.tray_now = parsed_tray_now
  3628. else:
  3629. # Single AMS — local slot 0-3 equals global ID
  3630. self.state.tray_now = parsed_tray_now
  3631. else:
  3632. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3633. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3634. # During filament change, the printer sends 255 first (unload), then the slot.
  3635. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3636. # Trust the printer's reported value.
  3637. self.state.tray_now = parsed_tray_now
  3638. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3639. tn = self.state.tray_now
  3640. if rack_layout.is_loaded_tray(tn):
  3641. # Log tray change for mid-print usage splitting. Gate on the
  3642. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3643. # new print, `_completion_triggered` set when on_print_complete
  3644. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3645. # firmware briefly transitions out of RUNNING during AMS
  3646. # auto-fallback (#957), so a literal-string gate misses the
  3647. # switch and the usage tracker double-credits at completion.
  3648. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3649. self.state.tray_change_log.append((tn, self.state.layer_num))
  3650. logger.info(
  3651. "[%s] Tray change during print: tray=%d at layer=%d",
  3652. self.serial_number,
  3653. tn,
  3654. self.state.layer_num,
  3655. )
  3656. if self.on_tray_change:
  3657. self.on_tray_change(tn, self.state.layer_num)
  3658. self.state.last_loaded_tray = self.state.tray_now
  3659. self._debug_on_change(
  3660. "tray_now",
  3661. self.state.tray_now,
  3662. "[%s] tray_now updated: %s",
  3663. self.serial_number,
  3664. self.state.tray_now,
  3665. )
  3666. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3667. # state when checking filament change mode for H2D disambiguation
  3668. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3669. # We've already processed the status fields above, so just return if no ams list
  3670. if ams_list is None:
  3671. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3672. return
  3673. elif isinstance(ams_data, list):
  3674. ams_list = ams_data
  3675. self._normalize_a2l_am_units(ams_list)
  3676. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3677. else:
  3678. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3679. return
  3680. # Merge AMS data instead of replacing, to handle partial updates
  3681. # During prints, the printer may only send updates for active AMS units
  3682. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3683. existing_ams = self.state.raw_data.get("ams")
  3684. # #3499: anything but the merged unit list (once, the frame's own AMS
  3685. # object) would fail every later frame on its string keys.
  3686. if not isinstance(existing_ams, list):
  3687. existing_ams = []
  3688. existing_by_id = {
  3689. ams.get("id"): ams for ams in existing_ams if isinstance(ams, dict) and ams.get("id") is not None
  3690. }
  3691. # Update existing units with new data, add new units
  3692. for ams_unit in ams_list:
  3693. ams_id = ams_unit.get("id")
  3694. if ams_id is not None:
  3695. existing_unit = existing_by_id.get(ams_id)
  3696. if existing_unit and "tray" in ams_unit:
  3697. # Deep merge trays to preserve fields from previous updates
  3698. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3699. merged_trays = []
  3700. for new_tray in ams_unit.get("tray", []):
  3701. tray_id = new_tray.get("id")
  3702. if tray_id is not None and tray_id in existing_trays:
  3703. # Merge: start with existing, update with new non-empty values
  3704. merged_tray = existing_trays[tray_id].copy()
  3705. # Detect slot-clearing updates (spool removal):
  3706. # When tray_type is explicitly empty, clear everything
  3707. # including RFID data (tag_uid/tray_uuid).
  3708. slot_clearing = new_tray.get("tray_type") == ""
  3709. # Some printers (e.g. H2D) only send {id, state} in
  3710. # incremental updates when a tray is not fully loaded.
  3711. # state=11 means loaded; other values (9=empty,
  3712. # 10=spool present but filament not in feeder) indicate
  3713. # the slot should be cleared. Without this, old
  3714. # tray_type/tray_color persist indefinitely (#784).
  3715. #
  3716. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3717. # tray high-temp dry box, id >= 128) reports its loaded
  3718. # tray as state=9, not 11 — it doesn't feed filament into
  3719. # a shared buffer the way a 4-slot AMS does. Applying the
  3720. # `state != 11 → empty` rule to an HT unit wiped a present
  3721. # spool on every power-on, when the printer sends a partial
  3722. # {id, state=9} for the HT tray (#2594). Skip the state
  3723. # heuristic for HT units — a genuine HT spool removal still
  3724. # clears via the explicit tray_type=="" case above and the
  3725. # tray_exist_bits cleanup below.
  3726. #
  3727. # A rack AMS (the H3C's AMS 3H) reports a loaded slot
  3728. # as state=27, so it is skipped the same way.
  3729. try:
  3730. _is_ht_unit = int(ams_id) >= 128 or is_rack_ams(
  3731. unit_ams_type(int(ams_id), ams_unit.get("info") or existing_unit.get("info"))
  3732. )
  3733. except (TypeError, ValueError):
  3734. _is_ht_unit = False
  3735. tray_state = new_tray.get("state")
  3736. if (
  3737. tray_state is not None
  3738. and tray_state != 11
  3739. and not _is_ht_unit
  3740. and "tray_type" not in new_tray
  3741. and merged_tray.get("tray_type")
  3742. ):
  3743. logger.info(
  3744. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3745. self.serial_number,
  3746. ams_id,
  3747. tray_id,
  3748. tray_state,
  3749. )
  3750. slot_clearing = True
  3751. # The incremental update only has {id, state} — inject
  3752. # empty values for all content fields so the merge loop
  3753. # below clears the stale data from merged_tray.
  3754. new_tray.update(
  3755. {
  3756. "tray_type": "",
  3757. "tray_sub_brands": "",
  3758. "tray_color": "",
  3759. "tray_id_name": "",
  3760. "tray_info_idx": "",
  3761. "tag_uid": "0000000000000000",
  3762. "tray_uuid": "00000000000000000000000000000000",
  3763. "remain": 0,
  3764. "k": None,
  3765. "cali_idx": None,
  3766. }
  3767. )
  3768. for key, value in new_tray.items():
  3769. # Fields that should always be updated (even with empty/zero values):
  3770. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3771. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3772. # tray_id_name: slot content indicators that must be cleared
  3773. # when a spool is removed (fixes #147 - old AMS empty slot)
  3774. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3775. # They are only cleared during spool removal (slot_clearing=True).
  3776. # Periodic AMS updates often include empty RFID fields which
  3777. # would overwrite valid data from the initial pushall.
  3778. always_update_fields = (
  3779. "remain",
  3780. "k",
  3781. "id",
  3782. "cali_idx",
  3783. "tray_type",
  3784. "tray_sub_brands",
  3785. "tray_info_idx",
  3786. "tray_color",
  3787. "tray_id_name",
  3788. )
  3789. if (
  3790. key in always_update_fields
  3791. or slot_clearing
  3792. or value
  3793. not in (
  3794. None,
  3795. "",
  3796. "0000000000000000",
  3797. "00000000000000000000000000000000",
  3798. )
  3799. ):
  3800. merged_tray[key] = value
  3801. merged_trays.append(merged_tray)
  3802. else:
  3803. merged_trays.append(new_tray)
  3804. # Update ams_unit with merged trays. Spread existing_unit
  3805. # FIRST so top-level fields the partial update omits —
  3806. # dry_time, info (which drives dry_status / dry_sub_status),
  3807. # humidity, temp — are preserved instead of dropped. The
  3808. # printer sends tray-bearing partials that carry no drying
  3809. # fields; without this, dry_time reads as absent → 0 and the
  3810. # falling-edge detector below fires a false "drying complete"
  3811. # (#1462). Mirrors the no-tray branch's merge semantics.
  3812. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3813. elif existing_unit:
  3814. # Partial update without tray data: merge new fields into existing
  3815. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3816. ams_unit = {**existing_unit, **ams_unit}
  3817. existing_by_id[ams_id] = ams_unit
  3818. # The merge keeps a unit the push doesn't list, so an unplugged AMS used
  3819. # to stay until Bambuddy restarted (#3356). Drop one only on the
  3820. # printer's own word that it is gone.
  3821. if isinstance(ams_data, dict):
  3822. listed = {ams_unit.get("id") for ams_unit in ams_list}
  3823. for ams_id in [i for i in existing_by_id if i not in listed]:
  3824. if unit_reported_absent(ams_id, ams_list, ams_data.get("ams_exist_bits")):
  3825. logger.info("[%s] AMS %s no longer attached, removing it", self.serial_number, ams_id)
  3826. del existing_by_id[ams_id]
  3827. # Convert back to list, sorted by ID for consistent ordering
  3828. merged_ams = sorted(existing_by_id.values(), key=_ams_unit_order)
  3829. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3830. # Shared with the VP bridge cache so the slicer-facing view stays in
  3831. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3832. # for the full rationale and the printer-shutdown guard.
  3833. if isinstance(ams_data, dict):
  3834. apply_tray_exist_bits(
  3835. merged_ams,
  3836. ams_data.get("tray_exist_bits"),
  3837. power_on_flag=ams_data.get("power_on_flag", True),
  3838. log_label=self.serial_number,
  3839. annotate_exists=True,
  3840. )
  3841. self.state.raw_data["ams"] = merged_ams
  3842. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3843. self._apply_ams_version_cache(merged_ams)
  3844. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3845. self.state.last_ams_update = time.time()
  3846. self._debug_on_change(
  3847. "merged_ams",
  3848. (len(ams_list), len(merged_ams)),
  3849. "[%s] Merged AMS data: %s new units, %s total",
  3850. self.serial_number,
  3851. len(ams_list),
  3852. len(merged_ams),
  3853. )
  3854. # Extract ams_extruder_map from each AMS unit's info field
  3855. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3856. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3857. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3858. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3859. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3860. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3861. #
  3862. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3863. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3864. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3865. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3866. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3867. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3868. # the switch being installed.
  3869. #
  3870. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3871. # the full map. Merge into existing map to preserve entries from prior updates.
  3872. fts_installed = self.state.fila_switch.installed
  3873. inlet_moves: list[tuple[int, str]] = []
  3874. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3875. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3876. # A rack AMS feeds the one extruder of a rack printer; listed here it
  3877. # would make the slot/dispatch code assume two nozzles.
  3878. rack_ams_ids = {uid for uid, _ in TrayLayout.from_units(merged_ams).rack_units}
  3879. for ams_unit in merged_ams:
  3880. ams_id = ams_unit.get("id")
  3881. info = ams_unit.get("info")
  3882. if _mqtt_int(ams_id) in rack_ams_ids:
  3883. continue
  3884. if ams_id is not None and info is not None:
  3885. try:
  3886. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3887. info_val = int(str(info), 16)
  3888. # Extract 4 bits starting at bit 8 for extruder assignment
  3889. extruder_id = (info_val >> 8) & 0xF
  3890. if extruder_id == 0xE:
  3891. if fts_installed:
  3892. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3893. if inlet is not None:
  3894. previous = ams_switch_inlet.get(str(ams_id))
  3895. ams_switch_inlet[str(ams_id)] = inlet
  3896. self._debug_on_change(
  3897. f"ams_inlet:{ams_id}",
  3898. inlet,
  3899. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3900. self.serial_number,
  3901. ams_id,
  3902. info,
  3903. inlet,
  3904. )
  3905. if previous is not None and previous != inlet:
  3906. # Only a genuine move, never the first sighting:
  3907. # re-applying K-profiles on every reconnect would
  3908. # fight a binding the operator set deliberately.
  3909. logger.info(
  3910. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3911. self.serial_number,
  3912. ams_id,
  3913. inlet,
  3914. previous,
  3915. )
  3916. inlet_moves.append((int(ams_id), inlet))
  3917. continue
  3918. ams_extruder_map[str(ams_id)] = extruder_id
  3919. self._debug_on_change(
  3920. f"ams_info:{ams_id}",
  3921. (info, extruder_id),
  3922. "[%s] AMS %s info=0x%s -> extruder %s",
  3923. self.serial_number,
  3924. ams_id,
  3925. info,
  3926. extruder_id,
  3927. )
  3928. except (ValueError, TypeError):
  3929. pass # Skip AMS units with unparseable info bitmask values
  3930. if ams_extruder_map:
  3931. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3932. self.state.ams_extruder_map = ams_extruder_map
  3933. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3934. if ams_switch_inlet:
  3935. self.state.ams_switch_inlet = ams_switch_inlet
  3936. for moved_ams_id, moved_inlet in inlet_moves:
  3937. if self.on_fts_inlet_change:
  3938. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3939. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3940. # BambuStudio DevFilaSystem.cpp parses info bits:
  3941. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3942. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3943. for ams_unit in merged_ams:
  3944. info = ams_unit.get("info")
  3945. if info is not None:
  3946. try:
  3947. info_val = int(str(info), 16)
  3948. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3949. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3950. except (ValueError, TypeError):
  3951. pass # Skip unparseable info values
  3952. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3953. if "dry_sf_reason" in ams_unit:
  3954. sf_reason = ams_unit["dry_sf_reason"]
  3955. if isinstance(sf_reason, list):
  3956. ams_unit["dry_sf_reason"] = [
  3957. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3958. ]
  3959. else:
  3960. ams_unit["dry_sf_reason"] = []
  3961. # Persist updated drying fields back to raw_data
  3962. self.state.raw_data["ams"] = merged_ams
  3963. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3964. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3965. # — fire the callback so smart-plug auto-off-after-drying can run,
  3966. # and drop our cached target-cycle params so the badge stops claiming
  3967. # an active cycle. Works identically for queue-triggered, ambient,
  3968. # and manual drying because we observe the firmware-reported state.
  3969. for ams_unit in merged_ams:
  3970. try:
  3971. ams_id = int(ams_unit.get("id", -1))
  3972. except (TypeError, ValueError):
  3973. continue
  3974. if ams_id < 0:
  3975. continue
  3976. # The firmware phase outranks the stalled-countdown heuristic even
  3977. # on a transient-zero frame, which the completion guard below skips.
  3978. # Clear a previously raised flag before that early continue.
  3979. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3980. ams_unit["dry_countdown_stalled"] = False
  3981. # Only evaluate the edge when this update carries an explicit
  3982. # dry_time. An absent / unparseable value is NOT zero — treating
  3983. # it as 0 lets a tray-only partial fake a drying-complete edge
  3984. # (#1462). Skip without touching the remembered value so the
  3985. # next update that DOES carry dry_time sees the true previous.
  3986. raw_dry_time = ams_unit.get("dry_time")
  3987. if raw_dry_time is None:
  3988. continue
  3989. try:
  3990. current = int(raw_dry_time)
  3991. except (TypeError, ValueError):
  3992. continue
  3993. # A dry_time of 0 only means "finished" when the unit also reports
  3994. # an idle phase. Between the command ack and the countdown settling
  3995. # the firmware publishes a transient 0 while the AMS is still
  3996. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3997. # 12-hour cycle. Taking that at face value dropped the cached target
  3998. # (leaving the badge to guess the filament from tray 1, so a PLA
  3999. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  4000. # schedules smart-plug auto-off. dry_status comes from the same info
  4001. # hex parsed above; when it is absent we let the edge through, so a
  4002. # firmware that never reports one still ends its cycles.
  4003. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  4004. # Leave the remembered value alone, exactly as the absent-
  4005. # dry_time skip above does: whichever push ends the cycle for
  4006. # real must still see a non-zero previous.
  4007. logger.debug(
  4008. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  4009. self.serial_number,
  4010. ams_id,
  4011. ams_unit.get("dry_status"),
  4012. )
  4013. continue
  4014. seen_before = ams_id in self._previous_dry_times
  4015. previous = self._previous_dry_times.get(ams_id, 0)
  4016. self._previous_dry_times[ams_id] = current
  4017. if current > 0:
  4018. cycle = self._dry_cycles.get(ams_id)
  4019. if cycle is None or previous == 0:
  4020. cycle = {
  4021. "peak": current,
  4022. # A rise from an observed 0 is the cycle's first minute.
  4023. # A first sighting already counting down is not.
  4024. "start_seen": seen_before,
  4025. "target": self._drying_targets.get(ams_id),
  4026. }
  4027. self._dry_cycles[ams_id] = cycle
  4028. elif current > int(cycle["peak"]):
  4029. cycle["peak"] = current
  4030. # Stall detection: stamp value CHANGES only — a live countdown
  4031. # decrements once a minute, so repeats of the same value within
  4032. # the minute must not refresh the stamp, and a frame without a
  4033. # dry_time never reaches here (the absent-value skip above).
  4034. now_mono = time.monotonic()
  4035. if current != previous or ams_id not in self._dry_time_changed_at:
  4036. self._dry_time_changed_at[ams_id] = now_mono
  4037. ams_unit["dry_countdown_stalled"] = bool(
  4038. current > 0
  4039. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  4040. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  4041. )
  4042. if previous > 0 and current == 0:
  4043. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  4044. if self.on_drying_complete:
  4045. self.on_drying_complete(ams_id)
  4046. cycle = self._dry_cycles.pop(ams_id, None) or {"peak": previous, "start_seen": False, "target": None}
  4047. if self.on_drying_cycle_end:
  4048. self.on_drying_cycle_end(self._drying_cycle_end(ams_id, previous, cycle))
  4049. # Create a hash of relevant AMS data to detect changes.
  4050. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  4051. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  4052. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  4053. # above but leaves the raw payload's tracked fields untouched — so a
  4054. # raw-based hash never flips and on_ams_change never fires, leaving the
  4055. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  4056. # always spans every unit, so a partial single-unit update can't produce a
  4057. # spuriously different hash from a full pushall.
  4058. ams_hash_data = []
  4059. for ams_unit in merged_ams:
  4060. for tray in ams_unit.get("tray", []):
  4061. # Include fields that matter for filament tracking
  4062. ams_hash_data.append(
  4063. f"{ams_unit.get('id')}:{tray.get('id')}:"
  4064. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  4065. )
  4066. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  4067. # Only trigger callback if AMS data actually changed
  4068. if ams_hash != self._previous_ams_hash:
  4069. self._previous_ams_hash = ams_hash
  4070. if self.on_ams_change:
  4071. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  4072. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  4073. # may lack fields like 'remain' that the merged state preserves
  4074. self.on_ams_change(merged_ams)
  4075. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  4076. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  4077. # or cali_idx — so an assignment that only swaps the filament id on an
  4078. # already-loaded slot would not flip the hash, and gating the check on
  4079. # it would miss exactly the confirmation we are after.
  4080. if self._pending_assignments:
  4081. self._check_assignment_verifications()
  4082. @staticmethod
  4083. def _drying_cycle_end(ams_id: int, remaining: int, cycle: dict[str, object]) -> DryingCycleEnd:
  4084. """Build the cycle-end report from the record kept while it ran."""
  4085. target = cycle.get("target")
  4086. target_temp: int | None = None
  4087. target_hours: int | None = None
  4088. if isinstance(target, dict):
  4089. try:
  4090. target_temp = int(target.get("temp") or 0) or None
  4091. target_hours = int(target.get("duration_hours") or 0) or None
  4092. except (TypeError, ValueError):
  4093. target_temp = target_hours = None
  4094. return DryingCycleEnd(
  4095. ams_id=ams_id,
  4096. remaining_minutes=remaining,
  4097. peak_minutes=max(int(cycle.get("peak") or 0), remaining),
  4098. start_seen=bool(cycle.get("start_seen")),
  4099. target_temp=target_temp,
  4100. target_hours=target_hours,
  4101. )
  4102. def _log_drying_cycle_end(
  4103. self,
  4104. ams_id: int,
  4105. remaining: int,
  4106. ams_unit: dict,
  4107. target: dict[str, object] | None,
  4108. ) -> None:
  4109. """Report a finished drying cycle, with the firmware's reason when it was
  4110. cut short (#2770).
  4111. A cycle that reaches its configured duration needs no explanation and
  4112. keeps the one-line "drying complete" it has always had. One that ends
  4113. with most of its countdown left was ended by somebody, and there are
  4114. only two candidates: a stop Bambuddy sent — the print-takes-priority
  4115. stop, or the user's Stop button — which is named as such, or the
  4116. firmware.
  4117. For the firmware case the only account of why lives in fields we already
  4118. parse but have never written down: the ``dry_status`` /
  4119. ``dry_sub_status`` phase from the info hex, the per-unit
  4120. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  4121. that moment. Logging them at INFO puts them in every support bundle by
  4122. default, which is what a report like #2770 needs before its cause can be
  4123. argued about at all.
  4124. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  4125. logged for every cycle, early or not, because they are what decides
  4126. whether auto-drying re-arms. Reconstructing them for #2770 meant
  4127. cross-referencing hourly alarm lines against 30-second scheduler debug
  4128. that was switched off at the time; one line here says it outright — a
  4129. cycle ending at 63 degC with the reading still above the threshold is
  4130. the whole shape of the re-arm loop.
  4131. """
  4132. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  4133. if ams_id in self._drying_stops_sent:
  4134. self._drying_stops_sent.discard(ams_id)
  4135. logger.info(
  4136. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  4137. self.serial_number,
  4138. ams_id,
  4139. remaining,
  4140. box,
  4141. )
  4142. return
  4143. if remaining <= _EARLY_DRY_END_MINUTES:
  4144. logger.info(
  4145. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  4146. self.serial_number,
  4147. ams_id,
  4148. remaining,
  4149. box,
  4150. )
  4151. return
  4152. requested_minutes: int | None = None
  4153. if target is not None:
  4154. try:
  4155. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  4156. except (TypeError, ValueError):
  4157. requested_minutes = None
  4158. logger.info(
  4159. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  4160. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  4161. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  4162. self.serial_number,
  4163. ams_id,
  4164. remaining,
  4165. requested_minutes if requested_minutes is not None else "?",
  4166. ams_unit.get("dry_status"),
  4167. ams_unit.get("dry_sub_status"),
  4168. ams_unit.get("dry_sf_reason") or [],
  4169. [e.full_code for e in self.state.hms_errors] or "none",
  4170. box,
  4171. )
  4172. def register_assignment_verification(
  4173. self,
  4174. ams_id: int,
  4175. tray_id: int,
  4176. tray_info_idx: str,
  4177. tray_color: str,
  4178. cali_idx: int | None,
  4179. ) -> None:
  4180. """Record an assignment we just pushed so subsequent AMS telemetry can
  4181. confirm the tray actually accepted it (#2582).
  4182. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  4183. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  4184. accepted filament id back in the per-tray push, so a match means the
  4185. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  4186. signal so we can specifically flag "filament loaded but K-profile not
  4187. applied", which is the exact symptom the reporter chased via flow-cal.
  4188. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  4189. there is nothing to verify and no record is stored.
  4190. """
  4191. want_idx = (tray_info_idx or "").strip().upper()
  4192. if not want_idx:
  4193. return
  4194. self._pending_assignments[(ams_id, tray_id)] = {
  4195. "tray_info_idx": want_idx,
  4196. "tray_color": (tray_color or "").strip().upper(),
  4197. "cali_idx": cali_idx,
  4198. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  4199. "last_seen_idx": None,
  4200. }
  4201. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  4202. """Locate the live tray dict for a pending verification.
  4203. External spools (ams_id 255) live in ``vt_tray`` under global ids
  4204. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  4205. report a single tray whose id may not equal the logical tray_id, so fall
  4206. back to the sole tray when an id match fails.
  4207. """
  4208. raw = self.state.raw_data or {}
  4209. if ams_id == 255:
  4210. want_ext = external_tray_id(tray_id)
  4211. for vt in raw.get("vt_tray", []) or []:
  4212. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  4213. return vt
  4214. return None
  4215. for unit in raw.get("ams", []) or []:
  4216. if str(unit.get("id")) != str(ams_id):
  4217. continue
  4218. trays = unit.get("tray", []) or []
  4219. for tray in trays:
  4220. if str(tray.get("id")) == str(tray_id):
  4221. return tray
  4222. if ams_id >= 128 and len(trays) == 1:
  4223. return trays[0]
  4224. return None
  4225. return None
  4226. def _check_assignment_verifications(self) -> None:
  4227. """Compare each pending assignment against live tray telemetry and fire
  4228. ``on_assignment_verified`` on a match or once the deadline passes.
  4229. Runs on every AMS push. Non-matching-but-still-within-window entries are
  4230. left in place for the next push. The timeout branch only fires when a
  4231. later push arrives after the deadline; if the printer goes silent we
  4232. simply never confirm, which is preferable to inventing a failure.
  4233. """
  4234. now = time.monotonic()
  4235. for key, want in list(self._pending_assignments.items()):
  4236. ams_id, tray_id = key
  4237. tray = self._find_verify_tray(ams_id, tray_id)
  4238. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  4239. if tray is not None and actual_idx:
  4240. want["last_seen_idx"] = actual_idx
  4241. if actual_idx and actual_idx == want["tray_info_idx"]:
  4242. self._pending_assignments.pop(key, None)
  4243. kprofile_applied = True
  4244. want_cali = want.get("cali_idx")
  4245. if want_cali is not None and want_cali >= 0:
  4246. actual_cali = tray.get("cali_idx")
  4247. kprofile_applied = actual_cali == want_cali
  4248. self._fire_assignment_verified(
  4249. ams_id,
  4250. tray_id,
  4251. True,
  4252. {
  4253. "tray_info_idx": actual_idx,
  4254. "kprofile_applied": kprofile_applied,
  4255. },
  4256. )
  4257. elif now >= want["deadline"]:
  4258. self._pending_assignments.pop(key, None)
  4259. self._fire_assignment_verified(
  4260. ams_id,
  4261. tray_id,
  4262. False,
  4263. {
  4264. "expected_tray_info_idx": want["tray_info_idx"],
  4265. "actual_tray_info_idx": want.get("last_seen_idx"),
  4266. # True when we saw the tray at least once (so the push
  4267. # channel is alive and the printer really stored a
  4268. # different/blank id) vs never observing it at all.
  4269. "saw_tray": want.get("last_seen_idx") is not None,
  4270. },
  4271. )
  4272. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  4273. if verified:
  4274. logger.info(
  4275. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  4276. self.serial_number,
  4277. ams_id,
  4278. tray_id,
  4279. detail.get("tray_info_idx"),
  4280. detail.get("kprofile_applied"),
  4281. )
  4282. else:
  4283. logger.warning(
  4284. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  4285. self.serial_number,
  4286. ams_id,
  4287. tray_id,
  4288. detail.get("expected_tray_info_idx"),
  4289. detail.get("actual_tray_info_idx"),
  4290. detail.get("saw_tray"),
  4291. )
  4292. if self.on_assignment_verified:
  4293. try:
  4294. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  4295. except Exception:
  4296. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  4297. @staticmethod
  4298. def _probe_number(value, fallback: float | None = None) -> float | None:
  4299. """Coerce a telemetry field to a number, or return `fallback`.
  4300. Firmware is inconsistent about whether these arrive as ints or as
  4301. numeric strings, and the probe must never raise on a surprise type.
  4302. """
  4303. try:
  4304. return float(value)
  4305. except (TypeError, ValueError):
  4306. return fallback
  4307. def _probe_end_of_print(self, data: dict) -> None:
  4308. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  4309. Opens on the first frame that looks like end-of-print (last object
  4310. layer reached, progress at 99+, or no remaining time), then logs each
  4311. frame in which any probed field changed, and closes on the transition
  4312. out of RUNNING. Armed once per print — see the module-level comment on
  4313. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  4314. currently see into.
  4315. Read-only with respect to printer state: this is instrumentation, and
  4316. nothing downstream may come to depend on it.
  4317. """
  4318. if not logger.isEnabledFor(logging.DEBUG):
  4319. return
  4320. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  4321. return
  4322. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  4323. if not present:
  4324. return
  4325. if not self._eop_probe_open:
  4326. # Open on any end-of-print signal. Read from the raw frame first so
  4327. # the frame that *carries* the signal is itself captured — state
  4328. # fields are only updated further down this same call.
  4329. frame_layer = data.get("layer_num")
  4330. if self._is_stale_layer(frame_layer):
  4331. frame_layer = None
  4332. layer = self._probe_number(frame_layer, self.state.layer_num) or 0
  4333. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  4334. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  4335. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  4336. at_last_layer = total > 0 and layer >= total
  4337. # `remaining <= 0` is only meaningful once the print has actually
  4338. # progressed — it reads 0 during the pre-print calibration too.
  4339. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  4340. if not (at_last_layer or percent >= 99 or out_of_time):
  4341. return
  4342. self._eop_probe_open = True
  4343. self._eop_probe_frames = 0
  4344. self._eop_probe_last = {}
  4345. logger.debug(
  4346. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  4347. self.serial_number,
  4348. layer,
  4349. total,
  4350. percent,
  4351. remaining,
  4352. )
  4353. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  4354. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  4355. self._eop_probe_last.update(present)
  4356. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  4357. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  4358. self._eop_probe_frames += 1
  4359. logger.debug(
  4360. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  4361. self.serial_number,
  4362. _END_OF_PRINT_PROBE_MAX_FRAMES,
  4363. )
  4364. return
  4365. if changed or closing:
  4366. self._eop_probe_frames += 1
  4367. logger.debug(
  4368. "[%s] EOP-PROBE %s%s: %s",
  4369. self.serial_number,
  4370. self._eop_probe_frames,
  4371. " CLOSE" if closing else "",
  4372. # `changed` on a closing frame can be empty; fall back to the
  4373. # full picture so the last line is always self-contained.
  4374. changed if changed else present,
  4375. )
  4376. if closing:
  4377. self._eop_probe_open = False
  4378. self._eop_probe_armed = False
  4379. self._eop_probe_last = {}
  4380. @property
  4381. def layer_before_new_print(self) -> int:
  4382. """The layer the printer was on when a print start was detected, until
  4383. it reports another (#3317); 0 when none.
  4384. For a print that is resumed rather than new, which a restart while it
  4385. was paused makes look new, that is the layer it is still on (#2984).
  4386. """
  4387. return self._stale_layer_num
  4388. def _is_stale_layer(self, value) -> bool:
  4389. """Whether a frame's `layer_num` is the previous print's last layer (#3317)."""
  4390. if not self._stale_layer_num:
  4391. return False
  4392. try:
  4393. return int(value) == self._stale_layer_num
  4394. except (TypeError, ValueError):
  4395. return False
  4396. def _apply_nozzle_temp(self, temps: dict, temp_val) -> None:
  4397. """Set ``nozzle`` / ``nozzle_target`` / ``nozzle_heating`` from an extruder's ``temp``.
  4398. H2D protocol: temp field encoding depends on value
  4399. - When > 500: encoded as (target * 65536 + current) - heater is ON
  4400. - When < 500: direct Celsius current temp only - heater is OFF
  4401. """
  4402. # Check if we recently set the target locally (within 5 seconds)
  4403. # If so, don't let MQTT data overwrite it
  4404. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4405. respect_local_target = (time.time() - local_set_time) < 5.0
  4406. if temp_val > 500:
  4407. # Encoded format: temp = target * 65536 + current
  4408. target = temp_val // 65536
  4409. current = temp_val % 65536
  4410. if 0 < target < 500 and not respect_local_target:
  4411. temps["nozzle_target"] = float(target)
  4412. if -50 < current < 500:
  4413. temps["nozzle"] = float(current)
  4414. # Heating = encoded AND we're using the MQTT target (not local override)
  4415. # If local target is being respected, use local target to determine heating
  4416. if respect_local_target:
  4417. local_target = self.state.temperatures.get("nozzle_target", 0)
  4418. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4419. else:
  4420. temps["nozzle_heating"] = target > 0 and current < target
  4421. elif -50 < temp_val < 500:
  4422. # Direct Celsius = heater is OFF (or at target with heater off)
  4423. temps["nozzle"] = float(temp_val)
  4424. if not respect_local_target:
  4425. temps["nozzle_target"] = 0.0
  4426. temps["nozzle_heating"] = False # Direct = not heating
  4427. def _update_state(self, data: dict):
  4428. """Update printer state from message data."""
  4429. _previous_state = self.state.state
  4430. # #2547: instrumentation only — runs before any state mutation so the
  4431. # frame carrying an end-of-print signal is logged as it arrived.
  4432. try:
  4433. self._probe_end_of_print(data)
  4434. except Exception: # pragma: no cover - a probe must never break ingest
  4435. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  4436. # Update state fields
  4437. if "gcode_state" in data:
  4438. self.state.state = data["gcode_state"]
  4439. if "gcode_file" in data:
  4440. self.state.gcode_file = data["gcode_file"]
  4441. self.state.current_print = data["gcode_file"]
  4442. # The answer to a print start the printer refused names the job it
  4443. # refused, not one it runs: read as status, its job id told the start
  4444. # watchdog the file had landed.
  4445. refused_start = (
  4446. data.get("command") == "project_file"
  4447. and data.get("result") is not None
  4448. and str(data["result"]).upper() != "SUCCESS"
  4449. )
  4450. if "subtask_name" in data and not refused_start:
  4451. self.state.subtask_name = data["subtask_name"]
  4452. # Prefer subtask_name as current_print if available
  4453. if data["subtask_name"]:
  4454. self.state.current_print = data["subtask_name"]
  4455. if "subtask_id" in data and not refused_start:
  4456. self.state.subtask_id = data["subtask_id"]
  4457. if "mc_percent" in data:
  4458. # Billing: retain this frame's latest positive value immediately.
  4459. # A display-side abort may be the very next frame (and may omit
  4460. # mc_percent entirely), so retaining only the previous frame can
  4461. # lose the only usable estimate for proportional charging.
  4462. previous_progress = self.state.progress
  4463. new_progress = float(data["mc_percent"])
  4464. if new_progress > 0:
  4465. self._last_valid_progress = new_progress
  4466. self.state.progress = new_progress
  4467. # #2547: strictly-increasing only. The firmware resets progress to 0
  4468. # on cancel and re-reports the same percent on most frames; neither
  4469. # is the print advancing, and both would make the frame bank grab a
  4470. # camera frame for nothing.
  4471. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  4472. self.on_print_progress(int(self.state.progress))
  4473. if "mc_remaining_time" in data:
  4474. self.state.remaining_time = int(data["mc_remaining_time"])
  4475. if "mc_print_sub_stage" in data:
  4476. new_sub_stage = int(data["mc_print_sub_stage"])
  4477. if new_sub_stage != self.state.mc_print_sub_stage:
  4478. logger.debug(
  4479. f"[{self.serial_number}] mc_print_sub_stage changed: "
  4480. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  4481. )
  4482. self.state.mc_print_sub_stage = new_sub_stage
  4483. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  4484. # front because three places below consult it and they run in an order
  4485. # that is not the order they read most naturally in: the layer-advance
  4486. # refresh (#2702) must not fire on a frame that already answers it, the
  4487. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  4488. # reset must not discard a total that belongs to the starting print.
  4489. total_from_this_frame = 0
  4490. if "total_layer_num" in data:
  4491. try:
  4492. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  4493. except (TypeError, ValueError):
  4494. # Must not escape. `_on_message` catches only JSONDecodeError
  4495. # and paho is left at `suppress_exceptions = False`, so an
  4496. # exception raised here is re-raised on the network thread and
  4497. # takes the printer connection down over one unusable field.
  4498. # Treat it as "not reported": the refresh below then recovers
  4499. # the real total from a pushall.
  4500. logger.debug(
  4501. "[%s] ignoring unusable total_layer_num: %r",
  4502. self.serial_number,
  4503. data["total_layer_num"],
  4504. )
  4505. if "layer_num" in data:
  4506. try:
  4507. new_layer = int(data["layer_num"])
  4508. except (TypeError, ValueError):
  4509. # Contained for the same reason as `total_layer_num` above: an
  4510. # exception raised here escapes `_update_state` and paho
  4511. # re-raises it on the network thread. Losing this frame would
  4512. # also lose the print-start and completion detection further
  4513. # down, which is worse than losing a layer number.
  4514. #
  4515. # Held at the last known layer rather than substituted with 0:
  4516. # a fabricated 0 reads as the firmware's cancel reset, which
  4517. # would move `_last_valid_layer_num` and show layer 0 in the UI
  4518. # until the next good frame.
  4519. logger.debug(
  4520. "[%s] ignoring unusable layer_num: %r",
  4521. self.serial_number,
  4522. data["layer_num"],
  4523. )
  4524. new_layer = self.state.layer_num
  4525. if self._is_stale_layer(new_layer):
  4526. logger.debug(
  4527. "[%s] ignoring layer_num %s: last layer of the previous print",
  4528. self.serial_number,
  4529. new_layer,
  4530. )
  4531. new_layer = self.state.layer_num
  4532. elif new_layer > 0:
  4533. # The new print reports a layer of its own; from here on the
  4534. # previous print's value is a layer this print can reach.
  4535. self._stale_layer_num = 0
  4536. old_layer = self.state.layer_num
  4537. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  4538. if old_layer > 0:
  4539. self._last_valid_layer_num = old_layer
  4540. self.state.layer_num = new_layer
  4541. # Trigger layer change callback if layer increased
  4542. if new_layer > old_layer and self.on_layer_change:
  4543. self.on_layer_change(new_layer)
  4544. # #2702: the print is demonstrably laying down layers but we still
  4545. # have no denominator, so the pushall requested at print start
  4546. # either went unanswered or raced the printer learning the total.
  4547. # Ask once more — by layer 1 the printer definitely knows it.
  4548. # One-shot: an unanswered pushall must not turn into a per-layer
  4549. # retry loop for the rest of the print.
  4550. if (
  4551. new_layer > old_layer
  4552. and self._total_layers_refresh_armed
  4553. and not self.state.total_layers
  4554. and not total_from_this_frame
  4555. ):
  4556. self._total_layers_refresh_armed = False
  4557. logger.debug(
  4558. "[%s] layer %s with no total_layer_num — re-requesting full status",
  4559. self.serial_number,
  4560. new_layer,
  4561. )
  4562. self._request_push_all()
  4563. # #2547: there is deliberately NO finish-photo trigger on the
  4564. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  4565. # moment the printer *starts* the final layer, not the moment it
  4566. # finishes it — on the H2C capture that closed #2547 the edge
  4567. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  4568. # filament change before the print actually ended, so the photo
  4569. # showed the toolhead mid-print over the part. Worse, the trigger
  4570. # latched `_finish_photo_captured`, locking out both the stage-22
  4571. # and FINISH triggers below for the rest of the print.
  4572. #
  4573. # #1867 (End G-code ejects the plate before FINISH) is handled
  4574. # where it belongs instead: `on_finish_photo_moment` prefers the
  4575. # in-print frame bank when the dispatcher recorded that it injected
  4576. # End G-code into this print. See services/print_dispatch_context.
  4577. if total_from_this_frame:
  4578. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  4579. # end — same shape as the `layer_num` reset guarded above. Applying
  4580. # only positive values preserves the last known good denominator so
  4581. # the usage-tracker split path (#1771) survives the reset frame.
  4582. self.state.total_layers = total_from_this_frame
  4583. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  4584. # Convert to 0-100 percentage for display
  4585. def parse_fan_speed(value: str | int | None) -> int | None:
  4586. if value is None:
  4587. return None
  4588. try:
  4589. speed = int(value)
  4590. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  4591. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  4592. if speed <= 15:
  4593. return round(speed * 100 / 15)
  4594. # If already a percentage (0-255 scale from some printers), convert
  4595. elif speed <= 255:
  4596. return round(speed * 100 / 255)
  4597. return speed
  4598. except (ValueError, TypeError):
  4599. return None
  4600. # Log fan fields once for debugging
  4601. if not hasattr(self, "_fan_fields_logged"):
  4602. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  4603. if fan_fields:
  4604. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  4605. self._fan_fields_logged = True
  4606. if "cooling_fan_speed" in data:
  4607. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  4608. if "big_fan1_speed" in data:
  4609. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  4610. if "big_fan2_speed" in data:
  4611. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  4612. if "heatbreak_fan_speed" in data:
  4613. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  4614. # Calibration stage tracking
  4615. if "stg_cur" in data:
  4616. new_stg = data["stg_cur"]
  4617. prev_stg = self.state.stg_cur
  4618. # Always log ANY stg_cur change for debugging filament operations
  4619. if new_stg != prev_stg:
  4620. logger.debug(
  4621. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  4622. )
  4623. # A stage we cannot name is the one worth seeing at the default
  4624. # log level: the DEBUG line above is off in normal running, so
  4625. # an unnamed stage otherwise reaches the user as "Unknown stage
  4626. # (72)" on a card with nothing behind it to say when it
  4627. # happened or what the printer was doing. Recorded once per
  4628. # stage number per session, with the stage it came from and the
  4629. # print state, which is what naming it later needs. Guarded on
  4630. # the int type because the field is whatever the firmware sent.
  4631. if (
  4632. isinstance(new_stg, int)
  4633. and not isinstance(new_stg, bool)
  4634. # -1 is Bambuddy's own "not in a stage" sentinel and the
  4635. # initial value of the field, not something the firmware
  4636. # reports; every print would otherwise report it on the way
  4637. # out of its last real stage.
  4638. and new_stg != -1
  4639. and new_stg not in STAGE_NAMES
  4640. and new_stg not in self._unnamed_stages_seen
  4641. ):
  4642. self._unnamed_stages_seen.add(new_stg)
  4643. logger.info(
  4644. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  4645. "state=%s progress=%s%% layer=%s/%s",
  4646. self.serial_number,
  4647. new_stg,
  4648. self.model,
  4649. prev_stg,
  4650. get_stage_name(prev_stg),
  4651. self.state.state,
  4652. self.state.progress,
  4653. self.state.layer_num,
  4654. self.state.total_layers,
  4655. )
  4656. self.state.stg_cur = new_stg
  4657. # #1721 end-of-print finish photo trigger.
  4658. # Stage 22 = "Filament unloading" fires at end-of-print AND
  4659. # during mid-print color swaps. The end-of-print gate
  4660. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  4661. # — those signals only line up at the real end. Edge-only
  4662. # (prev != 22) so the trigger fires once per stage entry.
  4663. if (
  4664. new_stg == 22
  4665. and prev_stg != 22
  4666. and self._was_running
  4667. and not self._finish_photo_captured
  4668. and self.on_finish_photo_moment
  4669. ):
  4670. progress = self.state.progress or 0.0
  4671. layer_num = self.state.layer_num or 0
  4672. total_layers = self.state.total_layers or 0
  4673. remaining = self.state.remaining_time or 0
  4674. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  4675. if is_end_of_print:
  4676. self._finish_photo_captured = True
  4677. logger.info(
  4678. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  4679. f"progress={progress}, layer={layer_num}/{total_layers}, "
  4680. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  4681. )
  4682. self.on_finish_photo_moment(
  4683. {
  4684. "trigger": "stage_22",
  4685. "filename": self._previous_gcode_file or self.state.gcode_file,
  4686. "subtask_name": self.state.subtask_name,
  4687. "timelapse_was_active": self._timelapse_during_print,
  4688. }
  4689. )
  4690. if "stg" in data:
  4691. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  4692. # Temperature data
  4693. temps = {}
  4694. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  4695. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  4696. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  4697. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  4698. # Log ALL keys in print data for H2D temperature discovery
  4699. all_keys = sorted(data.keys())
  4700. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  4701. self._temp_fields_logged = True
  4702. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  4703. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  4704. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  4705. self._vir_slot_logged = True
  4706. # Log nozzle hardware info fields (once)
  4707. nozzle_fields = {
  4708. k: v
  4709. for k, v in data.items()
  4710. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  4711. }
  4712. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  4713. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  4714. self._nozzle_fields_logged = True
  4715. # Parse active extruder from device.extruder.state bit 8
  4716. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  4717. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  4718. if "device" in data and isinstance(data.get("device"), dict):
  4719. device = data["device"]
  4720. # One-shot identification probe: surface whatever the firmware uses to
  4721. # name itself so an unknown model in a support bundle becomes self-
  4722. # diagnosing. INFO level so it shows up without debug logging. Falls
  4723. # back to dumping device.keys() if none of the known fields are present
  4724. # (so a future Bambu rename like `model_name` is still observable).
  4725. if not getattr(self, "_device_id_logged", False):
  4726. id_fields = {
  4727. k: device.get(k)
  4728. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  4729. if k in device
  4730. }
  4731. if id_fields:
  4732. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  4733. else:
  4734. logger.info(
  4735. "[%s] Device identification: no known id fields; device.keys=%s",
  4736. self.serial_number,
  4737. sorted(device.keys()),
  4738. )
  4739. self._device_id_logged = True
  4740. self._parse_extruder_position(data)
  4741. # Log device.extruder structure for active extruder
  4742. if "device" in data and isinstance(data.get("device"), dict):
  4743. device = data["device"]
  4744. if "extruder" in device:
  4745. ext_data = device["extruder"]
  4746. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4747. if "state" in ext_data:
  4748. state_val = ext_data["state"]
  4749. # Extract bits 12-14 (3 bits) for switch state
  4750. switch_state = (state_val >> 12) & 0x7
  4751. self._debug_on_change(
  4752. "extruder_state",
  4753. state_val,
  4754. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4755. self.serial_number,
  4756. state_val,
  4757. switch_state,
  4758. )
  4759. # Log 'cur' field if present (might indicate current/active extruder)
  4760. if "cur" in ext_data:
  4761. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4762. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4763. # it first. Repeated here so _update_state stays a complete "absorb this
  4764. # payload" step for any other caller; re-parsing the same block is free.
  4765. self._parse_fila_switch(data)
  4766. self._parse_extruder_slots(data)
  4767. if "bed_temper" in data:
  4768. temps["bed"] = float(data["bed_temper"])
  4769. if "bed_target_temper" in data:
  4770. temps["bed_target"] = float(data["bed_target_temper"])
  4771. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4772. has_h2d_extruder_info = (
  4773. "device" in data
  4774. and isinstance(data.get("device"), dict)
  4775. and "extruder" in data["device"]
  4776. and isinstance(data["device"]["extruder"].get("info"), list)
  4777. and len(data["device"]["extruder"]["info"]) >= 2
  4778. )
  4779. # A rack printer (H3C, #3442) swaps hotends on its one extruder, and
  4780. # nozzle_temper keeps reporting the one just put back in the rack. The
  4781. # mounted one's temperature is in device.extruder.info, which Bambu
  4782. # Studio reads over nozzle_temper too (DevExtruderSystem ParseV2_0).
  4783. # The layout knows an H3C by its model before any AMS data came.
  4784. mounted_tool_temp = self.tray_layout.rack
  4785. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4786. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4787. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4788. if "nozzle_temper" in data and not mounted_tool_temp:
  4789. if has_h2d_extruder_info:
  4790. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4791. else:
  4792. temps["nozzle"] = float(data["nozzle_temper"])
  4793. if "nozzle_target_temper" in data and not mounted_tool_temp:
  4794. if has_h2d_extruder_info:
  4795. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4796. else:
  4797. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4798. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4799. if not has_h2d_extruder_info:
  4800. # Try multiple possible field names used by different firmware versions
  4801. if "nozzle_temper_2" in data:
  4802. val = float(data["nozzle_temper_2"])
  4803. if -50 < val < 500: # Valid temp range
  4804. temps["nozzle_2"] = val
  4805. else:
  4806. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4807. elif "right_nozzle_temper" in data:
  4808. val = float(data["right_nozzle_temper"])
  4809. if -50 < val < 500: # Valid temp range
  4810. temps["nozzle_2"] = val
  4811. else:
  4812. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4813. if "nozzle_target_temper_2" in data:
  4814. val = float(data["nozzle_target_temper_2"])
  4815. if 0 <= val < 500: # Valid temp range
  4816. temps["nozzle_2_target"] = val
  4817. else:
  4818. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4819. elif "right_nozzle_target_temper" in data:
  4820. val = float(data["right_nozzle_target_temper"])
  4821. if 0 <= val < 500: # Valid temp range
  4822. temps["nozzle_2_target"] = val
  4823. else:
  4824. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4825. # Also check for left nozzle as primary (some H2 models)
  4826. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4827. temps["nozzle"] = float(data["left_nozzle_temper"])
  4828. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4829. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4830. if "chamber_temper" in data:
  4831. chamber_val = float(data["chamber_temper"])
  4832. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4833. # Check if we recently set the target locally (within 5 seconds)
  4834. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4835. respect_local = (time.time() - local_set_time) < 5.0
  4836. # H2D protocol: chamber_temper encoding indicates heater state
  4837. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4838. # - When < 500: direct Celsius current temp only - heater is OFF
  4839. if -50 < chamber_val < 100:
  4840. # Direct value = heater is OFF
  4841. temps["chamber"] = chamber_val
  4842. if not respect_local:
  4843. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4844. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4845. else:
  4846. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4847. # Try to decode if it looks like an encoded value
  4848. if chamber_val > 500:
  4849. mqtt_target = int(chamber_val) // 65536
  4850. current = int(chamber_val) % 65536
  4851. logger.debug(
  4852. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4853. )
  4854. if -50 < current < 100:
  4855. temps["chamber"] = float(current)
  4856. # Store decoded target for later use, but DON'T set chamber_heating here!
  4857. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4858. # which is the authoritative source the slicer uses.
  4859. if not respect_local:
  4860. if 0 <= mqtt_target <= 60:
  4861. # Store as "decoded" target - may be overridden by explicit target fields
  4862. temps["_chamber_decoded_target"] = float(mqtt_target)
  4863. # Chamber target temperature (set by print file or display)
  4864. if "mc_target_cham" in data:
  4865. mc_target = float(data["mc_target_cham"])
  4866. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4867. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4868. if 0 <= mc_target <= 60:
  4869. temps["chamber_target"] = mc_target
  4870. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4871. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4872. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4873. try:
  4874. if "info" in data and isinstance(data["info"], dict):
  4875. info_temp = data["info"].get("temp")
  4876. if info_temp is not None and "chamber" not in temps:
  4877. # Check for encoded value (target * 65536 + current)
  4878. if info_temp > 500:
  4879. # Decode: extract current temperature and target
  4880. target = info_temp // 65536
  4881. current = info_temp % 65536
  4882. temps["chamber"] = float(current)
  4883. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4884. if "_chamber_decoded_target" not in temps:
  4885. temps["_chamber_decoded_target"] = float(target)
  4886. logger.debug(
  4887. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4888. )
  4889. elif -50 < info_temp < 100:
  4890. # Valid direct temperature - heater is OFF
  4891. temps["chamber"] = float(info_temp)
  4892. temps["chamber_target"] = 0.0 # Direct value means heater off
  4893. self._debug_on_change(
  4894. "info_temp_direct",
  4895. info_temp,
  4896. "[%s] info.temp direct: %s°C (heater OFF)",
  4897. self.serial_number,
  4898. info_temp,
  4899. )
  4900. # H2D series: Dual extruder temps are in device.extruder.info array
  4901. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4902. if "device" in data and isinstance(data["device"], dict):
  4903. device = data["device"]
  4904. # Parse dual extruder temperatures
  4905. extruder_data = device.get("extruder", {})
  4906. extruder_info = extruder_data.get("info", [])
  4907. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4908. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4909. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4910. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4911. if has_h2d_extruder_info:
  4912. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4913. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4914. if "temp" in extruder_info[0]:
  4915. temp_val = extruder_info[0]["temp"]
  4916. if temp_val > 500:
  4917. # Encoded format: temp = target * 65536 + current
  4918. target = temp_val // 65536
  4919. current = temp_val % 65536
  4920. if -50 < current < 500:
  4921. temps["nozzle_2"] = float(current)
  4922. if 0 < target < 500:
  4923. temps["nozzle_2_target"] = float(target)
  4924. temps["nozzle_2_heating"] = target > 0 and current < target
  4925. elif -50 < temp_val < 500:
  4926. # Direct Celsius value = heater is OFF
  4927. temps["nozzle_2"] = float(temp_val)
  4928. temps["nozzle_2_target"] = 0.0
  4929. temps["nozzle_2_heating"] = False
  4930. # Left nozzle (extruder 1) - only for dual nozzle printers
  4931. # H2D protocol: temp field encoding depends on value
  4932. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4933. # - When < 500: direct Celsius current temp only - heater is OFF
  4934. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4935. self._apply_nozzle_temp(temps, extruder_info[1]["temp"])
  4936. # The H3C's one extruder: the hotend mounted on it (#3442).
  4937. elif mounted_tool_temp and "temp" in extruder_info[0]:
  4938. self._apply_nozzle_temp(temps, extruder_info[0]["temp"])
  4939. # The extruder snow is read by _parse_extruder_position, before the
  4940. # AMS block of the same frame (tray_now resolution needs it first).
  4941. # Parse bed heating state from device.bed.info.temp encoding
  4942. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4943. bed_data = device.get("bed", {})
  4944. bed_info = bed_data.get("info", {})
  4945. if "temp" in bed_info:
  4946. temp_val = bed_info["temp"]
  4947. if temp_val > 500:
  4948. target = temp_val // 65536
  4949. current = temp_val % 65536
  4950. temps["bed_heating"] = target > 0 and current < target
  4951. else:
  4952. temps["bed_heating"] = False
  4953. # Parse chamber temp from device.ctc.info.temp if not already set
  4954. ctc_data = device.get("ctc", {})
  4955. ctc_info = ctc_data.get("info", {})
  4956. # Parse airduct mode (0=cooling, 1=heating)
  4957. airduct_data = device.get("airduct", {})
  4958. if "modeCur" in airduct_data:
  4959. new_mode = airduct_data["modeCur"]
  4960. if new_mode != self.state.airduct_mode:
  4961. logger.debug(
  4962. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4963. )
  4964. self.state.airduct_mode = new_mode
  4965. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4966. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4967. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4968. # AIR_FUN enum: 1=part cooling, 2=aux, 3=chamber/exhaust,
  4969. # 10=second aux (FAN_REMOTE_COOLING_1). Aux 2 is the right fan and
  4970. # 10 the left on the P2S, the other way round on the X2D (#3373;
  4971. # Bambu Studio's N7.json / N6.json). The airduct `parts` list only
  4972. # contains the fans that physically exist, so it doubles as a
  4973. # presence signal for the two P2S/X2D add-on kits:
  4974. # - id 10 (second auxiliary part cooling fan) — reported ONLY here,
  4975. # never mirrored into a flat big_fanX_speed field.
  4976. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4977. # big_fan2_speed, but the part is only listed when the External
  4978. # Exhaust Fan kit (get_version module "eef") is installed.
  4979. # `state` is already a 0-100 percentage.
  4980. parts = airduct_data.get("parts")
  4981. if isinstance(parts, list):
  4982. speeds: dict[int, int] = {}
  4983. for part in parts:
  4984. if not isinstance(part, dict):
  4985. continue
  4986. try:
  4987. # Studio reads the id with get_flag_bits(id, 4, 8),
  4988. # so mask after shifting for the same reason `state`
  4989. # is masked below. Every id seen in the wild
  4990. # (16/32/48/160) decodes identically either way —
  4991. # this is consistency, not a live bug.
  4992. part_id = (int(part["id"]) >> 4) & 0xFF
  4993. # `state` is bit-packed like its sibling `range`
  4994. # (end << 16 | start), so take only the low 8 bits —
  4995. # the same decode Bambu Studio does with
  4996. # get_flag_bits(state, 0, 8). Without the mask a
  4997. # packed value would clamp to 100 instead of
  4998. # decoding to the real percentage.
  4999. part_state = int(part["state"]) & 0xFF
  5000. except (KeyError, ValueError, TypeError):
  5001. continue
  5002. # Ids seen across the support-package archive:
  5003. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  5004. # 6 (H2 series, unmapped), 10 second aux.
  5005. speeds[part_id] = max(0, min(100, part_state))
  5006. # Absence in this list is what tells us a kit is NOT fitted,
  5007. # so it may only be trusted when the list is a full
  5008. # inventory rather than a diff frame. `device.airduct` is
  5009. # pushed field by field — the `modeCur` handler above exists
  5010. # for exactly that reason — and a truncated `parts` read as
  5011. # gospel would retract both accessory badges mid-print and
  5012. # start rejecting `aux2` on a printer that has the fan.
  5013. #
  5014. # Every airduct layout in the support-package archive
  5015. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  5016. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  5017. # part cooling fan and the aux fan, neither of which is
  5018. # optional on any machine that reports an airduct at all.
  5019. # A list carrying both is therefore a complete inventory; a
  5020. # list missing either is a partial frame, and we take its
  5021. # speeds without touching presence.
  5022. is_full_inventory = 1 in speeds and 2 in speeds
  5023. left_aux_speed = speeds.get(10)
  5024. if left_aux_speed is None and not is_full_inventory:
  5025. # Partial frame that didn't mention the second aux fan —
  5026. # keep whatever we already knew about it.
  5027. left_aux_speed = self.state.left_aux_fan_speed
  5028. if left_aux_speed != self.state.left_aux_fan_speed:
  5029. logger.debug(
  5030. f"[{self.serial_number}] left_aux_fan_speed changed: "
  5031. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  5032. )
  5033. # A FULL parts list without id 10 means the second aux fan is
  5034. # not installed — report None so the UI can hide the widget.
  5035. self.state.left_aux_fan_speed = left_aux_speed
  5036. # id 3 present == chamber exhaust fan installed (base P2S
  5037. # omits it). Only ever retracted on a full inventory.
  5038. if 3 in speeds:
  5039. self.state.exhaust_fan_present = True
  5040. elif is_full_inventory:
  5041. self.state.exhaust_fan_present = False
  5042. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  5043. # Check if we recently set the target locally (within 5 seconds)
  5044. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  5045. respect_local_target = (time.time() - local_set_time) < 5.0
  5046. # Log ctc_info contents for debugging
  5047. if ctc_info:
  5048. self._debug_on_change(
  5049. "ctc_info_keys",
  5050. tuple(ctc_info.keys()),
  5051. "[%s] ctc_info keys: %s",
  5052. self.serial_number,
  5053. list(ctc_info.keys()),
  5054. )
  5055. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  5056. # (what the slicer shows). This OVERRIDES any previously decoded target.
  5057. explicit_target = None
  5058. if "target" in ctc_info:
  5059. target_val = ctc_info["target"]
  5060. logger.debug(
  5061. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  5062. )
  5063. # Filter out invalid values (valid chamber target is 0-60°C)
  5064. if 0 <= target_val <= 60 and not respect_local_target:
  5065. explicit_target = float(target_val)
  5066. temps["chamber_target"] = explicit_target # Override any previous value
  5067. logger.debug(
  5068. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  5069. )
  5070. # Parse chamber temp from ctc.info.temp - may be encoded
  5071. if "temp" in ctc_info and "chamber" not in temps:
  5072. temp_val = ctc_info["temp"]
  5073. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  5074. if temp_val > 500:
  5075. # Encoded value: decode target and current
  5076. decoded_target = temp_val // 65536
  5077. current = temp_val % 65536
  5078. temps["chamber"] = float(current)
  5079. logger.debug(
  5080. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  5081. )
  5082. # Determine which target to use for heating state:
  5083. # Priority: local target > explicit target > decoded target
  5084. if respect_local_target:
  5085. local_target = self.state.temperatures.get("chamber_target", 0)
  5086. temps["chamber_heating"] = local_target > 0 and current < local_target
  5087. elif explicit_target is not None:
  5088. # Use explicit ctc.info.target - this is what slicer sees
  5089. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  5090. else:
  5091. # Fallback to decoded target only if no explicit target available
  5092. if not respect_local_target and "chamber_target" not in temps:
  5093. temps["chamber_target"] = float(decoded_target)
  5094. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  5095. else:
  5096. # Direct value (not encoded) - heater is OFF
  5097. temps["chamber"] = float(temp_val)
  5098. temps["chamber_heating"] = False
  5099. except Exception as e:
  5100. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  5101. if temps:
  5102. # Handle chamber_target: prefer explicit over decoded
  5103. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  5104. # No explicit target available, use decoded target from chamber_temper
  5105. temps["chamber_target"] = temps["_chamber_decoded_target"]
  5106. # Remove internal temp key before merging
  5107. temps.pop("_chamber_decoded_target", None)
  5108. # Merge new temps into existing, preserving valid values when new ones are filtered out
  5109. for key, value in temps.items():
  5110. self.state.temperatures[key] = value
  5111. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  5112. if "bed" in temps and self.on_bed_temp_update:
  5113. self.on_bed_temp_update(temps["bed"])
  5114. # Calculate chamber_heating after all targets are known
  5115. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  5116. if "chamber" in temps and "chamber_heating" not in temps:
  5117. current = self.state.temperatures.get("chamber", 0)
  5118. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  5119. respect_local = (time.time() - local_set_time) < 5.0
  5120. if respect_local:
  5121. # Use locally-set target
  5122. target = self.state.temperatures.get("chamber_target", 0)
  5123. else:
  5124. # Use explicit/decoded target from MQTT
  5125. target = self.state.temperatures.get("chamber_target", 0)
  5126. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  5127. self._debug_on_change(
  5128. "chamber_heating",
  5129. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  5130. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  5131. self.serial_number,
  5132. target,
  5133. current,
  5134. self.state.temperatures["chamber_heating"],
  5135. respect_local,
  5136. )
  5137. # Debug: log chamber value if it was updated
  5138. if "chamber" in temps:
  5139. self._debug_on_change(
  5140. "chamber_temp",
  5141. (
  5142. self.state.temperatures.get("chamber"),
  5143. self.state.temperatures.get("chamber_target"),
  5144. self.state.temperatures.get("chamber_heating"),
  5145. ),
  5146. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  5147. self.serial_number,
  5148. self.state.temperatures.get("chamber"),
  5149. self.state.temperatures.get("chamber_target"),
  5150. self.state.temperatures.get("chamber_heating"),
  5151. )
  5152. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  5153. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  5154. if "nozzle" in temps and "nozzle_heating" not in temps:
  5155. current = self.state.temperatures.get("nozzle", 0)
  5156. target = self.state.temperatures.get("nozzle_target", 0)
  5157. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  5158. # Parse HMS (Health Management System) errors
  5159. if "hms" in data:
  5160. hms_list = data["hms"]
  5161. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  5162. # A `print_error` fault is not in `hms[]` and its field only comes
  5163. # when it changes, so a list rebuilt from `hms[]` keeps it (#3487).
  5164. print_error_entries = [e for e in self.state.hms_errors if _is_print_error_entry(e)]
  5165. self.state.hms_errors = []
  5166. verify_failed = False
  5167. if isinstance(hms_list, list):
  5168. for hms in hms_list:
  5169. if isinstance(hms, dict):
  5170. # HMS format: {"attr": attribute_code, "code": error_code}
  5171. # attr contains module/severity info, code contains error number
  5172. # Both are needed to construct the wiki URL
  5173. attr = hms.get("attr", 0)
  5174. code = hms.get("code", 0)
  5175. if isinstance(attr, str):
  5176. attr = int(attr.replace("0x", ""), 16) if attr else 0
  5177. if isinstance(code, str):
  5178. code = int(code.replace("0x", ""), 16) if code else 0
  5179. # attr is module, module no., part, part no. (a byte each);
  5180. # code is the alert level (high 16 bits) then the error
  5181. # (low 16). The level is 1 error (task stopped), 2 warning
  5182. # (task paused), 3 notification; 0 is invalid. This is how
  5183. # Bambu Studio decodes it (DevHMSItem::parse_hms_info). It
  5184. # used to be read from attr bits 8-15, which is the part
  5185. # byte (#2728).
  5186. severity = (code >> 16) & 0xFFFF
  5187. # Module is in attr byte 3 (bits 24-31)
  5188. module = (attr >> 24) & 0xFF
  5189. # Skip non-error status codes. A real fault has a level of
  5190. # at least 1 in the high half, so its code is >= 0x10000
  5191. # and clears this; lower values are status/phase
  5192. # indicators some firmware sends during normal printing.
  5193. if code < 0x4000:
  5194. continue
  5195. # Skip user-action echoes — the printer firmware emits these
  5196. # as part of normal user-cancel sequences. They're not faults
  5197. # and shouldn't count toward "X problem" badges or surface as
  5198. # red pips on the printer card. Backend's notification path
  5199. # already suppresses 0500_400E for the same reason.
  5200. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  5201. if short_code in _HMS_USER_ACTION_CODES:
  5202. continue
  5203. # The full 16-char identifier is the firmware's matching key
  5204. # and the HMS catalogue's key for this kind of fault; the
  5205. # short code discards the part and alert-level groups. The
  5206. # action table still has some short-form entries, so that
  5207. # lookup falls back to it.
  5208. full_code = f"{attr:08X}{code:08X}"
  5209. if full_code == HMS_MQTT_VERIFY_FAILED:
  5210. verify_failed = True
  5211. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  5212. if not actions:
  5213. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5214. self.state.hms_errors.append(
  5215. HMSError(
  5216. code=f"0x{code:x}" if code else "0x0",
  5217. attr=attr,
  5218. module=module,
  5219. # No fallback: 0 is Bambu's "invalid" level, and
  5220. # promoting it would render it as a fault.
  5221. severity=severity,
  5222. actions=actions,
  5223. job_id=self.state.subtask_id,
  5224. full_code=full_code,
  5225. description=describe_fault(full_code, self.serial_number[:3]),
  5226. )
  5227. )
  5228. hms_short_codes = _hms_short_codes(self.state.hms_errors)
  5229. self.state.hms_errors.extend(e for e in print_error_entries if _hms_short_code(e) not in hms_short_codes)
  5230. self._apply_mqtt_verify_state(verify_failed)
  5231. # Parse print_error - this is a different error format than HMS
  5232. # print_error is a 32-bit integer where:
  5233. # - High 16 bits contain module info (e.g., 0x0500)
  5234. # - Low 16 bits contain error code (e.g., 0x8061)
  5235. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  5236. if "print_error" in data:
  5237. print_error = data["print_error"]
  5238. # The field holds the one current fault, and 0 once it is resolved,
  5239. # for example when the filament-load prompt is answered on the
  5240. # printer. The entry of a code that is no longer reported goes
  5241. # (#3487); the entry of the same code is kept as it is.
  5242. self.state.hms_errors = [
  5243. e for e in self.state.hms_errors if not _is_print_error_entry(e) or e.attr == print_error
  5244. ]
  5245. if print_error and print_error != 0:
  5246. # Extract components: MMMMEEEE -> MMMM_EEEE
  5247. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  5248. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  5249. # Values below 0x4000 are status/phase indicators, not real errors.
  5250. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  5251. # Some firmware sends low values like 0x0002 during normal printing.
  5252. if error < 0x4000:
  5253. pass # Skip — not a real error
  5254. else:
  5255. # Store in a format that matches the community error database
  5256. # attr stores the full 32-bit value for reconstruction
  5257. # code stores the short format string for lookup
  5258. short_code = f"{module:04X}_{error:04X}"
  5259. logger.debug(
  5260. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  5261. )
  5262. # Same user-action filter as the hms[] branch above — print_error
  5263. # carries the same cancel echoes (e.g. 0500_400E) and they must
  5264. # not surface as faults on the printer card.
  5265. if short_code in _HMS_USER_ACTION_CODES:
  5266. pass # cancel echo — silently drop
  5267. else:
  5268. # Only add if not already in HMS errors (avoid duplicates)
  5269. if short_code not in _hms_short_codes(self.state.hms_errors):
  5270. # Bambu's HMS catalog keys by 3-letter device code (the SN
  5271. # prefix) and a 16-char short error code without the
  5272. # underscore separator we store internally.
  5273. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5274. # Bambu pushes the current job as `subtask_id` on the
  5275. # state stream; the HMS-action commands echo it back as
  5276. # `job_id`. The error payload itself doesn't carry the
  5277. # id, so snapshot it from the live state at parse time
  5278. # and freeze it on the HMSError so subsequent
  5279. # job changes don't invalidate the action.
  5280. job_id = self.state.subtask_id
  5281. logger.debug(
  5282. "[%s, %s] HMS available actions: %s (job_id=%s)",
  5283. self.serial_number[:3],
  5284. short_code.replace("_", ""),
  5285. actions,
  5286. job_id,
  5287. )
  5288. self.state.hms_errors.append(
  5289. HMSError(
  5290. code=f"0x{error:x}",
  5291. attr=print_error, # Store full value for display
  5292. module=module >> 8, # High byte of module (e.g., 0x05)
  5293. # print_error has no level field; its error
  5294. # number's first digit carries it instead.
  5295. severity=alert_level_from_print_error(error),
  5296. actions=actions,
  5297. job_id=job_id,
  5298. # print_error is already 32-bit — `f"{print_error:08X}"`
  5299. # is the firmware's matching key with no truncation.
  5300. full_code=f"{print_error:08X}",
  5301. description=describe_fault(f"{print_error:08X}", self.serial_number[:3]),
  5302. )
  5303. )
  5304. # Parse home_flag first so SD-card detection below can prefer it.
  5305. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  5306. # bit 23 = door-open (X1 family only).
  5307. home_flag = None
  5308. if "home_flag" in data:
  5309. home_flag = data["home_flag"]
  5310. if home_flag < 0:
  5311. home_flag = home_flag & 0xFFFFFFFF
  5312. # SD card presence: the only remaining consumer is the firmware-update
  5313. # precondition check (firmware_update.py). Use the top-level `sdcard`
  5314. # field when present with a permissive truthy check covering the
  5315. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  5316. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  5317. # when a card is inserted, which caused the badge to flap before the
  5318. # badge was removed entirely.
  5319. if "sdcard" in data:
  5320. raw_sdcard = data["sdcard"]
  5321. if isinstance(raw_sdcard, str):
  5322. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  5323. else:
  5324. self.state.sdcard = bool(raw_sdcard)
  5325. self.state.sdcard_reported = True
  5326. if home_flag is not None:
  5327. store_to_sdcard = bool((home_flag >> 11) & 1)
  5328. if store_to_sdcard != self.state.store_to_sdcard:
  5329. logger.debug(
  5330. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  5331. )
  5332. self.state.store_to_sdcard = store_to_sdcard
  5333. # Door open detection — source depends on printer family:
  5334. # X1 series (X1, X1C, X1E): home_flag bit 23
  5335. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  5336. # Both share the same bitmask (0x00800000) but live in different fields.
  5337. model_upper = (self.model or "").upper().strip()
  5338. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  5339. if is_x1_family and home_flag is not None:
  5340. door_open = (home_flag & 0x00800000) != 0
  5341. if door_open != self.state.door_open:
  5342. logger.debug(
  5343. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  5344. self.serial_number,
  5345. self.state.door_open,
  5346. door_open,
  5347. home_flag,
  5348. )
  5349. self.state.door_open = door_open
  5350. elif not is_x1_family and "stat" in data:
  5351. try:
  5352. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  5353. door_open = (stat_value & 0x00800000) != 0
  5354. if door_open != self.state.door_open:
  5355. logger.debug(
  5356. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  5357. self.serial_number,
  5358. self.state.door_open,
  5359. door_open,
  5360. stat_value,
  5361. )
  5362. self.state.door_open = door_open
  5363. except (ValueError, TypeError):
  5364. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  5365. # Parse timelapse status (recording active during print). Status frames
  5366. # only — the project_file ack echoes back the per-job timelapse flag we
  5367. # asked for, which is a request, not the recorder's state (#3040).
  5368. if "timelapse" in data and is_printer_status_frame(data):
  5369. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  5370. self.state.timelapse = data["timelapse"] is True
  5371. # Track if timelapse was ever active during this print
  5372. if self.state.timelapse and self._was_running:
  5373. self._timelapse_during_print = True
  5374. # Parse ipcam/live view status
  5375. if "ipcam" in data:
  5376. ipcam_data = data["ipcam"]
  5377. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  5378. if isinstance(ipcam_data, dict):
  5379. # Check ipcam_record field for live view status
  5380. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  5381. # Check timelapse field (H2D sends it here, not in xcam)
  5382. if "timelapse" in ipcam_data:
  5383. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  5384. if timelapse_enabled != self.state.timelapse:
  5385. logger.debug(
  5386. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  5387. )
  5388. self.state.timelapse = timelapse_enabled
  5389. # Track if timelapse was ever active during this print
  5390. if self.state.timelapse and self._was_running:
  5391. self._timelapse_during_print = True
  5392. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  5393. else:
  5394. self.state.ipcam = ipcam_data is True
  5395. # Parse WiFi signal strength (dBm)
  5396. if "wifi_signal" in data:
  5397. wifi_signal = data["wifi_signal"]
  5398. self._debug_on_change(
  5399. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  5400. )
  5401. if isinstance(wifi_signal, (int, float)):
  5402. self.state.wifi_signal = int(wifi_signal)
  5403. elif isinstance(wifi_signal, str):
  5404. # Handle string format like "-52dBm"
  5405. try:
  5406. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  5407. except ValueError:
  5408. pass # Ignore unparseable wifi_signal strings; field is non-critical
  5409. # Detect ethernet connection: printers on ethernet with WiFi disabled
  5410. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  5411. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  5412. from backend.app.utils.printer_models import has_ethernet
  5413. if has_ethernet(self.model):
  5414. self.state.wired_network = self.state.wifi_signal == -90
  5415. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5416. if "spd_lvl" in data:
  5417. new_speed = data["spd_lvl"]
  5418. if new_speed != self.state.speed_level:
  5419. logger.debug(
  5420. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  5421. )
  5422. self.state.speed_level = new_speed
  5423. # Parse skipped objects from printer status (s_obj field)
  5424. # This allows us to restore skipped objects state after reconnection
  5425. if "s_obj" in data:
  5426. s_obj = data["s_obj"]
  5427. if isinstance(s_obj, list):
  5428. # Update skipped objects from printer's list
  5429. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  5430. if new_skipped != self.state.skipped_objects:
  5431. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  5432. self.state.skipped_objects = new_skipped
  5433. for oid in new_skipped:
  5434. self._unconfirmed_skips.pop(oid, None)
  5435. self._check_unconfirmed_skips()
  5436. # Parse chamber light status from lights_report
  5437. if "lights_report" in data:
  5438. lights = data["lights_report"]
  5439. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  5440. if isinstance(lights, list):
  5441. for light in lights:
  5442. if isinstance(light, dict) and light.get("node") == "chamber_light":
  5443. new_light_state = light.get("mode") == "on"
  5444. if new_light_state != self.state.chamber_light:
  5445. logger.debug(
  5446. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  5447. )
  5448. self.state.chamber_light = new_light_state
  5449. break
  5450. # Parse nozzle hardware info (single nozzle printers)
  5451. if "nozzle_type" in data:
  5452. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  5453. if "nozzle_diameter" in data:
  5454. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  5455. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  5456. # Left nozzle
  5457. if "left_nozzle_type" in data:
  5458. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  5459. if "left_nozzle_diameter" in data:
  5460. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  5461. # Right nozzle
  5462. if "right_nozzle_type" in data:
  5463. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  5464. if "right_nozzle_diameter" in data:
  5465. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  5466. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  5467. if "nozzle_type_2" in data:
  5468. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  5469. if "nozzle_diameter_2" in data:
  5470. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  5471. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  5472. if "device" in data and isinstance(data["device"], dict):
  5473. device = data["device"]
  5474. nozzle_data = device.get("nozzle", {})
  5475. # H2C rack position (#2800). `tar_id` is where the carriage is
  5476. # headed, `src_id` where it came from; mid-swap they differ, so
  5477. # dispatch prefers tar_id and falls back to src_id. Both are
  5478. # sticky — the field is only pushed when it changes, so an
  5479. # absent key must leave the last known value alone rather than
  5480. # reset it to None.
  5481. if isinstance(nozzle_data, dict):
  5482. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  5483. if key not in nozzle_data:
  5484. continue
  5485. try:
  5486. parsed_id = int(nozzle_data[key])
  5487. except (TypeError, ValueError):
  5488. continue
  5489. if getattr(self.state, attr) != parsed_id:
  5490. setattr(self.state, attr, parsed_id)
  5491. # DEBUG, not INFO: these move on every tool change, so
  5492. # a long multi-material print would otherwise write
  5493. # thousands of lines. The dispatch log records both
  5494. # values once per print, which is where triage needs
  5495. # them. Same reasoning as the one-shot `nozzle_info`
  5496. # log below.
  5497. logger.debug(
  5498. "[%s] Nozzle rack %s -> %s",
  5499. self.serial_number,
  5500. key,
  5501. parsed_id,
  5502. )
  5503. nozzle_info = nozzle_data.get("info", [])
  5504. if isinstance(nozzle_info, list):
  5505. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  5506. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  5507. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  5508. # for hover cards on both the L/R indicator and the nozzle rack card.
  5509. if nozzle_info:
  5510. self.state.nozzle_rack = sorted(
  5511. [
  5512. {
  5513. "id": n.get("id", i),
  5514. "type": str(n.get("type", "")),
  5515. "diameter": str(n.get("diameter", "")),
  5516. "wear": n.get("wear"),
  5517. # H2C: seconds this nozzle has printed (#1908)
  5518. "print_time_s": nozzle_print_time_s(n.get("p_t")),
  5519. "stat": n.get("stat"),
  5520. # H2C uses "tm", H2D uses "max_temp"
  5521. "max_temp": n.get("max_temp") or n.get("tm", 0),
  5522. # H2C uses "sn", H2D uses "serial_number"
  5523. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  5524. # H2C uses "color_m", H2D uses "filament_colour"
  5525. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  5526. # H2C uses "fila_id", H2D uses "filament_id"
  5527. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  5528. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  5529. # H3C: home rack position 0-8 (the mounted hotend reports id 0)
  5530. "addr_id": n.get("addr_id") if isinstance(n.get("addr_id"), int) else None,
  5531. }
  5532. for i, n in enumerate(nozzle_info)
  5533. ],
  5534. key=lambda x: x["id"],
  5535. )
  5536. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  5537. self._nozzle_rack_logged = True
  5538. logger.debug(
  5539. "[%s] Nozzle info: %d entries, IDs: %s",
  5540. self.serial_number,
  5541. len(nozzle_info),
  5542. [n.get("id") for n in nozzle_info],
  5543. )
  5544. for nozzle in nozzle_info:
  5545. idx = nozzle.get("id", 0)
  5546. if idx < len(self.state.nozzles):
  5547. if "type" in nozzle and nozzle["type"]:
  5548. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  5549. if "diameter" in nozzle:
  5550. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  5551. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  5552. # (these fields aren't sent in every MQTT push, only when changed)
  5553. ams_data = self.state.raw_data.get("ams")
  5554. vt_tray_data = self.state.raw_data.get("vt_tray")
  5555. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  5556. mapping_data = self.state.raw_data.get("mapping")
  5557. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  5558. # as a dict but consumers expect a list. Without this, the dev mode probe
  5559. # below can release the GIL (via publish), letting the event-loop thread
  5560. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  5561. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  5562. data["vt_tray"] = [data["vt_tray"]]
  5563. self.state.raw_data = data
  5564. # Restore preserved fields BEFORE any work that may release the GIL
  5565. # (e.g. _probe_developer_mode publishes an MQTT message).
  5566. if ams_data is not None:
  5567. self.state.raw_data["ams"] = ams_data
  5568. elif not isinstance(self.state.raw_data.get("ams"), list):
  5569. # #3499: no unit list yet (the AMS handling failed on this frame).
  5570. # The frame's AMS object is not one; readers iterate it as units.
  5571. self.state.raw_data.pop("ams", None)
  5572. if vt_tray_data is not None:
  5573. self.state.raw_data["vt_tray"] = vt_tray_data
  5574. if ams_extruder_map_data is not None:
  5575. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  5576. if mapping_data is not None and "mapping" not in data:
  5577. self.state.raw_data["mapping"] = mapping_data
  5578. # Parse developer LAN mode from "fun" field
  5579. if "fun" in data:
  5580. try:
  5581. fun_val = data["fun"]
  5582. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  5583. self.state.developer_mode = (fun_int & 0x20000000) == 0
  5584. except (ValueError, TypeError):
  5585. pass
  5586. elif self.state.developer_mode is None and not self._dev_mode_probed:
  5587. # No "fun" field — A1/P1 series never send it, so we need to probe.
  5588. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  5589. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  5590. # after connect to let the MQTT session stabilize — probing too early
  5591. # can destabilize some firmware MQTT brokers (#887).
  5592. if not self._dev_mode_needs_probe and len(data) > 30:
  5593. # First full status without "fun" — mark that probe is needed
  5594. self._dev_mode_needs_probe = True
  5595. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  5596. self._probe_developer_mode()
  5597. elif self._dev_mode_needs_probe:
  5598. logger.debug(
  5599. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  5600. self.serial_number,
  5601. time.monotonic() - self._connect_time,
  5602. )
  5603. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  5604. # Probe was sent but no response yet — check for timeout.
  5605. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  5606. # may deliver status pushes but silently drop commands (#887).
  5607. elapsed = time.monotonic() - self._dev_mode_probe_time
  5608. if elapsed > 10.0:
  5609. self._dev_mode_probe_failures += 1
  5610. logger.warning(
  5611. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  5612. self.serial_number,
  5613. elapsed,
  5614. self._dev_mode_probe_failures,
  5615. )
  5616. self._dev_mode_probe_seq = None
  5617. if self._dev_mode_probe_failures >= 2:
  5618. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  5619. else:
  5620. # Allow retry on next full status message
  5621. self._dev_mode_probed = False
  5622. # Zombie session detection: if an ams_filament_setting command has been
  5623. # pending for >10s with no response, the publish path is likely dead (#887).
  5624. if self._last_ams_cmd_time > 0:
  5625. elapsed = time.monotonic() - self._last_ams_cmd_time
  5626. if elapsed > 10.0:
  5627. self._ams_cmd_unanswered += 1
  5628. logger.warning(
  5629. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  5630. self.serial_number,
  5631. elapsed,
  5632. self._ams_cmd_unanswered,
  5633. )
  5634. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  5635. if self._ams_cmd_unanswered >= 2:
  5636. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  5637. self._ams_cmd_unanswered = 0
  5638. # Log mapping data when received (for usage tracking debugging)
  5639. if "mapping" in data:
  5640. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  5641. # Log state transitions for debugging
  5642. if "gcode_state" in data:
  5643. logger.debug(
  5644. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  5645. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  5646. )
  5647. # Detect print start (state changes TO RUNNING with a file)
  5648. current_file = self.state.gcode_file or self.state.current_print
  5649. if self._previous_gcode_state is None and self.state.state == "PAUSE" and current_file:
  5650. self._paused_at_startup = True
  5651. is_new_print = (
  5652. self.state.state == "RUNNING"
  5653. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  5654. and self._previous_gcode_state != "RUNNING"
  5655. and current_file
  5656. and not self._was_running # Prevent duplicates when resuming from PAUSE
  5657. # #3485: a print paused when Bambuddy started resumes like one it
  5658. # found running (#1304): restart recovery below, not a new print.
  5659. and not (self._paused_at_startup and self._previous_gcode_state == "PAUSE")
  5660. )
  5661. if self.state.state != "PAUSE":
  5662. self._paused_at_startup = False
  5663. # Also detect if file changed while running (new print started)
  5664. is_file_change = (
  5665. self.state.state == "RUNNING"
  5666. and current_file
  5667. and current_file != self._previous_gcode_file
  5668. and self._previous_gcode_file is not None
  5669. )
  5670. # Track RUNNING state for more robust completion detection
  5671. running_first_observed = False
  5672. if self.state.state == "RUNNING" and current_file:
  5673. if not self._was_running:
  5674. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  5675. # Check if timelapse was enabled in the same message (xcam parsed before this)
  5676. if self.state.timelapse:
  5677. self._timelapse_during_print = True
  5678. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  5679. # Mark this as the first RUNNING observation of the session.
  5680. # If is_new_print also fires below, on_print_start handles
  5681. # baseline capture and we suppress on_print_running_observed
  5682. # to avoid double-capture. If is_new_print does NOT fire
  5683. # (Bambuddy started mid-print — the #1304 guard suppressed
  5684. # it), main.py needs this hook to catch the restart-recovery
  5685. # case (#1485 follow-up).
  5686. running_first_observed = True
  5687. self._was_running = True
  5688. self._completion_triggered = False
  5689. if is_new_print or is_file_change:
  5690. # Clear any old HMS errors when a new print starts
  5691. self.state.hms_errors = []
  5692. # The last print's pauses; this one's come from its 3MF (#2984).
  5693. self.state.pause_points = []
  5694. self.state.pause_warned_layers = set()
  5695. # Reset layer tracking for new print (needed for layer-based timelapse)
  5696. # #3317: only above 1. Every print reports layer 1 first, which
  5697. # clears a higher value; a previous print that ended on layer 1
  5698. # would make this print's own first layer look stale.
  5699. self._stale_layer_num = self.state.layer_num if self.state.layer_num > 1 else 0
  5700. self.state.layer_num = 0
  5701. # Reset total_layers so the previous print's value can't bleed into
  5702. # this print's usage-tracker split (#1771 follow-on to the
  5703. # preservation guard at the `total_layer_num` parse above — that
  5704. # guard ignores firmware-reset 0s, so the explicit reset has to
  5705. # happen here instead).
  5706. #
  5707. # #2702: reset to *this frame's* total, not to 0. The frame that
  5708. # trips the new-print detection can carry the new print's
  5709. # `total_layer_num` as well — the parse above has already applied
  5710. # it, and zeroing unconditionally threw it away. That looked
  5711. # harmless but is not recoverable: Bambu firmware sends only
  5712. # changed fields, so the printer never offers the total again, and
  5713. # the print runs to completion at `n/0` in the UI, in
  5714. # `{total_layers}` notifications, and as the usage-split
  5715. # denominator. The value only reappears on the next full pushall
  5716. # (reconnect / Force Refresh), which is why the symptom looked
  5717. # random and why a *stable* connection made it worse.
  5718. self.state.total_layers = total_from_this_frame
  5719. # If the starting frame brought no total, ask for one. Costs one
  5720. # MQTT message per print and covers the ordering where the printer
  5721. # published the total a frame or two before the state flip.
  5722. self._total_layers_refresh_armed = not total_from_this_frame
  5723. if self._total_layers_refresh_armed:
  5724. self._request_push_all()
  5725. # Reset completion tracking for new print
  5726. self._was_running = True
  5727. self._completion_triggered = False
  5728. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5729. self._finish_photo_captured = False
  5730. # #2547: rearm the end-of-print telemetry probe for the new print
  5731. self._eop_probe_armed = True
  5732. self._eop_probe_open = False
  5733. self._eop_probe_frames = 0
  5734. self._eop_probe_last = {}
  5735. # Reset last valid progress/layer for usage tracking
  5736. self._last_valid_progress = 0.0
  5737. self._last_valid_layer_num = 0
  5738. # Clear and seed tray change log for mid-print usage splitting
  5739. self.state.tray_change_log.clear()
  5740. # Seeded with the assigned spools by usage_tracker.on_print_start.
  5741. self.state.spool_change_log = []
  5742. tn = self.state.tray_now
  5743. if self.tray_layout.is_loaded_tray(tn):
  5744. self.state.tray_change_log.append((tn, 0))
  5745. # Initialize timelapse tracking based on current state
  5746. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5747. # so self.state.timelapse may already be set from this message.
  5748. # We preserve that value instead of blindly resetting to False.
  5749. if self.state.timelapse:
  5750. self._timelapse_during_print = True
  5751. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5752. else:
  5753. self._timelapse_during_print = False
  5754. if (is_new_print or is_file_change) and self.on_print_start:
  5755. logger.info(
  5756. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5757. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5758. )
  5759. self.on_print_start(
  5760. {
  5761. "filename": current_file,
  5762. "subtask_name": self.state.subtask_name,
  5763. "remaining_time": self.state.remaining_time * 60
  5764. if self.state.remaining_time > 0
  5765. else None, # Convert minutes to seconds
  5766. "raw_data": data,
  5767. "ams_mapping": self._captured_ams_mapping,
  5768. }
  5769. )
  5770. elif running_first_observed and self.on_print_running_observed:
  5771. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5772. # print, so the #1304 first-push guard suppressed on_print_start,
  5773. # but we still need main.py to capture a fresh timelapse baseline
  5774. # before the printer uploads the in-flight MP4. Same payload
  5775. # shape as on_print_start so the consumer can reuse fields.
  5776. logger.info(
  5777. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5778. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5779. )
  5780. self.on_print_running_observed(
  5781. {
  5782. "filename": current_file,
  5783. "subtask_name": self.state.subtask_name,
  5784. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5785. "raw_data": data,
  5786. "ams_mapping": self._captured_ams_mapping,
  5787. }
  5788. )
  5789. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5790. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5791. # This handles cases where server restarts during a print
  5792. should_trigger_completion = (
  5793. self.state.state in ("FINISH", "FAILED")
  5794. and not self._completion_triggered
  5795. and self.on_print_complete
  5796. and (
  5797. self._previous_gcode_state == "RUNNING" # Normal transition
  5798. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5799. # Pre-print failure (#1111): printer rejected the job during setup
  5800. # — wrong nozzle size, AMS error, etc. The print never reaches
  5801. # RUNNING, so without this branch neither the RUNNING check nor
  5802. # _was_running match and the queue item stays stuck at "printing".
  5803. # Restricted to FAILED from pre-print states so a stale FAILED on
  5804. # first connection (prev=None) still can't accidentally fire.
  5805. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5806. )
  5807. )
  5808. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5809. if (
  5810. self.state.state == "IDLE"
  5811. and self._previous_gcode_state == "RUNNING"
  5812. and not self._completion_triggered
  5813. and self.on_print_complete
  5814. ):
  5815. should_trigger_completion = True
  5816. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5817. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5818. if (
  5819. not should_trigger_completion
  5820. and self.state.state in ("FINISH", "FAILED")
  5821. and self._previous_gcode_state != self.state.state
  5822. ):
  5823. logger.info(
  5824. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5825. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5826. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5827. )
  5828. # Mark as triggered so state is clean for the next print cycle
  5829. self._completion_triggered = True
  5830. if should_trigger_completion:
  5831. if self.state.state == "FINISH":
  5832. status = "completed"
  5833. elif self.state.state == "FAILED":
  5834. status = "failed"
  5835. else:
  5836. status = "aborted"
  5837. logger.info(
  5838. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5839. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5840. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5841. f"timelapse_during_print: {self._timelapse_during_print}"
  5842. )
  5843. timelapse_was_active = self._timelapse_during_print
  5844. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5845. # external-spool-only, HMS halt, or firmware variant that skips
  5846. # the unload phase) fire the finish-photo moment now. Bed has
  5847. # already dropped, framing is worse, but we still capture.
  5848. # Only on successful completion — aborted/failed prints don't
  5849. # produce a meaningful finish photo.
  5850. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5851. self._finish_photo_captured = True
  5852. logger.info(
  5853. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5854. f"stage-22 never fired; capturing at FINISH-state transition"
  5855. )
  5856. self.on_finish_photo_moment(
  5857. {
  5858. "trigger": "finish_state",
  5859. "filename": self._previous_gcode_file or current_file,
  5860. "subtask_name": self.state.subtask_name,
  5861. "timelapse_was_active": timelapse_was_active,
  5862. }
  5863. )
  5864. self._completion_triggered = True
  5865. self._was_running = False
  5866. self._timelapse_during_print = False # Reset for next print
  5867. # Include HMS errors for failure reason detection
  5868. hms_errors_data = [e.completion_payload() for e in self.state.hms_errors or []]
  5869. from backend.app.utils.printer_models import usage_progress
  5870. last_progress = usage_progress(
  5871. self.model, self._last_valid_progress, self._last_valid_layer_num, self.state.total_layers
  5872. )
  5873. self.on_print_complete(
  5874. {
  5875. "status": status,
  5876. "subtask_id": self.state.subtask_id,
  5877. "filename": self._previous_gcode_file or current_file,
  5878. "subtask_name": self.state.subtask_name,
  5879. "raw_data": data,
  5880. "timelapse_was_active": timelapse_was_active,
  5881. "hms_errors": hms_errors_data,
  5882. "ams_mapping": self._captured_ams_mapping,
  5883. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5884. "last_progress": last_progress,
  5885. "last_layer_num": self._last_valid_layer_num,
  5886. }
  5887. )
  5888. self._captured_ams_mapping = None
  5889. # Same lifecycle as the mapping above: it described *this* print.
  5890. # Leaving it set would hand the next print an answer about where a
  5891. # different file went, and a stale "internal storage" reading costs
  5892. # an archive that the FTPS sweep would have found (#2780).
  5893. self.state.current_project_url = None
  5894. self._previous_gcode_state = self.state.state
  5895. if current_file:
  5896. self._previous_gcode_file = current_file
  5897. if self.on_state_change:
  5898. self.on_state_change(self.state)
  5899. def _request_push_all(self):
  5900. """Request full status update from printer."""
  5901. if self._client:
  5902. message = {"pushing": {"command": "pushall"}}
  5903. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5904. def _probe_developer_mode(self):
  5905. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5906. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5907. For these, we detect developer mode by sending a harmless command and
  5908. checking whether the printer accepts or rejects it:
  5909. - result="success" → developer mode ON (commands accepted)
  5910. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5911. The probe re-sends the current external slot configuration so it's a no-op
  5912. when the command succeeds. If there's no external slot data yet, we send a
  5913. reset (empty filament) which is also safe.
  5914. """
  5915. if not self._client or not self.state.connected:
  5916. return
  5917. self._dev_mode_probed = True
  5918. self._dev_mode_probe_time = time.monotonic()
  5919. self._sequence_id += 1
  5920. seq = str(self._sequence_id)
  5921. self._dev_mode_probe_seq = seq
  5922. # Build probe command: re-send current external slot config (no-op on success)
  5923. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5924. current = vt_tray[0] if vt_tray else {}
  5925. command = {
  5926. "print": {
  5927. "command": "ams_filament_setting",
  5928. "ams_id": 255,
  5929. "tray_id": 0,
  5930. "slot_id": 0,
  5931. "tray_info_idx": current.get("tray_info_idx", ""),
  5932. "tray_type": current.get("tray_type", ""),
  5933. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5934. "tray_color": current.get("tray_color", "00000000"),
  5935. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5936. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5937. "sequence_id": seq,
  5938. }
  5939. }
  5940. setting_id = current.get("setting_id")
  5941. if setting_id:
  5942. command["print"]["setting_id"] = setting_id
  5943. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5944. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5945. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5946. """Reconcile developer_mode with the printer's own command-verification verdict.
  5947. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5948. control commands are being refused, so it outranks the probe in both
  5949. directions:
  5950. * present → developer_mode is definitively False, whatever the probe
  5951. concluded. The probe can only read the response to its own
  5952. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5953. instead, so the probe answers ENABLED while every print silently dies
  5954. (#2732).
  5955. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5956. probe, so a user who enables Developer Mode and restarts the printer
  5957. isn't stuck behind a verdict nothing would ever revisit.
  5958. A False that came from the probe or the ``fun`` bit is left alone — this
  5959. only ever unwinds its own latch.
  5960. """
  5961. if verify_failed:
  5962. if not self._dev_mode_from_hms:
  5963. logger.warning(
  5964. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5965. "rejecting control commands, so prints, temperature changes and filament "
  5966. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5967. self.serial_number,
  5968. HMS_MQTT_VERIFY_FAILED,
  5969. )
  5970. self._dev_mode_from_hms = True
  5971. self.state.developer_mode = False
  5972. return
  5973. if not self._dev_mode_from_hms:
  5974. return
  5975. logger.info(
  5976. "[%s] HMS %s cleared — re-probing developer mode",
  5977. self.serial_number,
  5978. HMS_MQTT_VERIFY_FAILED,
  5979. )
  5980. self._dev_mode_from_hms = False
  5981. self.state.developer_mode = None
  5982. self._dev_mode_probed = False
  5983. self._dev_mode_needs_probe = False
  5984. def _handle_dev_mode_probe_response(self, data: dict):
  5985. """Handle response to the developer mode probe command.
  5986. Sets developer_mode based on whether the printer accepted or rejected the command.
  5987. Three outcomes, not two. An explicit ``success`` proves commands are
  5988. accepted and an explicit verify-failure proves they are not, but anything
  5989. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5990. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5991. ``result`` at all, while refusing every control command and reporting
  5992. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5993. is what put ``developer_mode: pass`` in the support bundle of a printer
  5994. that had not accepted a command all day (#2732). Leaving it unknown makes
  5995. the connection diagnostic report ``skip``, which is the honest answer.
  5996. """
  5997. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5998. self._dev_mode_probe_failures = 0 # Reset on any response
  5999. result = data.get("result", "")
  6000. reason = data.get("reason", "")
  6001. if result == "failed" and "verify failed" in reason:
  6002. self.state.developer_mode = False
  6003. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  6004. elif str(result).lower() == "success":
  6005. self.state.developer_mode = True
  6006. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  6007. else:
  6008. # An HMS verdict already recorded here is real evidence; don't let an
  6009. # inconclusive probe response wipe it back to unknown.
  6010. if not self._dev_mode_from_hms:
  6011. self.state.developer_mode = None
  6012. logger.info(
  6013. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  6014. "the printer neither confirmed nor refused the command",
  6015. self.serial_number,
  6016. result,
  6017. reason,
  6018. )
  6019. if self.on_state_change:
  6020. self.on_state_change(self.state)
  6021. def _request_version(self):
  6022. """Request firmware version info from printer."""
  6023. if self._client:
  6024. self._sequence_id += 1
  6025. message = {
  6026. "info": {
  6027. "sequence_id": str(self._sequence_id),
  6028. "command": "get_version",
  6029. }
  6030. }
  6031. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  6032. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  6033. def request_status_update(self) -> bool:
  6034. """Request a full status update from the printer (public API).
  6035. Sends both pushall and get_accessories commands to refresh all data
  6036. including nozzle hardware info.
  6037. Returns:
  6038. True if the request was sent, False if not connected.
  6039. """
  6040. if not self._client or not self.state.connected:
  6041. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  6042. return False
  6043. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  6044. self._request_push_all()
  6045. # Note: get_accessories returns stale nozzle data on H2D.
  6046. # The correct nozzle data comes from push_status response.
  6047. return True
  6048. def _prime_kprofile_request(self):
  6049. """Send a priming K-profile request on connect.
  6050. Bambu printers often ignore the first K-profile request after connection,
  6051. so we send a dummy request on connect to 'prime' the system.
  6052. """
  6053. if self._client:
  6054. self._sequence_id += 1
  6055. command = {
  6056. "print": {
  6057. "command": "extrusion_cali_get",
  6058. "filament_id": "",
  6059. "nozzle_diameter": "0.4",
  6060. "sequence_id": str(self._sequence_id),
  6061. }
  6062. }
  6063. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  6064. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6065. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  6066. """Connect to the printer MQTT broker.
  6067. Args:
  6068. loop: The asyncio event loop to use for thread-safe callbacks.
  6069. If not provided, will try to get the running loop.
  6070. """
  6071. self._loop = loop
  6072. BambuMQTTClient._client_instance_counter += 1
  6073. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  6074. self._client = mqtt.Client(
  6075. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  6076. client_id=client_id,
  6077. protocol=mqtt.MQTTv311,
  6078. )
  6079. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  6080. # tracking (#1164). The default ceiling of 20 wedges sessions after
  6081. # ~16-20 cumulative commands; lifting it well above any realistic
  6082. # session count keeps QoS=1 working without changing wire-protocol
  6083. # behaviour across printer models.
  6084. self._client.max_inflight_messages_set(1000)
  6085. self._client.username_pw_set("bblp", self.access_code)
  6086. self._client.on_connect = self._on_connect
  6087. self._client.on_disconnect = self._on_disconnect
  6088. self._client.on_subscribe = self._on_subscribe
  6089. self._client.on_message = self._on_message
  6090. # TLS setup - Bambu uses self-signed certs
  6091. ssl_context = ssl.create_default_context()
  6092. ssl_context.check_hostname = False
  6093. ssl_context.verify_mode = ssl.CERT_NONE
  6094. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  6095. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  6096. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  6097. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  6098. # bare-metal installs whose build allows TLS 1.0.
  6099. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  6100. self._client.tls_set_context(ssl_context)
  6101. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  6102. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  6103. # Keepalive: paho sends PINGREQs at this interval, broker considers
  6104. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  6105. # real network loss (45s), not so aggressive that transient hiccups
  6106. # trigger false disconnects. Stale detection (60s no messages) handles
  6107. # the P1S/P1P firmware bug where the broker stops publishing but the
  6108. # TCP connection stays alive.
  6109. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  6110. self._client.loop_start()
  6111. def start_print(
  6112. self,
  6113. filename: str,
  6114. plate_id: int = 1,
  6115. ams_mapping: list[int] | None = None,
  6116. bed_levelling: str = "auto",
  6117. flow_cali: str = "auto",
  6118. vibration_cali: bool = True,
  6119. layer_inspect: bool = False,
  6120. timelapse: bool = False,
  6121. use_ams: bool = True,
  6122. nozzle_offset_cali: str = "auto",
  6123. nozzle_mapping: str | None = None,
  6124. nozzle_slot_extruders: str | None = None,
  6125. plate_uses_only_external: bool = False,
  6126. ):
  6127. """Start a print job on the printer.
  6128. The file should already be uploaded to the printer's root directory via FTP.
  6129. Args:
  6130. filename: Name of the uploaded file
  6131. plate_id: Plate number to print (default 1)
  6132. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  6133. Global tray ID = (ams_id * 4) + slot_id, external = 254
  6134. timelapse: Record timelapse video
  6135. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  6136. if the bed was levelled recently, matching BambuStudio).
  6137. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  6138. vibration_cali: Vibration compensation calibration
  6139. layer_inspect: First layer AI inspection
  6140. use_ams: Use AMS for automatic filament changes
  6141. plate_uses_only_external: The caller determined from the plate's
  6142. own filament list that it prints only from the spool holder;
  6143. use_ams=False then stands even if the mapping names a real
  6144. tray (one another plate of the file uses, #3087)
  6145. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  6146. (dual-nozzle printers only — silently ignored on single-nozzle).
  6147. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  6148. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  6149. AND the printer is dual-nozzle, parsed and injected as the
  6150. `nozzle_mapping` array on the dispatched project_file so the
  6151. firmware honours the user's slicer pick instead of falling
  6152. back to "last matching nozzle" auto-pick. Silently ignored
  6153. on single-nozzle printers.
  6154. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  6155. MQTT extruder indices, derived from the 3MF when no
  6156. BambuStudio capture exists (#2800). Consulted only on
  6157. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  6158. not already supply one; resolved here into physical rack
  6159. positions using the live `device.nozzle` state. When it
  6160. cannot be resolved the field is omitted and the firmware
  6161. picks, as it did before this existed.
  6162. Returns True when the start command was published, False otherwise
  6163. (not connected, or the printer is already busy — see the run-state
  6164. guard below).
  6165. """
  6166. # Never dispatch project_file to a printer that is not idle (#2598).
  6167. # This is the single publish choke point for every dispatch path — the
  6168. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  6169. # forwarded job all funnel through here — so one guard covers them all.
  6170. # The firmware rejects a start while busy with 0500_4004 ("Device is
  6171. # busy and cannot start a new task"), and on an A1 mini that error
  6172. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  6173. # start targets; only the active-print states are refused. (A
  6174. # transport-level QoS-1 replay on reconnect would bypass this guard;
  6175. # _on_connect empties paho's outbox before it can re-send (#3454).)
  6176. if self.state.state in _ACTIVE_PRINT_STATES:
  6177. logger.warning(
  6178. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  6179. self.serial_number,
  6180. self.state.state,
  6181. filename,
  6182. )
  6183. return False
  6184. if self._client and self.state.connected:
  6185. # Bambu print command format — matches Bambu Studio's format.
  6186. # The calibration/leveling fields (timelapse, bed_leveling,
  6187. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  6188. # every model. An earlier revision integer-encoded them for the H2
  6189. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  6190. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  6191. # sends plain booleans, and the integer encoding made the H2S
  6192. # silently skip flow-dynamics calibration (#1478). use_ams is the
  6193. # one field that genuinely must stay boolean: H2D Pro firmware
  6194. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  6195. # what actually caused the wrong-extruder routing behind #1386.
  6196. # Dual-nozzle routing for external spool (254 = deputy/left,
  6197. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  6198. # H2 firmware family but is single-nozzle, despite sharing serial
  6199. # prefix "094" with H2D. Prefer runtime detection from
  6200. # device.extruder.info (set in _handle_push_status); fall back to
  6201. # model name for the brief window after connect before push data
  6202. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  6203. # as the primary signal.
  6204. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  6205. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6206. # The scheduler's filament check (#3522) reads the feed with the
  6207. # same `reconcile_use_ams`, but its dual-nozzle test
  6208. # (`_might_be_dual_nozzle`) is more generous: it also counts a
  6209. # populated `ams_extruder_map` or more than one external feed.
  6210. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  6211. ams_mapping2 = []
  6212. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  6213. # ams_mapping and relies on ams_mapping2 for external spool details.
  6214. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  6215. # with 0700_8012 "Failed to get AMS mapping table".
  6216. flat_ams_mapping = []
  6217. layout = self.tray_layout
  6218. if ams_mapping is not None:
  6219. for tray_id in ams_mapping:
  6220. # Ensure tray_id is an integer (may be string from JSON)
  6221. tray_id = int(tray_id) if tray_id is not None else -1
  6222. rack_slot = layout.rack_slot(tray_id) if tray_id >= 0 else None
  6223. if tray_id == -1:
  6224. # Unmapped filament slot
  6225. flat_ams_mapping.append(-1)
  6226. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  6227. elif layout.rack and layout.is_external(tray_id):
  6228. # A rack printer's per-hotend input 247-255, as Studio
  6229. # sends it: -1 flat, its own id in ams_mapping2.
  6230. flat_ams_mapping.append(-1)
  6231. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6232. elif rack_slot is not None:
  6233. # Rack AMS slot, as Studio sends it: 28 + k flat,
  6234. # {ams_id: 32, slot_id: k} in ams_mapping2.
  6235. flat_ams_mapping.append(tray_id)
  6236. ams_mapping2.append({"ams_id": rack_slot[0], "slot_id": rack_slot[1]})
  6237. elif tray_id >= 254:
  6238. # External/virtual spool. BambuStudio convention:
  6239. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  6240. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  6241. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  6242. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  6243. # for external spool, but BambuStudio always sends ams_id=255
  6244. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  6245. # firmware to target AMS tray 0 instead of external spool, leading
  6246. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  6247. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  6248. flat_ams_mapping.append(-1)
  6249. ext_ams_id = tray_id if is_dual_nozzle else 255
  6250. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  6251. elif tray_id >= 128:
  6252. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  6253. flat_ams_mapping.append(tray_id)
  6254. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6255. elif (_a2l := a2l_lite_wire_ids(layout.slot_key(tray_id)[0], tray_id)) is not None:
  6256. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  6257. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  6258. # — both CONFIRMED against the firmware's own mapping
  6259. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  6260. _wire_ams, _wire_slot, _ = _a2l
  6261. flat_ams_mapping.append(_wire_slot)
  6262. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  6263. else:
  6264. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  6265. ams_id, slot_id = layout.slot_key(tray_id)
  6266. flat_ams_mapping.append(tray_id)
  6267. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  6268. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  6269. # printers — the mapping is authoritative about whether this print
  6270. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  6271. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  6272. # H2S falls through here now (#1386): it is single-nozzle and was
  6273. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  6274. # without an AMS attached.
  6275. #
  6276. # Two symmetric corrections:
  6277. #
  6278. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  6279. # use_ams=True even if it arrived False. A print sent to a Virtual
  6280. # Printer is sliced against the VP, which advertises no AMS, so the
  6281. # slicer sends use_ams=false and that gets stamped on the queue item
  6282. # — but at dispatch the scheduler colour-matches a real printer and
  6283. # resolves a real AMS slot. Without this, the stale False reaches the
  6284. # printer, which ignores the mapped slot and aborts at layer 0 on the
  6285. # empty external spool ("not enough filament"). Diagnosed by
  6286. # @Sawtaytoes (#2595, PR #2596).
  6287. #
  6288. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  6289. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  6290. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  6291. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  6292. # status-load race that persisted [-1] (#2589) — and treating it as
  6293. # external silently started the print against an empty feed. A genuine
  6294. # external selection is >=254; unresolved is -1; a loaded tray is
  6295. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  6296. # (or is recomputed upstream) instead of silently going external, and
  6297. # never gets force-enabled by (a) either.
  6298. #
  6299. # The rule lives in `reconcile_use_ams`, which the scheduler's
  6300. # filament-permission check (#3522) shares, so what it judges is
  6301. # what is sent here. (Not when the scheduler worked out from the
  6302. # plate's own filament list that it prints only from the spool
  6303. # holder: a real tray here is then one another plate of the file
  6304. # uses.)
  6305. if ams_mapping and not is_dual_nozzle:
  6306. reconciled = reconcile_use_ams(
  6307. ams_mapping, use_ams, layout, plate_uses_only_external=plate_uses_only_external
  6308. )
  6309. if reconciled and not use_ams:
  6310. logger.info(
  6311. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  6312. self.serial_number,
  6313. )
  6314. elif use_ams and not reconciled:
  6315. logger.info(
  6316. "[%s] All filament slots use external spool — setting use_ams=False",
  6317. self.serial_number,
  6318. )
  6319. use_ams = reconciled
  6320. # (c) A single-nozzle printer that reported no AMS at all can only
  6321. # print from the spool holder, whatever the mapping says. With
  6322. # nothing set on the holder the matcher resolves no mapping, so
  6323. # neither (a) nor (b) ran and the print went out as use_ams=True,
  6324. # which the firmware refuses with 07FF_8012 "Failed to get AMS
  6325. # mapping table" (#3356). An empty raw_data["ams"] is the
  6326. # printer's own report of no AMS; a missing key means no AMS
  6327. # push has been handled yet (a reconnect), which changes nothing.
  6328. if use_ams and not is_dual_nozzle and reports_no_ams(self.state.raw_data):
  6329. use_ams = False
  6330. logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
  6331. # Unique per-submission identity fields. Hardcoded "0" values caused
  6332. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  6333. # continuations of the same job: the printer reuses gcode_start_time
  6334. # from the prior print with task_id=0, so observers latch onto a stale
  6335. # timestamp and report compounding durations on repeat replays (#1011).
  6336. # BambuStudio mints fresh IDs per submission; matching that behavior
  6337. # makes the printer emit a clean state-transition for each job.
  6338. # md5 is left empty — firmware historically accepts "" as "skip
  6339. # validation" (unlike Studio, we don't have the file's real md5 here
  6340. # without re-reading the upload, and sending a synthetic wrong digest
  6341. # risks activation of md5 verification on some firmwares).
  6342. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  6343. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  6344. # overflows and every submission ends up with the same task_id from
  6345. # the printer's perspective — the printer then treats a fresh dispatch
  6346. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  6347. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  6348. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  6349. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  6350. # Remember it so on_print_start can persist a restart-stable id on
  6351. # the archive even before the printer echoes subtask_id back (#1485).
  6352. self.last_dispatch_subtask_id = submission_id
  6353. self.last_start_refusal = None
  6354. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  6355. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  6356. # only if it wasn't done recently). The paired bool field is true
  6357. # only for the explicit "on" state — for "auto" the bool is false and
  6358. # the int carries the intent, exactly as BambuStudio's SelectMachine
  6359. # sends it. Unknown values fall back to auto.
  6360. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  6361. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  6362. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  6363. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  6364. command = {
  6365. "print": {
  6366. "sequence_id": "20000",
  6367. "command": "project_file",
  6368. "param": f"Metadata/plate_{plate_id}.gcode",
  6369. "url": f"ftp://{filename}",
  6370. "file": filename,
  6371. "md5": "",
  6372. "bed_type": "auto",
  6373. "timelapse": timelapse,
  6374. # bed_leveling stays a JSON bool (true only for "on") and
  6375. # auto_bed_leveling carries the tri-state int — the exact
  6376. # two-field shape BambuStudio sends. The int must stay a plain
  6377. # number, never quoted (#1478 boolean-family concern applies to
  6378. # the *_cali bools, not these companion ints).
  6379. "bed_leveling": bed_levelling == "on",
  6380. "auto_bed_leveling": bed_level_int,
  6381. "flow_cali": flow_cali == "on",
  6382. "vibration_cali": vibration_cali,
  6383. "layer_inspect": layer_inspect,
  6384. "use_ams": use_ams,
  6385. # No "cfg": it is the printer's device-config bitmask
  6386. # (auto-refill, detect-on-insert, chamber light, ...), not a
  6387. # per-job field — BambuStudio's PrintParams has no such
  6388. # member. We used to send "0"; firmware ignores it, but it
  6389. # comes straight back in the project_file ack (#3040).
  6390. # extrude_cali_flag gates flow-dynamics calibration:
  6391. # 0 = never, 1 = force every print, 2 = auto (run only if the
  6392. # filament wasn't calibrated recently). #1721 saw stage 8
  6393. # ("Calibrating dynamic flow") still queued when we send 2 —
  6394. # that is exactly the auto contract (the printer queues the
  6395. # stage and skips it at runtime if recent), not a bug, so 2 is
  6396. # the right wire value for "auto". off/on remain 0/1.
  6397. "extrude_cali_flag": flow_cali_int,
  6398. "extrude_cali_manual_mode": 0,
  6399. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  6400. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  6401. # again the auto contract, not a failure to suppress.
  6402. # BambuStudio exposes the toggle only for dual-nozzle
  6403. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  6404. # firmware never runs a calibration the head doesn't support.
  6405. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  6406. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  6407. "profile_id": "0",
  6408. "project_id": submission_id,
  6409. "subtask_id": submission_id,
  6410. "task_id": submission_id,
  6411. }
  6412. }
  6413. # P2S-specific parameter adjustments
  6414. # P2S printer doesn't support vibration calibration like X1/P1 series
  6415. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  6416. command["print"]["vibration_cali"] = False
  6417. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  6418. # Add AMS mapping if provided
  6419. if ams_mapping is not None:
  6420. command["print"]["ams_mapping"] = flat_ams_mapping
  6421. command["print"]["ams_mapping2"] = ams_mapping2
  6422. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  6423. # `nozzle_mapping` carries per-filament physical nozzle position
  6424. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  6425. # item; parse here so the wire ships an array, matching
  6426. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  6427. # defensively — single-nozzle firmwares would ignore the field
  6428. # but we err on the side of not emitting unrecognised fields. A
  6429. # parse failure is logged but never blocks the dispatch — the
  6430. # firmware will fall back to its auto-pick path, which is the
  6431. # pre-fix behaviour.
  6432. if is_dual_nozzle and nozzle_mapping:
  6433. try:
  6434. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  6435. except json.JSONDecodeError:
  6436. logger.warning(
  6437. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  6438. "project_file (firmware will auto-pick): %r",
  6439. self.serial_number,
  6440. nozzle_mapping,
  6441. )
  6442. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  6443. # never saw the job, so it can never override a real capture. The
  6444. # queue stores extruder indices per filament slot; the physical
  6445. # rack position they resolve to is only knowable here, because the
  6446. # mounted hotend can change between queueing and dispatch.
  6447. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  6448. try:
  6449. slot_extruders = json.loads(nozzle_slot_extruders)
  6450. except (json.JSONDecodeError, TypeError):
  6451. # TypeError covers a caller handing us the list itself
  6452. # rather than its JSON — the field is opaque by contract,
  6453. # and a print must not die over the difference.
  6454. slot_extruders = None
  6455. logger.warning(
  6456. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  6457. "omitting nozzle_mapping (firmware will auto-pick): %r",
  6458. self.serial_number,
  6459. nozzle_slot_extruders,
  6460. )
  6461. if isinstance(slot_extruders, list):
  6462. rack_nozzle_id = (
  6463. self.state.nozzle_rack_tar_id
  6464. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  6465. else self.state.nozzle_rack_src_id
  6466. )
  6467. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  6468. if resolved is None:
  6469. logger.info(
  6470. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  6471. "omitting nozzle_mapping so the firmware picks",
  6472. self.serial_number,
  6473. slot_extruders,
  6474. self.state.nozzle_rack_tar_id,
  6475. self.state.nozzle_rack_src_id,
  6476. )
  6477. else:
  6478. logger.info(
  6479. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  6480. self.serial_number,
  6481. slot_extruders,
  6482. rack_nozzle_id,
  6483. resolved,
  6484. )
  6485. command["print"]["nozzle_mapping"] = resolved
  6486. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  6487. # Remember this dispatch so its echo on the topic is recognised as
  6488. # ours rather than logged as a slicer's.
  6489. self._own_project_file_key = self._project_file_key(command["print"])
  6490. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6491. # Record what we dispatched so /cover can pick the right plate
  6492. # thumbnail even when the printer's gcode_file echo is just the
  6493. # 3MF filename without a plate path (#1166). Match the same
  6494. # subtask_name shape we send so the comparison in the cover route
  6495. # works against state.subtask_name reflected back via MQTT.
  6496. self.state.dispatched_plate_id = plate_id
  6497. self.state.dispatched_subtask = command["print"]["subtask_name"]
  6498. return True
  6499. else:
  6500. # Log why we couldn't send the command
  6501. if not self._client:
  6502. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  6503. elif not self.state.connected:
  6504. logger.error(
  6505. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  6506. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  6507. )
  6508. return False
  6509. def stop_print(self) -> bool:
  6510. """Stop the current print job."""
  6511. if self._client and self.state.connected:
  6512. command = {"print": {"command": "stop", "sequence_id": "0"}}
  6513. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6514. logger.info("[%s] Sent stop print command", self.serial_number)
  6515. return True
  6516. return False
  6517. def set_xcam_option(
  6518. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  6519. ) -> bool:
  6520. """Set an xcam (AI detection) option on the printer.
  6521. Args:
  6522. module_name: The xcam module to control (e.g., "spaghetti_detector",
  6523. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  6524. enabled: Whether to enable or disable the feature
  6525. print_halt: Whether to halt print on detection (only applies to some detectors)
  6526. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  6527. Returns:
  6528. True if command was sent, False if not connected
  6529. """
  6530. if not self._client or not self.state.connected:
  6531. return False
  6532. # auto_recovery_step_loss uses a different command format (print.print_option)
  6533. if module_name == "auto_recovery_step_loss":
  6534. return self._set_print_option("auto_recovery", enabled)
  6535. self._sequence_id += 1
  6536. # Build the xcam control command (exact OrcaSlicer format)
  6537. # Key findings from OrcaSlicer source:
  6538. # - Uses "xcam" wrapper (not "print")
  6539. # - print_halt is ALWAYS true (legacy protocol requirement)
  6540. # - Both "control" and "enable" are set to the same value
  6541. # - halt_print_sensitivity controls actual halt behavior
  6542. command = {
  6543. "xcam": {
  6544. "command": "xcam_control_set",
  6545. "sequence_id": str(self._sequence_id),
  6546. "module_name": module_name,
  6547. "control": enabled,
  6548. "enable": enabled, # old protocol compatibility
  6549. "print_halt": True, # ALWAYS true per OrcaSlicer
  6550. }
  6551. }
  6552. # Only add sensitivity if not "never_halt"
  6553. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  6554. # The module_name field determines which detector's sensitivity is being set
  6555. if sensitivity and sensitivity != "never_halt":
  6556. command["xcam"]["halt_print_sensitivity"] = sensitivity
  6557. command_json = json.dumps(command)
  6558. self._client.publish(self.topic_publish, command_json, qos=1)
  6559. logger.debug(
  6560. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  6561. )
  6562. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  6563. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  6564. # This prevents stale MQTT data from immediately overwriting our change
  6565. self._xcam_hold_start[module_name] = time.time()
  6566. # Update local state immediately for responsive UI
  6567. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  6568. # When spaghetti_detector sensitivity is changed, pileup also changes
  6569. if module_name == "spaghetti_detector":
  6570. self.state.print_options.spaghetti_detector = enabled
  6571. self.state.print_options.print_halt = print_halt
  6572. if sensitivity and sensitivity != "never_halt":
  6573. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  6574. self.state.print_options.halt_print_sensitivity = sensitivity
  6575. self.state.print_options.pileup_sensitivity = sensitivity
  6576. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  6577. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  6578. elif module_name == "first_layer_inspector":
  6579. self.state.print_options.first_layer_inspector = enabled
  6580. elif module_name == "printing_monitor":
  6581. self.state.print_options.printing_monitor = enabled
  6582. elif module_name == "buildplate_marker_detector":
  6583. self.state.print_options.buildplate_marker_detector = enabled
  6584. elif module_name == "allow_skip_parts":
  6585. self.state.print_options.allow_skip_parts = enabled
  6586. elif module_name == "pileup_detector":
  6587. self.state.print_options.pileup_detector = enabled
  6588. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  6589. elif module_name == "clump_detector":
  6590. self.state.print_options.nozzle_clumping_detector = enabled
  6591. if sensitivity and sensitivity != "never_halt":
  6592. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  6593. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  6594. elif module_name == "airprint_detector":
  6595. self.state.print_options.airprint_detector = enabled
  6596. if sensitivity and sensitivity != "never_halt":
  6597. self.state.print_options.airprint_sensitivity = sensitivity
  6598. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  6599. elif module_name == "auto_recovery_step_loss":
  6600. self.state.print_options.auto_recovery_step_loss = enabled
  6601. return True
  6602. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  6603. """Set a print option using the print.print_option command.
  6604. This is different from xcam_control_set and is used for options like:
  6605. - auto_recovery
  6606. - air_print_detect
  6607. - filament_tangle_detect
  6608. - nozzle_blob_detect
  6609. - sound_enable
  6610. Args:
  6611. option_name: The option to control (e.g., "auto_recovery")
  6612. enabled: Whether to enable or disable the option
  6613. Returns:
  6614. True if command was sent, False if not connected
  6615. """
  6616. if not self._client or not self.state.connected:
  6617. return False
  6618. self._sequence_id += 1
  6619. command = {
  6620. "print": {
  6621. "command": "print_option",
  6622. "sequence_id": str(self._sequence_id),
  6623. option_name: enabled,
  6624. }
  6625. }
  6626. command_json = json.dumps(command)
  6627. self._client.publish(self.topic_publish, command_json, qos=1)
  6628. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  6629. # Set hold timer
  6630. hold_key = f"print_option_{option_name}"
  6631. self._xcam_hold_start[hold_key] = time.time()
  6632. # Update local state immediately
  6633. if option_name == "auto_recovery":
  6634. self.state.print_options.auto_recovery_step_loss = enabled
  6635. elif option_name == "auto_switch_filament":
  6636. self.state.ams_filament_backup = enabled
  6637. return True
  6638. def set_ams_filament_backup(self, enabled: bool) -> bool:
  6639. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  6640. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  6641. shape from H2D capture 2026-06-20.
  6642. """
  6643. return self._set_print_option("auto_switch_filament", enabled)
  6644. def start_calibration(
  6645. self,
  6646. bed_leveling: bool = False,
  6647. vibration: bool = False,
  6648. motor_noise: bool = False,
  6649. nozzle_offset: bool = False,
  6650. high_temp_heatbed: bool = False,
  6651. ) -> bool:
  6652. """Start printer calibration with selected options.
  6653. Args:
  6654. bed_leveling: Run bed leveling calibration
  6655. vibration: Run vibration compensation calibration
  6656. motor_noise: Run motor noise cancellation calibration
  6657. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  6658. high_temp_heatbed: Run high-temperature heatbed calibration
  6659. Returns:
  6660. True if command was sent, False if not connected
  6661. """
  6662. if not self._client or not self.state.connected:
  6663. return False
  6664. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  6665. # Bit 0: xcam_cali (not exposed in UI)
  6666. # Bit 1: bed_leveling
  6667. # Bit 2: vibration
  6668. # Bit 3: motor_noise
  6669. # Bit 4: nozzle_cali
  6670. # Bit 5: bed_cali (high-temp heatbed)
  6671. # Bit 6: clumppos_cali (not exposed in UI)
  6672. option = 0
  6673. if bed_leveling:
  6674. option |= 1 << 1
  6675. if vibration:
  6676. option |= 1 << 2
  6677. if motor_noise:
  6678. option |= 1 << 3
  6679. if nozzle_offset:
  6680. option |= 1 << 4
  6681. if high_temp_heatbed:
  6682. option |= 1 << 5
  6683. if option == 0:
  6684. logger.warning("[%s] No calibration options selected", self.serial_number)
  6685. return False
  6686. self._sequence_id += 1
  6687. command = {
  6688. "print": {
  6689. "command": "calibration",
  6690. "sequence_id": str(self._sequence_id),
  6691. "option": option,
  6692. }
  6693. }
  6694. command_json = json.dumps(command)
  6695. self._client.publish(self.topic_publish, command_json, qos=1)
  6696. logger.info(
  6697. f"[{self.serial_number}] Starting calibration: "
  6698. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  6699. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  6700. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  6701. )
  6702. return True
  6703. def disconnect(self, timeout: float = 0):
  6704. """Disconnect from the printer.
  6705. Waits up to *timeout* for paho to report the disconnect, then lets the
  6706. client go without joining its network thread — the callers are route
  6707. handlers (printer edited, deleted, disconnected by hand) running on the
  6708. asyncio thread, and that join has no bound (#3068)."""
  6709. if self._client:
  6710. old_client = self._client
  6711. self._disconnection_event = threading.Event()
  6712. old_client.disconnect()
  6713. # The callback that sets this fires on paho's thread, so it has to
  6714. # be given its window before retire_paho_client detaches it.
  6715. self._disconnection_event.wait(timeout=timeout)
  6716. self._client = None
  6717. retire_paho_client(old_client, self.serial_number)
  6718. self.state.connected = False
  6719. # Deliberately no on_state_change here. paho's disconnect callback
  6720. # used to land during the join, but `_on_disconnect` suppresses
  6721. # itself for a clean disconnect of a printer that reported within
  6722. # the last 10s -- which is every healthy printer -- so a
  6723. # hand-disconnected printer never broadcast one. Announcing it now
  6724. # would fire the connected→disconnected edge in
  6725. # `on_printer_status_change` and notify the user their printer went
  6726. # offline a minute after they disconnected it on purpose (#1752).
  6727. # The callers drop the client from the manager anyway, so the next
  6728. # status read already shows it gone.
  6729. def enable_logging(self, enabled: bool = True):
  6730. """Enable or disable MQTT message logging."""
  6731. self._logging_enabled = enabled
  6732. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6733. def get_logs(self) -> list[MQTTLogEntry]:
  6734. """Get all logged MQTT messages."""
  6735. return list(self._message_log)
  6736. def clear_logs(self):
  6737. """Clear the message log."""
  6738. self._message_log.clear()
  6739. @property
  6740. def logging_enabled(self) -> bool:
  6741. """Check if logging is enabled."""
  6742. return self._logging_enabled
  6743. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6744. """Register a handler invoked for every incoming MQTT message.
  6745. Used by the VP MQTT bridge to republish the printer's report pushes to
  6746. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6747. on paho's network thread and must not block; exceptions are caught.
  6748. """
  6749. if handler not in self._raw_message_handlers:
  6750. self._raw_message_handlers.append(handler)
  6751. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6752. """Unregister a previously-registered raw-message handler."""
  6753. try:
  6754. self._raw_message_handlers.remove(handler)
  6755. except ValueError:
  6756. pass
  6757. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6758. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6759. Used by the VP MQTT bridge to forward slicer-originated commands without
  6760. giving it one of our own sequence ids. Returns False if the
  6761. underlying paho client isn't ready.
  6762. """
  6763. if self._client is None:
  6764. return False
  6765. try:
  6766. info = self._client.publish(topic, payload, qos=qos)
  6767. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6768. except Exception:
  6769. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6770. return False
  6771. def _ams3h_drying_zone_id(self, ams_id: int) -> int:
  6772. """The drying zone id of AMS 3H unit ``ams_id`` from the last status, else 0."""
  6773. unit = self._ams_unit(ams_id)
  6774. return _mqtt_int((unit or {}).get("dry_zone_id")) or 0
  6775. def send_drying_command(
  6776. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6777. ):
  6778. """Send AMS drying start/stop command.
  6779. Args:
  6780. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6781. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6782. duration: Drying duration in hours
  6783. mode: 1=start, 0=stop
  6784. filament: Filament type string (e.g. "PLA", "PETG")
  6785. rotate_tray: Whether to rotate the spool during drying for even heat
  6786. """
  6787. if not self._client:
  6788. return False
  6789. self._sequence_id += 1
  6790. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6791. # not actually support drying, but keep the translation consistent). The
  6792. # _drying_targets dict below stays keyed by the normalised id so the
  6793. # on_drying_complete callback matches the telemetry.
  6794. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6795. ams3h = self._rack_ams_type(ams_id) == AmsType.ZMULTI_A
  6796. command = {
  6797. "print": {
  6798. "sequence_id": str(self._sequence_id),
  6799. "command": "ams_filament_drying",
  6800. "ams_id": wire_ams_id,
  6801. "temp": temp,
  6802. "cooling_temp": 20 if mode == 1 else 0,
  6803. "duration": duration,
  6804. "humidity": 0,
  6805. "mode": mode,
  6806. "rotate_tray": rotate_tray,
  6807. "filament": filament,
  6808. "close_power_conflict": False,
  6809. }
  6810. }
  6811. if ams3h:
  6812. # As Studio 02.09 sends it (DevFilaSystemCtrl.cpp): a start names
  6813. # the drying zone and cooling_temp; a stop names no zone. The AMS 3H
  6814. # can't turn spools.
  6815. command["print"]["rotate_tray"] = False
  6816. if mode == 1:
  6817. command["print"]["zone_id"] = self._ams3h_drying_zone_id(ams_id)
  6818. command["print"]["cooling_temp"] = ams3h_drying_cooling_temp(filament)
  6819. # Log the full wire JSON at INFO so support bundles capture exactly
  6820. # what we sent — needed to diagnose silent rejections (#1447) where
  6821. # the printer ACKs the command but never starts/stops drying.
  6822. # Paired with the ams_filament_drying response-payload INFO log so
  6823. # both halves of the conversation land in the bundle by default.
  6824. wire_json = json.dumps(command)
  6825. self._client.publish(self.topic_publish, wire_json, qos=1)
  6826. logger.info(
  6827. "[%s] Sent ams_filament_drying: %s",
  6828. self.serial_number,
  6829. wire_json,
  6830. )
  6831. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6832. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6833. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6834. # say how much of the requested time the firmware actually ran (#2770).
  6835. if mode == 1:
  6836. self._drying_targets[ams_id] = {
  6837. "filament": filament or "",
  6838. "temp": int(temp),
  6839. "duration_hours": int(duration),
  6840. }
  6841. self._drying_stops_sent.discard(ams_id)
  6842. # A start sent while a cycle is still counting down replaces it
  6843. # without dry_time passing through 0; begin a fresh record so the
  6844. # new target and length are the ones reported (#2863).
  6845. self._dry_cycles.pop(ams_id, None)
  6846. else:
  6847. self._drying_targets.pop(ams_id, None)
  6848. # Remember that this cycle's end is ours, so the cycle-end log
  6849. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6850. # stop always ends the cycle far short of its duration, which is
  6851. # otherwise indistinguishable from the firmware abandoning it.
  6852. self._drying_stops_sent.add(ams_id)
  6853. return True
  6854. @staticmethod
  6855. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6856. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6857. The printer reports ``nozzle_diameter`` **only on the response
  6858. envelope** — the per-filament entries carry just setting_id,
  6859. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6860. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6861. single-nozzle printers regardless of the installed nozzle (#1748),
  6862. which broke the K-Profiles display and, worse, the cali_idx cascade
  6863. in the inventory/Spoolman assign paths that matches on
  6864. nozzle_diameter. Fall back to the envelope value instead, and only
  6865. to "0.4" when the envelope has none either.
  6866. ``or`` rather than a dict default on purpose: it also covers an entry
  6867. that carries the key with an empty value, and stops ``str()`` turning
  6868. a missing envelope value into the literal "None".
  6869. """
  6870. profiles: list[KProfile] = []
  6871. for i, f in enumerate(filaments):
  6872. if not isinstance(f, dict):
  6873. continue
  6874. try:
  6875. profiles.append(
  6876. KProfile(
  6877. # cali_idx is the actual slot/calibration index from the printer
  6878. slot_id=f.get("cali_idx", i),
  6879. extruder_id=int(f.get("extruder_id", 0)),
  6880. nozzle_id=str(f.get("nozzle_id", "")),
  6881. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6882. filament_id=str(f.get("filament_id", "")),
  6883. name=str(f.get("name", "")),
  6884. k_value=str(f.get("k_value", "0.000000")),
  6885. n_coef=str(f.get("n_coef", "0.000000")),
  6886. ams_id=int(f.get("ams_id", 0)),
  6887. tray_id=int(f.get("tray_id", -1)),
  6888. setting_id=f.get("setting_id"),
  6889. )
  6890. )
  6891. except (ValueError, TypeError) as e:
  6892. # Skip malformed entries; the remaining profiles stay usable.
  6893. # Unsolicited broadcasts arrive constantly, so only a response
  6894. # someone is actually waiting on is worth a warning.
  6895. if log_errors:
  6896. logger.warning("Failed to parse K-profile: %s", e)
  6897. else:
  6898. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6899. return profiles
  6900. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6901. """File one calibration-table response under its nozzle diameter.
  6902. ``response_nozzle`` names the table the printer just sent, so that
  6903. bucket is replaced wholesale and every other one is left alone. When
  6904. the envelope carries no diameter, fall back to the diameters the parsed
  6905. profiles claim for themselves — and if there are none of those either,
  6906. keep what we have rather than dropping a table we cannot attribute.
  6907. ``state.kprofiles`` stays a flat list because that is what its readers
  6908. expect; the three assign paths already filter it by ``nozzle_diameter``
  6909. and were quietly finding nothing whenever the last response happened to
  6910. be for a different nozzle.
  6911. """
  6912. buckets: dict[str, list] = {}
  6913. if response_nozzle:
  6914. buckets[str(response_nozzle)] = list(profiles)
  6915. else:
  6916. for profile in profiles:
  6917. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6918. if not buckets:
  6919. return
  6920. self._kprofiles_by_nozzle.update(buckets)
  6921. self.state.kprofiles = [
  6922. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6923. ]
  6924. def _handle_kprofile_response(self, data: dict):
  6925. """Handle K-profile response from printer."""
  6926. response_nozzle = data.get("nozzle_diameter")
  6927. response_seq_id = str(data.get("sequence_id", ""))
  6928. filaments = data.get("filaments", [])
  6929. # Snapshot the map: the asyncio thread adds and removes entries while
  6930. # this MQTT callback thread walks it.
  6931. pending = dict(self._pending_kprofile_requests)
  6932. request = pending.get(response_seq_id)
  6933. if request is None and pending:
  6934. # Firmware that doesn't echo our sequence_id still has to be
  6935. # served, so fall back to the pre-#1748 rule of matching on the
  6936. # nozzle size. Only requests still waiting are eligible, and the
  6937. # sequence_id lookup above has already claimed any response that
  6938. # identifies itself, so this can no longer hand request A's
  6939. # answer to request B when both are in flight.
  6940. request = next(
  6941. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6942. None,
  6943. )
  6944. if pending:
  6945. logger.info(
  6946. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6947. self.serial_number,
  6948. response_nozzle,
  6949. response_seq_id or "?",
  6950. len(filaments),
  6951. request is not None,
  6952. )
  6953. if request is None and pending:
  6954. # A request is outstanding and this isn't its answer. The printer
  6955. # broadcasts extrusion_cali_get unsolicited, so letting this
  6956. # through would replace state.kprofiles with another nozzle's
  6957. # profiles while the caller is still waiting.
  6958. logger.debug(
  6959. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6960. self.serial_number,
  6961. response_nozzle,
  6962. response_seq_id or "?",
  6963. )
  6964. return
  6965. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6966. self._store_kprofiles(profiles, response_nozzle)
  6967. if request is None:
  6968. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6969. # nobody to wake. Worth a line — this is the printer answering
  6970. # somebody else (BambuStudio queries the same report topic), and
  6971. # until it was bucketed by nozzle it was also the quietest way for
  6972. # the AMS card's K values to change underneath us.
  6973. logger.debug(
  6974. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6975. self.serial_number,
  6976. response_nozzle or "?",
  6977. len(profiles),
  6978. )
  6979. return
  6980. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6981. request["profiles"] = profiles
  6982. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6983. # in a different thread than the event loop.
  6984. event = request["event"]
  6985. if self._loop and self._loop.is_running():
  6986. self._loop.call_soon_threadsafe(event.set)
  6987. else:
  6988. # Fallback for when loop is not available
  6989. event.set()
  6990. async def get_kprofiles(
  6991. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6992. ) -> list[KProfile]:
  6993. """Request K-profiles from the printer with retry logic.
  6994. Bambu printers sometimes ignore the first K-profile request, so we
  6995. implement retry logic to ensure reliable retrieval.
  6996. Args:
  6997. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6998. timeout: Timeout in seconds to wait for each response attempt
  6999. max_retries: Maximum number of retry attempts
  7000. Returns:
  7001. List of KProfile objects; empty when the printer has none for
  7002. the nozzle.
  7003. Raises:
  7004. KProfileReadError: not connected, or no answer to any attempt.
  7005. Returning an empty list made that a printer without profiles
  7006. (#3404).
  7007. """
  7008. if not self._client or not self.state.connected:
  7009. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  7010. raise KProfileReadError("Printer not connected")
  7011. # Capture current event loop for thread-safe callback
  7012. try:
  7013. self._loop = asyncio.get_running_loop()
  7014. except RuntimeError:
  7015. logger.warning("[%s] No running event loop", self.serial_number)
  7016. raise KProfileReadError("No running event loop") from None
  7017. for attempt in range(max_retries):
  7018. # Register this attempt under its own sequence_id so a concurrent
  7019. # request for a different nozzle size can't consume its response
  7020. # (#1748) — the pending map is keyed by exactly the id we send.
  7021. self._sequence_id += 1
  7022. seq_id = str(self._sequence_id)
  7023. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  7024. self._pending_kprofile_requests[seq_id] = request
  7025. # Send the command with nozzle_diameter filter
  7026. command = {
  7027. "print": {
  7028. "command": "extrusion_cali_get",
  7029. "filament_id": "",
  7030. "nozzle_diameter": nozzle_diameter,
  7031. "sequence_id": seq_id,
  7032. }
  7033. }
  7034. logger.info(
  7035. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  7036. )
  7037. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  7038. # Wait for the response (the handler matches it back to this entry)
  7039. try:
  7040. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7041. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  7042. profiles = request["profiles"] or []
  7043. logger.info(
  7044. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  7045. )
  7046. return profiles
  7047. except TimeoutError:
  7048. logger.warning(
  7049. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  7050. )
  7051. if attempt < max_retries - 1:
  7052. # Brief delay before retry
  7053. await asyncio.sleep(0.5)
  7054. finally:
  7055. self._pending_kprofile_requests.pop(seq_id, None)
  7056. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  7057. raise KProfileReadError("The printer did not answer the K-profile request")
  7058. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  7059. """Publish a K-profile write and arm its ack slot.
  7060. Registration happens before the publish because the printer answers in
  7061. well under a second — measured at 70-150ms — which is comfortably
  7062. before an async caller gets back to awaiting.
  7063. """
  7064. self._pending_cali_acks[seq_id] = None
  7065. try:
  7066. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7067. except Exception:
  7068. self._pending_cali_acks.pop(seq_id, None)
  7069. raise
  7070. return True
  7071. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  7072. """Wait for the printer's verdict on a K-profile write.
  7073. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  7074. explicitly said ``result: "fail"`` — a timeout returns True with a
  7075. detail string, because "no answer" is not evidence of rejection and
  7076. older firmware may not answer at all. Callers that need certainty read
  7077. the calibration table back.
  7078. Polled rather than event-driven on purpose: the ack is filled in by the
  7079. MQTT callback thread, and polling a dict costs one lookup every 50ms
  7080. for at most a few hundred milliseconds, against the cross-thread
  7081. event plumbing it would otherwise take.
  7082. """
  7083. deadline = time.monotonic() + timeout
  7084. try:
  7085. while time.monotonic() < deadline:
  7086. ack = self._pending_cali_acks.get(seq_id)
  7087. if ack is not None:
  7088. result = str(ack.get("result", "")).lower()
  7089. reason = str(ack.get("reason", "") or "")
  7090. if result == "fail":
  7091. return (False, reason or "printer reported failure")
  7092. return (True, reason)
  7093. await asyncio.sleep(0.05)
  7094. finally:
  7095. self._pending_cali_acks.pop(seq_id, None)
  7096. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  7097. return (True, CALI_ACK_UNCONFIRMED)
  7098. def set_kprofile(
  7099. self,
  7100. filament_id: str,
  7101. name: str,
  7102. k_value: str,
  7103. nozzle_diameter: str = "0.4",
  7104. nozzle_id: str = "HS00-0.4",
  7105. extruder_id: int = 0,
  7106. setting_id: str | None = None,
  7107. slot_id: int = 0,
  7108. cali_idx: int | None = None,
  7109. ) -> str | None:
  7110. """Set/update a K-profile on the printer.
  7111. Args:
  7112. filament_id: Bambu filament identifier
  7113. name: Profile name
  7114. k_value: Pressure advance value (e.g., "0.020000")
  7115. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7116. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  7117. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7118. setting_id: Existing setting ID for updates, None for new
  7119. slot_id: Calibration index (cali_idx) for the profile
  7120. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  7121. Returns:
  7122. The sequence_id the command was sent under, so the caller can
  7123. await the printer's verdict via await_cali_ack. None if the
  7124. command could not be sent.
  7125. """
  7126. if not self._client or not self.state.connected:
  7127. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  7128. return None
  7129. self._sequence_id += 1
  7130. seq_id = str(self._sequence_id)
  7131. # Build the filament entry - printer uses cali_idx for profile identification
  7132. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  7133. # For edits, use the provided cali_idx or slot_id
  7134. if cali_idx is not None:
  7135. effective_cali_idx = cali_idx
  7136. else:
  7137. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7138. # Generate a setting_id for new profiles (required by printer)
  7139. # Format: "PF" + 17 random digits
  7140. import random
  7141. if not setting_id and slot_id == 0:
  7142. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7143. filament_entry = {
  7144. "ams_id": 0,
  7145. "cali_idx": effective_cali_idx,
  7146. "extruder_id": extruder_id,
  7147. "filament_id": filament_id,
  7148. "k_value": k_value,
  7149. "n_coef": "0.000000",
  7150. "name": name,
  7151. "nozzle_diameter": nozzle_diameter,
  7152. "nozzle_id": nozzle_id,
  7153. "setting_id": setting_id if setting_id else "",
  7154. # 0, not -1. Single-nozzle firmware validates this field and
  7155. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  7156. # applying the write anyway, so the rejection looked like noise.
  7157. # Measured on an X1C: flipping only this value turns the ack into
  7158. # `success` (#2718). BambuStudio always sends a real tray_id and
  7159. # defaults it to 0 for a manually entered profile.
  7160. "tray_id": 0,
  7161. }
  7162. command = {
  7163. "print": {
  7164. "command": "extrusion_cali_set",
  7165. "filaments": [filament_entry],
  7166. "nozzle_diameter": nozzle_diameter,
  7167. "sequence_id": seq_id,
  7168. }
  7169. }
  7170. command_json = json.dumps(command)
  7171. logger.info(
  7172. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  7173. )
  7174. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  7175. self._publish_cali_write(command, seq_id)
  7176. return seq_id
  7177. def set_kprofiles_batch(
  7178. self,
  7179. profiles: list[dict],
  7180. nozzle_diameter: str = "0.4",
  7181. ) -> str | None:
  7182. """Set multiple K-profiles in a single command (for dual-nozzle).
  7183. Args:
  7184. profiles: List of profile dicts, each with:
  7185. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  7186. nozzle_diameter: Common nozzle diameter for all profiles
  7187. Returns:
  7188. The sequence_id the command was sent under (see set_kprofile),
  7189. or None if it could not be sent.
  7190. """
  7191. if not self._client or not self.state.connected:
  7192. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  7193. return None
  7194. import random
  7195. self._sequence_id += 1
  7196. seq_id = str(self._sequence_id)
  7197. filament_entries = []
  7198. for p in profiles:
  7199. slot_id = p.get("slot_id", 0)
  7200. cali_idx = p.get("cali_idx")
  7201. if cali_idx is not None:
  7202. effective_cali_idx = cali_idx
  7203. else:
  7204. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7205. setting_id = p.get("setting_id")
  7206. if not setting_id and slot_id == 0:
  7207. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7208. filament_entries.append(
  7209. {
  7210. "ams_id": 0,
  7211. "cali_idx": effective_cali_idx,
  7212. "extruder_id": p.get("extruder_id", 0),
  7213. "filament_id": p.get("filament_id", ""),
  7214. "k_value": p.get("k_value", "0.020000"),
  7215. "n_coef": "0.000000",
  7216. "name": p.get("name", ""),
  7217. "nozzle_diameter": nozzle_diameter,
  7218. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  7219. "setting_id": setting_id if setting_id else "",
  7220. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  7221. # single-nozzle firmware even though the write lands (#2718).
  7222. "tray_id": 0,
  7223. }
  7224. )
  7225. command = {
  7226. "print": {
  7227. "command": "extrusion_cali_set",
  7228. "filaments": filament_entries,
  7229. "nozzle_diameter": nozzle_diameter,
  7230. "sequence_id": seq_id,
  7231. }
  7232. }
  7233. command_json = json.dumps(command)
  7234. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  7235. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  7236. self._publish_cali_write(command, seq_id)
  7237. return seq_id
  7238. def delete_kprofile(
  7239. self,
  7240. cali_idx: int,
  7241. filament_id: str,
  7242. nozzle_id: str,
  7243. nozzle_diameter: str = "0.4",
  7244. extruder_id: int = 0,
  7245. setting_id: str | None = None,
  7246. ) -> str | None:
  7247. """Delete a K-profile from the printer.
  7248. Args:
  7249. cali_idx: The calibration index (slot_id) of the profile to delete
  7250. filament_id: Bambu filament identifier
  7251. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  7252. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7253. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7254. setting_id: Unique setting identifier (for X1C series)
  7255. Returns:
  7256. The sequence_id the command was sent under (see set_kprofile),
  7257. or None if it could not be sent.
  7258. """
  7259. if not self._client or not self.state.connected:
  7260. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  7261. return None
  7262. self._sequence_id += 1
  7263. seq_id = str(self._sequence_id)
  7264. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  7265. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  7266. # Prefer runtime detection from device.extruder.info; fall back to
  7267. # model name. H2S is single-nozzle but shares serial prefix "094" with
  7268. # H2D, so a prefix-only check misclassified it (#1386).
  7269. from backend.app.utils.printer_models import is_dual_nozzle_model
  7270. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  7271. if is_dual_nozzle:
  7272. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  7273. command = {
  7274. "print": {
  7275. "command": "extrusion_cali_del",
  7276. "sequence_id": seq_id,
  7277. "extruder_id": extruder_id,
  7278. "nozzle_id": nozzle_id,
  7279. "filament_id": filament_id,
  7280. "cali_idx": cali_idx,
  7281. "nozzle_diameter": nozzle_diameter,
  7282. }
  7283. }
  7284. else:
  7285. # X1C/P1/A1 format: include all fields like the set command
  7286. # The delete command structure should match what set uses
  7287. command = {
  7288. "print": {
  7289. "command": "extrusion_cali_del",
  7290. "sequence_id": seq_id,
  7291. "filament_id": filament_id,
  7292. "cali_idx": cali_idx,
  7293. "setting_id": setting_id if setting_id else "",
  7294. "nozzle_diameter": nozzle_diameter,
  7295. "nozzle_id": nozzle_id,
  7296. "extruder_id": extruder_id,
  7297. }
  7298. }
  7299. command_json = json.dumps(command)
  7300. logger.info(
  7301. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  7302. )
  7303. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  7304. # QoS 1 for reliable delivery (at least once)
  7305. self._publish_cali_write(command, seq_id)
  7306. return seq_id
  7307. # =========================================================================
  7308. # Printer Control Commands
  7309. # =========================================================================
  7310. def pause_print(self) -> bool:
  7311. """Pause the current print job."""
  7312. if not self._client or not self.state.connected:
  7313. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  7314. return False
  7315. command = {"print": {"command": "pause", "sequence_id": "0"}}
  7316. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7317. logger.info("[%s] Sent pause print command", self.serial_number)
  7318. return True
  7319. def resume_print(self) -> bool:
  7320. """Resume a paused print job."""
  7321. if not self._client or not self.state.connected:
  7322. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  7323. return False
  7324. command = {"print": {"command": "resume", "sequence_id": "0"}}
  7325. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7326. logger.info("[%s] Sent resume print command", self.serial_number)
  7327. return True
  7328. def clear_hms_errors(self) -> bool:
  7329. """Clear HMS/print errors on the printer and locally."""
  7330. if not self._client or not self.state.connected:
  7331. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  7332. return False
  7333. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  7334. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7335. self.state.hms_errors = []
  7336. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  7337. return True
  7338. def _handle_skip_objects_answer(self, print_data: dict) -> None:
  7339. """The printer's answer to skip_objects: a refusal is logged and the
  7340. objects are no longer shown as skipped."""
  7341. obj_list = self._skip_commands.pop(str(print_data.get("sequence_id", "")), None)
  7342. result = str(print_data.get("result", "") or "").lower()
  7343. if obj_list is None or result in ("", "success"):
  7344. return
  7345. logger.error(
  7346. "[%s] Printer refused skipping objects %s: result=%s reason=%s",
  7347. self.serial_number,
  7348. obj_list,
  7349. print_data.get("result"),
  7350. print_data.get("reason", ""),
  7351. )
  7352. for oid in obj_list:
  7353. self._unconfirmed_skips.pop(oid, None)
  7354. self.state.skipped_objects = [oid for oid in self.state.skipped_objects if oid not in obj_list]
  7355. def _check_unconfirmed_skips(self) -> None:
  7356. """Log, once, a skip the printer's s_obj list never showed."""
  7357. if not self._unconfirmed_skips:
  7358. return
  7359. if self.state.state not in ("RUNNING", "PAUSE"):
  7360. # The print ended; its skips are moot.
  7361. self._unconfirmed_skips.clear()
  7362. self._skip_commands.clear()
  7363. return
  7364. now = time.monotonic()
  7365. # A copy: skip_objects adds to the dict from the event loop while this
  7366. # runs on the MQTT thread.
  7367. pending = list(self._unconfirmed_skips.items())
  7368. expired = [oid for oid, sent_at in pending if now - sent_at > SKIP_CONFIRM_TIMEOUT_S]
  7369. if not expired:
  7370. return
  7371. logger.error(
  7372. "[%s] Printer did not confirm skipping objects %s within %.0fs; they may still be printed",
  7373. self.serial_number,
  7374. sorted(expired),
  7375. SKIP_CONFIRM_TIMEOUT_S,
  7376. )
  7377. for oid in expired:
  7378. self._unconfirmed_skips.pop(oid, None)
  7379. def skip_objects(self, object_ids: list[int]) -> bool:
  7380. """Skip specific objects during a print.
  7381. This command tells the printer to skip printing the specified objects.
  7382. The object IDs come from the slice_info.config file in the 3MF.
  7383. Args:
  7384. object_ids: List of identify_id values from slice_info.config
  7385. Returns:
  7386. True if command was sent, False otherwise
  7387. """
  7388. if not self._client or not self.state.connected:
  7389. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  7390. return False
  7391. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  7392. logger.warning(
  7393. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  7394. )
  7395. return False
  7396. if not object_ids:
  7397. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  7398. return False
  7399. # Validate all IDs are integers
  7400. try:
  7401. obj_list = [int(oid) for oid in object_ids]
  7402. except (ValueError, TypeError) as e:
  7403. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  7404. return False
  7405. self._sequence_id += 1
  7406. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  7407. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7408. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  7409. sent_at = time.monotonic()
  7410. for oid in obj_list:
  7411. self._unconfirmed_skips.setdefault(oid, sent_at)
  7412. self._skip_commands[str(self._sequence_id)] = obj_list
  7413. # Track skipped objects in state
  7414. for oid in obj_list:
  7415. if oid not in self.state.skipped_objects:
  7416. self.state.skipped_objects.append(oid)
  7417. return True
  7418. def send_gcode(self, gcode: str) -> bool:
  7419. """Send G-code command(s) to the printer.
  7420. Multiple commands can be separated by newlines.
  7421. Args:
  7422. gcode: G-code command(s) to send
  7423. Returns:
  7424. True if command was sent, False otherwise
  7425. """
  7426. if not self._client or not self.state.connected:
  7427. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  7428. return False
  7429. self._sequence_id += 1
  7430. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  7431. # Use QoS 1 for reliable delivery (at least once)
  7432. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7433. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  7434. return True
  7435. def set_bed_temperature(self, target: int) -> bool:
  7436. """Set the bed target temperature.
  7437. Args:
  7438. target: Target temperature in Celsius (0 to turn off)
  7439. Returns:
  7440. True if command was sent, False otherwise
  7441. """
  7442. return self.send_gcode(f"M140 S{target}")
  7443. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  7444. """Set the nozzle target temperature.
  7445. Args:
  7446. target: Target temperature in Celsius (0 to turn off)
  7447. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  7448. Returns:
  7449. True if command was sent, False otherwise
  7450. """
  7451. # Use M104 for non-blocking
  7452. # Always use T parameter for H2D compatibility
  7453. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  7454. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  7455. # Track it locally so we can display it correctly
  7456. if result and nozzle == 1:
  7457. self.state.temperatures["nozzle_target"] = float(target)
  7458. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  7459. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  7460. return result
  7461. def set_chamber_temperature(self, target: int) -> bool:
  7462. """Set the chamber target temperature.
  7463. Args:
  7464. target: Target temperature in Celsius (0 to turn off heating)
  7465. Returns:
  7466. True if command was sent, False otherwise
  7467. """
  7468. # The H3C's heater only runs in the airduct's heating mode.
  7469. from backend.app.utils.printer_models import chamber_heater_needs_heating_mode
  7470. if target > 0 and self.state.airduct_mode != 1 and chamber_heater_needs_heating_mode(self.model):
  7471. logger.info(
  7472. "[%s] Chamber target %s°C: switching the airduct to heating mode first (H3C)",
  7473. self.serial_number,
  7474. target,
  7475. )
  7476. self.set_airduct_mode("heating")
  7477. # M141 sets chamber temperature
  7478. result = self.send_gcode(f"M141 S{target}")
  7479. # Track chamber target locally (MQTT reports encoded values that need filtering)
  7480. if result:
  7481. self.state.temperatures["chamber_target"] = float(target)
  7482. self.state.temperatures["_chamber_target_set_time"] = time.time()
  7483. # Update heating state immediately based on new target
  7484. current_temp = self.state.temperatures.get("chamber", 0)
  7485. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  7486. logger.info(
  7487. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  7488. )
  7489. return result
  7490. def set_print_speed(self, mode: int) -> bool:
  7491. """Set the print speed mode.
  7492. Args:
  7493. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  7494. Returns:
  7495. True if command was sent, False otherwise
  7496. """
  7497. if not self._client or not self.state.connected:
  7498. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  7499. return False
  7500. if mode not in (1, 2, 3, 4):
  7501. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  7502. return False
  7503. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  7504. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7505. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  7506. return True
  7507. def set_fan_speed(self, fan: int, speed: int) -> bool:
  7508. """Set fan speed.
  7509. Args:
  7510. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=second auxiliary).
  7511. Index 10 is the second auxiliary part cooling fan: left on the P2S
  7512. (an accessory kit), right on the X2D, where 2 is the left (#3373)
  7513. (airduct part id 10); Bambu's official machine profiles drive it with
  7514. "M106 P10" in start/layer-change gcode.
  7515. speed: Speed 0-255 (0=off, 255=full)
  7516. Returns:
  7517. True if command was sent, False otherwise
  7518. """
  7519. if fan not in (1, 2, 3, 10):
  7520. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  7521. return False
  7522. speed = max(0, min(255, speed)) # Clamp to 0-255
  7523. return self.send_gcode(f"M106 P{fan} S{speed}")
  7524. def set_airduct_mode(self, mode: str) -> bool:
  7525. """Set air conditioning mode (cooling or heating).
  7526. Args:
  7527. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  7528. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  7529. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  7530. closes top exhaust flap
  7531. Returns:
  7532. True if command was sent, False otherwise
  7533. """
  7534. if not self._client or not self.state.connected:
  7535. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  7536. return False
  7537. self._sequence_id += 1
  7538. mode_id = 0 if mode == "cooling" else 1
  7539. command = {
  7540. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  7541. }
  7542. # Use QoS 1 for reliable delivery
  7543. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7544. logger.info(
  7545. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  7546. )
  7547. return True
  7548. def set_chamber_light(self, on: bool) -> bool:
  7549. """Turn chamber light on or off.
  7550. Args:
  7551. on: True to turn on, False to turn off
  7552. Returns:
  7553. True if command was sent, False otherwise
  7554. """
  7555. if not self._client or not self.state.connected:
  7556. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  7557. return False
  7558. mode = "on" if on else "off"
  7559. # Control both chamber lights (some printers like H2D have two)
  7560. for led_node in ["chamber_light", "chamber_light2"]:
  7561. self._sequence_id += 1
  7562. command = {
  7563. "system": {
  7564. "command": "ledctrl",
  7565. "led_node": led_node,
  7566. "led_mode": mode,
  7567. "led_on_time": 500,
  7568. "led_off_time": 500,
  7569. "loop_times": 0,
  7570. "interval_time": 0,
  7571. "sequence_id": str(self._sequence_id),
  7572. }
  7573. }
  7574. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7575. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  7576. return True
  7577. def select_extruder(self, extruder: int) -> bool:
  7578. """Select the active extruder for dual-nozzle printers (H2D).
  7579. Args:
  7580. extruder: Extruder index (0=right, 1=left for H2D)
  7581. Returns:
  7582. True if command was sent, False otherwise
  7583. """
  7584. if extruder not in (0, 1):
  7585. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  7586. return False
  7587. if not self._client or not self.state.connected:
  7588. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  7589. return False
  7590. # H2D extruder switching via select_extruder command
  7591. # Command format captured from OrcaSlicer:
  7592. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  7593. # extruder_index: 0 = RIGHT, 1 = LEFT
  7594. self._sequence_id += 1
  7595. command = {
  7596. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  7597. }
  7598. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7599. logger.info(
  7600. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  7601. )
  7602. return True
  7603. def _ams_unit(self, ams_id: int) -> dict | None:
  7604. """AMS unit ``ams_id`` in the last status, or None."""
  7605. for unit in self.state.raw_data.get("ams") or []:
  7606. if isinstance(unit, dict) and _mqtt_int(unit.get("id")) == ams_id:
  7607. return unit
  7608. return None
  7609. def _rack_tray(self, tray_id: int | None) -> tuple[int, int, dict | None] | None:
  7610. """``(ams_id, slot, tray)`` of a rack AMS slot's global tray id (the AMS 3H's 28-36), else None."""
  7611. if not isinstance(tray_id, int):
  7612. return None
  7613. located = self.tray_layout.rack_slot(tray_id)
  7614. if located is None:
  7615. return None
  7616. ams_id, slot = located
  7617. unit = self._ams_unit(ams_id) or {}
  7618. tray = next(
  7619. (t for t in unit.get("tray") or [] if isinstance(t, dict) and _mqtt_int(t.get("id")) == slot),
  7620. None,
  7621. )
  7622. return ams_id, slot, tray
  7623. def rack_tray_has_filament(self, tray_id: int) -> bool:
  7624. """Whether rack AMS slot ``tray_id`` reports a filament type, which Studio requires before a Load.
  7625. The AMS 3H registers a spool only once it has pulled the filament in at the inlet.
  7626. """
  7627. rack = self._rack_tray(tray_id)
  7628. return bool(rack and rack[2] and rack[2].get("tray_type"))
  7629. @staticmethod
  7630. def _tray_mid_temp(tray: dict | None) -> int:
  7631. """Midpoint of a tray's nozzle_temp_min/max, or -1 (as Studio's ams_change_filament)."""
  7632. if tray is None:
  7633. return -1
  7634. low, high = _mqtt_int(tray.get("nozzle_temp_min")), _mqtt_int(tray.get("nozzle_temp_max"))
  7635. return (low + high) // 2 if low and high and low > 0 and high > 0 else -1
  7636. def _rack_change_filament(self, tray_id: int, load: bool) -> bool:
  7637. """Load AMS 3H slot ``tray_id`` into its own hotend, or unload that hotend.
  7638. As Studio 02.09 sends it for a direct-connected rack (PageFilament.cpp):
  7639. load targets 32 at slot k, unload 255 at slot 255 - k (the feeder to
  7640. retract). The AMS 3H can't rewind: an unload ends with a hand pull.
  7641. """
  7642. client = self._client
  7643. rack = self._rack_tray(tray_id)
  7644. if client is None or rack is None:
  7645. return False
  7646. ams_id, slot, tray = rack
  7647. on_head = self._rack_tray(self.state.tray_now)
  7648. self._sequence_id += 1
  7649. command = {
  7650. "print": {
  7651. "command": "ams_change_filament",
  7652. "sequence_id": str(self._sequence_id),
  7653. "ams_id": ams_id,
  7654. "target": ams_id if load else 255,
  7655. "slot_id": slot if load else 255 - slot,
  7656. "extruder_id": 0,
  7657. "curr_temp": self._tray_mid_temp(on_head[2] if on_head else None),
  7658. "tar_temp": self._tray_mid_temp(tray),
  7659. }
  7660. }
  7661. command_json = json.dumps(command)
  7662. logger.info(
  7663. "[%s] Publishing ams_change_filament (%s, AMS 3H slot %d): %s",
  7664. self.serial_number,
  7665. "load" if load else "unload",
  7666. slot + 1,
  7667. command_json,
  7668. )
  7669. client.publish(self.topic_publish, command_json, qos=1)
  7670. if load:
  7671. self.state.pending_tray_target = tray_id
  7672. self.state.pending_tray_target_at = time.monotonic()
  7673. else:
  7674. self.state.pending_tray_target = None
  7675. self.state.pending_tray_target_at = None
  7676. return True
  7677. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  7678. """Load filament from a specific AMS tray.
  7679. Args:
  7680. tray_id: Global tray ID — 0..15 for AMS slots, 24..27 for the A2L
  7681. AMS-Lite, 128..135 for an AMS-HT (its unit id), 254 for external spool
  7682. (single-external printers and Ext-L on dual-nozzle H2D),
  7683. 255 for Ext-R on dual-nozzle H2D.
  7684. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  7685. Sent only when given, matching BambuStudio: ``extruder_id`` is
  7686. an optional field on ``ams_change_filament``
  7687. (``DeviceManager::command_ams_change_filament``) and Studio
  7688. omits it unless a Filament Track Switch is installed. Without a
  7689. switch the firmware derives the hotend from the AMS's own
  7690. extruder binding and an explicit value is redundant; *with* one
  7691. every AMS reports 0xE and is bound to a switch inlet instead, so
  7692. the firmware has nothing to derive from and the load silently
  7693. does nothing until we name the hotend.
  7694. Returns:
  7695. True if command was sent, False otherwise
  7696. """
  7697. if not self._client or not self.state.connected:
  7698. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  7699. return False
  7700. if self.tray_layout.rack_units:
  7701. # Only an AMS 3H slot can be loaded: an external input or an AMS-B
  7702. # can't feed itself (Studio's CanAutoFeed).
  7703. rack = self._rack_tray(tray_id)
  7704. if rack is None or self.tray_layout.ams_type(rack[0]) != AmsType.ZMULTI_A:
  7705. logger.warning("[%s] Load: tray %s is not an AMS 3H slot", self.serial_number, tray_id)
  7706. return False
  7707. if not self.rack_tray_has_filament(tray_id):
  7708. logger.warning("[%s] Load: AMS 3H slot %d has no filament", self.serial_number, rack[1] + 1)
  7709. return False
  7710. return self._rack_change_filament(tray_id, load=True)
  7711. # Build the ams_change_filament command. Encoding differs by target type:
  7712. # - AMS slots (0..15, A2L 24..27, AMS-HT 128..135): see
  7713. # change_filament_wire_ids; curr/tar_temp = -1.
  7714. # - External spool (tray_id=254): legacy capture from a single-extruder
  7715. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  7716. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  7717. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  7718. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  7719. self._sequence_id += 1
  7720. wire_target = tray_id
  7721. if tray_id == 255:
  7722. ams_id = 255
  7723. slot_id = 0 # extruder index for the right nozzle
  7724. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  7725. if right_temp < 180:
  7726. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  7727. curr_temp = right_temp
  7728. tar_temp = right_temp
  7729. elif tray_id == 254:
  7730. ams_id = 255
  7731. slot_id = 254
  7732. curr_temp = -1
  7733. tar_temp = -1
  7734. else:
  7735. # A regular AMS, the A2L AMS-Lite (physical unit 16) or an AMS-HT
  7736. # (128-135), as BambuStudio addresses each.
  7737. ams_id, slot_id, wire_target = change_filament_wire_ids(tray_id, self.tray_layout)
  7738. curr_temp = -1
  7739. tar_temp = -1
  7740. command = {
  7741. "print": {
  7742. "command": "ams_change_filament",
  7743. "sequence_id": str(self._sequence_id),
  7744. "ams_id": ams_id,
  7745. "slot_id": slot_id,
  7746. "target": wire_target,
  7747. "curr_temp": curr_temp,
  7748. "tar_temp": tar_temp,
  7749. }
  7750. }
  7751. if extruder_id is not None:
  7752. command["print"]["extruder_id"] = int(extruder_id)
  7753. command_json = json.dumps(command)
  7754. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  7755. self._client.publish(self.topic_publish, command_json, qos=1)
  7756. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  7757. # Track this load request for H2D dual-nozzle disambiguation
  7758. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  7759. self.state.pending_tray_target = tray_id
  7760. self.state.pending_tray_target_at = time.monotonic()
  7761. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  7762. return True
  7763. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  7764. """Unload filament, optionally naming the slot to unload.
  7765. Args:
  7766. tray_id: Global tray ID of the slot being unloaded. When given, the
  7767. command is addressed to that slot's AMS and is only sent if an
  7768. extruder is actually fed from it — BambuStudio does the same
  7769. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  7770. nothing when none matches). When omitted, the pre-existing
  7771. behaviour is kept: unload whatever ``tray_now`` names.
  7772. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  7773. machine with both hotends loaded it names only one of them and an
  7774. unaddressed unload picks that one regardless of which slot the operator
  7775. clicked. Passing the slot is what makes the two hotends distinguishable.
  7776. Returns:
  7777. True if command was sent, False otherwise
  7778. """
  7779. if not self._client or not self.state.connected:
  7780. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  7781. return False
  7782. if self.tray_layout.rack_units:
  7783. # The hotend of the named AMS 3H slot, else of the one on the toolhead.
  7784. source = tray_id if tray_id is not None else self.state.tray_now
  7785. if self._rack_tray(source) is None:
  7786. logger.warning("[%s] Unload: no AMS 3H slot to unload (tray %s)", self.serial_number, source)
  7787. return False
  7788. return self._rack_change_filament(source, load=False)
  7789. # Get the currently loaded tray info
  7790. tray_now = self.state.tray_now
  7791. source_tray = tray_now if tray_id is None else tray_id
  7792. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  7793. # Determine source ams_id for the unload command
  7794. if source_tray == 255 or source_tray == 254:
  7795. ams_id = 255 # No filament or external spool
  7796. else:
  7797. # Source AMS: the A2L AMS-Lite as physical 16, an AMS-HT as its unit id.
  7798. ams_id = change_filament_wire_ids(source_tray, self.tray_layout)[0]
  7799. # Refuse an addressed unload of a slot no hotend is holding — but only on
  7800. # a printer that has more than one hotend, which is the only case the
  7801. # check exists for. With one hotend there is nothing to disambiguate:
  7802. # tray_now already names the loaded slot exactly, and running the check
  7803. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  7804. # very likely does, but single-nozzle machines do report the block —
  7805. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  7806. # an X1C on the maintainer's own network sends `device.extruder` — and
  7807. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  7808. # would 409 every unload on every X1C, P1S and A1.
  7809. #
  7810. # Gated on the runtime flag rather than on len(extruder_slots), which is
  7811. # rebuilt from each payload's array and would flip the check off for any
  7812. # frame that carried a short one; and deliberately not on
  7813. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  7814. # one single-nozzle machine as dual (#1386) — the false positive there is
  7815. # exactly the case this gate exists to keep out.
  7816. #
  7817. # The external spool is excluded for a different reason: 254/255 are not
  7818. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  7819. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  7820. local_slot = change_filament_wire_ids(tray_id, self.tray_layout)[1]
  7821. holder = next(
  7822. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  7823. None,
  7824. )
  7825. if holder is None:
  7826. logger.info(
  7827. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  7828. self.serial_number,
  7829. ams_id,
  7830. local_slot,
  7831. )
  7832. return False
  7833. logger.info(
  7834. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7835. )
  7836. # Command format from BambuStudio traffic capture:
  7837. # - No extruder_id field
  7838. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7839. # - slot_id=255 and target=255 for unload
  7840. # Get current nozzle temperature for the unload command
  7841. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7842. if nozzle_temp < 180:
  7843. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7844. self._sequence_id += 1
  7845. command = {
  7846. "print": {
  7847. "command": "ams_change_filament",
  7848. "sequence_id": str(self._sequence_id),
  7849. "ams_id": ams_id,
  7850. "slot_id": 255, # 255 = unload marker
  7851. "target": 255, # 255 = unload destination
  7852. "curr_temp": nozzle_temp,
  7853. "tar_temp": nozzle_temp,
  7854. }
  7855. }
  7856. command_json = json.dumps(command)
  7857. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7858. self._client.publish(self.topic_publish, command_json, qos=1)
  7859. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7860. # Clear tracked load request since we're unloading
  7861. self.state.pending_tray_target = None
  7862. self.state.pending_tray_target_at = None
  7863. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7864. return True
  7865. def ams_control(self, action: str) -> bool:
  7866. """Control AMS operations.
  7867. Args:
  7868. action: "resume", "reset", or "pause"
  7869. Returns:
  7870. True if command was sent, False otherwise
  7871. """
  7872. if not self._client or not self.state.connected:
  7873. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7874. return False
  7875. if action not in ("resume", "reset", "pause"):
  7876. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7877. return False
  7878. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7879. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7880. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7881. return True
  7882. async def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7883. """Trigger RFID re-read for a specific AMS tray.
  7884. Sends ``ams_get_rfid`` and waits for the printer's answer. Firmware
  7885. that refuses it (#3206: X1Plus on base 01.08.02.00 answers ``FAIL`` /
  7886. ``ERROR STATE``) gets the legacy ``M620 R<global tray>`` gcode instead,
  7887. which is what Bambu Studio sends to printers without the new protocol.
  7888. The fallback only follows an explicit refusal, so firmware that takes
  7889. ``ams_get_rfid`` never sees it.
  7890. Success means the printer accepted the request, not that the tag was
  7891. read: the slot updating in the next push is the only proof of that.
  7892. Args:
  7893. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7894. tray_id: Tray ID within the AMS (0-3)
  7895. Returns:
  7896. Tuple of (success, message)
  7897. """
  7898. if not self._client or not self.state.connected:
  7899. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7900. return False, "Printer not connected"
  7901. # Check if filament is currently loaded (tray_now != 255)
  7902. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7903. tray_now = self.state.tray_now
  7904. if tray_now != 255:
  7905. # Decode which tray is loaded for the message
  7906. layout = self.tray_layout
  7907. if tray_now == 254:
  7908. loaded_tray = "external spool"
  7909. elif (rack := layout.rack_slot(tray_now)) is not None:
  7910. loaded_tray = f"{unit_label(rack[0], layout.ams_type(rack[0]))} slot {rack[1] + 1}"
  7911. elif tray_now >= 0 and tray_now < 128:
  7912. loaded_ams, loaded_slot = layout.slot_key(tray_now)
  7913. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7914. else:
  7915. loaded_tray = f"tray {tray_now}"
  7916. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7917. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7918. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7919. wire_ams_id, wire_slot_id = ams_id, tray_id
  7920. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7921. wire_ams_id, wire_slot_id, _ = _a2l
  7922. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7923. refused = await self._send_rfid_command(
  7924. {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id}
  7925. )
  7926. if refused is None:
  7927. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7928. # M620 R only for what Bambu Studio sends it to: a model older than the
  7929. # newer protocol, on one of the four regular AMS units (the only ones
  7930. # with a legacy global tray index). Never during a job either: a
  7931. # gcode_line would be executed inside the running print.
  7932. from backend.app.utils.printer_models import uses_legacy_rfid_refresh
  7933. if (
  7934. not 0 <= wire_ams_id <= 3
  7935. or not uses_legacy_rfid_refresh(self.model)
  7936. or self.state.state in _ACTIVE_PRINT_STATES
  7937. ):
  7938. return False, f"Printer refused the RFID refresh: {refused}"
  7939. logger.info(
  7940. "[%s] ams_get_rfid refused (%s), falling back to M620 R%s",
  7941. self.serial_number,
  7942. refused,
  7943. legacy_tray_index(wire_ams_id, wire_slot_id),
  7944. )
  7945. legacy_refused = await self._send_rfid_command(
  7946. {"command": "gcode_line", "param": f"M620 R{legacy_tray_index(wire_ams_id, wire_slot_id)}\n"}
  7947. )
  7948. if legacy_refused is None:
  7949. return True, f"Refreshing AMS {ams_id} tray {tray_id} (legacy command)"
  7950. return False, f"Printer refused the RFID refresh: {legacy_refused}"
  7951. # The answer to ams_get_rfid was measured at 11ms in #3206's capture.
  7952. _rfid_ack_timeout: float = 3.0
  7953. async def _send_rfid_command(self, print_command: dict) -> str | None:
  7954. """Publish one RFID refresh command and wait for the printer's answer.
  7955. Returns the printer's reason when it answered ``FAIL``, else None.
  7956. No answer within ``_rfid_ack_timeout`` counts as accepted, because
  7957. silence is not evidence of refusal and older firmware may not answer
  7958. at all.
  7959. """
  7960. timeout = self._rfid_ack_timeout
  7961. self._sequence_id += 1
  7962. seq_id = str(self._sequence_id)
  7963. command = {"print": {**print_command, "sequence_id": seq_id}}
  7964. self._pending_rfid_acks[seq_id] = None
  7965. try:
  7966. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7967. deadline = time.monotonic() + timeout
  7968. while time.monotonic() < deadline:
  7969. ack = self._pending_rfid_acks.get(seq_id)
  7970. if ack is not None:
  7971. if str(ack.get("result", "")).lower() == "fail":
  7972. return str(ack.get("reason", "") or "") or "printer reported failure"
  7973. return None
  7974. await asyncio.sleep(0.05)
  7975. finally:
  7976. self._pending_rfid_acks.pop(seq_id, None)
  7977. logger.info(
  7978. "[%s] No answer to %s seq=%s within %.1fs", self.serial_number, print_command["command"], seq_id, timeout
  7979. )
  7980. return None
  7981. def ams_set_filament_setting(
  7982. self,
  7983. ams_id: int,
  7984. tray_id: int,
  7985. tray_info_idx: str,
  7986. tray_type: str,
  7987. tray_sub_brands: str,
  7988. tray_color: str,
  7989. nozzle_temp_min: int,
  7990. nozzle_temp_max: int,
  7991. setting_id: str = "",
  7992. ) -> bool:
  7993. """Set AMS tray filament settings (type, color, temperature).
  7994. Note: K value is set separately via extrusion_cali_sel command.
  7995. Args:
  7996. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7997. tray_id: Tray ID within the AMS (0-3)
  7998. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7999. tray_type: Filament type (e.g., "PLA", "PETG")
  8000. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  8001. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  8002. nozzle_temp_min: Minimum nozzle temperature
  8003. nozzle_temp_max: Maximum nozzle temperature
  8004. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  8005. Returns:
  8006. True if command was sent, False otherwise
  8007. """
  8008. if not self._client or not self.state.connected:
  8009. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  8010. return False
  8011. # Calculate mqtt IDs based on AMS type.
  8012. # External-spool convention verified against a BambuStudio→X1C packet capture
  8013. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  8014. # *global* tray index in `tray_id`, not a local position within the virtual
  8015. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  8016. # is what the original code was matching — but the request and response
  8017. # use different semantics for that field. Sending `tray_id: 0` is what
  8018. # the P1S in #1279 rejected with `result: "fail"`.
  8019. if ams_id == 255:
  8020. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8021. if len(vt_tray) > 1:
  8022. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8023. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  8024. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  8025. # captured Studio→H2D exchange confirms the correct value.
  8026. mqtt_ams_id = external_tray_id(tray_id)
  8027. mqtt_tray_id = 0
  8028. else:
  8029. # Single external slot (X1C, P1S, A1): global tray_id=254.
  8030. mqtt_ams_id = 255
  8031. mqtt_tray_id = 254
  8032. slot_id = 0
  8033. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8034. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  8035. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  8036. mqtt_ams_id, slot_id, _ = _a2l
  8037. mqtt_tray_id = slot_id
  8038. elif self._rack_ams_type(ams_id) is not None:
  8039. # AMS 3H: unit 32 with its slot 0-8 in tray_id and slot_id (verified).
  8040. mqtt_ams_id = ams_id
  8041. mqtt_tray_id = slot_id = tray_id
  8042. elif ams_id <= 3:
  8043. mqtt_ams_id = ams_id
  8044. mqtt_tray_id = tray_id
  8045. slot_id = tray_id
  8046. else:
  8047. # AMS-HT: single tray per unit
  8048. mqtt_ams_id = ams_id
  8049. mqtt_tray_id = tray_id
  8050. slot_id = 0
  8051. command = {
  8052. "print": {
  8053. "command": "ams_filament_setting",
  8054. "ams_id": mqtt_ams_id,
  8055. "tray_id": mqtt_tray_id,
  8056. "slot_id": slot_id,
  8057. "tray_info_idx": tray_info_idx,
  8058. "tray_type": tray_type,
  8059. "tray_sub_brands": tray_sub_brands,
  8060. # UPPERCASE, always: lowercase hex is silently read as zeros by
  8061. # P1S firmware and acknowledged as a success (#2987).
  8062. "tray_color": wire_tray_color(tray_color),
  8063. "nozzle_temp_min": nozzle_temp_min,
  8064. "nozzle_temp_max": nozzle_temp_max,
  8065. "sequence_id": "0",
  8066. }
  8067. }
  8068. # Include setting_id if provided (helps slicer show correct profile)
  8069. if setting_id:
  8070. command["print"]["setting_id"] = setting_id
  8071. command_json = json.dumps(command)
  8072. logger.info(
  8073. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  8074. )
  8075. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  8076. self._client.publish(self.topic_publish, command_json, qos=1)
  8077. self._last_ams_cmd_time = time.monotonic()
  8078. return True
  8079. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  8080. """Reset an AMS slot to empty/unconfigured state.
  8081. Args:
  8082. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  8083. tray_id: Tray ID within the AMS (0-3)
  8084. Returns:
  8085. True if command was sent, False otherwise
  8086. """
  8087. if not self._client or not self.state.connected:
  8088. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  8089. return False
  8090. # Calculate mqtt IDs based on AMS type — same convention as
  8091. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  8092. if ams_id == 255:
  8093. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8094. if len(vt_tray) > 1:
  8095. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8096. mqtt_ams_id = external_tray_id(tray_id)
  8097. mqtt_tray_id = 0
  8098. else:
  8099. # Single external slot (X1C, P1S, A1): global tray_id=254.
  8100. mqtt_ams_id = 255
  8101. mqtt_tray_id = 254
  8102. slot_id = 0
  8103. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8104. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  8105. mqtt_ams_id, slot_id, _ = _a2l
  8106. mqtt_tray_id = slot_id
  8107. elif self._rack_ams_type(ams_id) is not None:
  8108. # AMS 3H: unit 32 with its slot 0-8 (see ams_set_filament_setting).
  8109. mqtt_ams_id = ams_id
  8110. mqtt_tray_id = slot_id = tray_id
  8111. elif ams_id <= 3:
  8112. mqtt_ams_id = ams_id
  8113. mqtt_tray_id = tray_id
  8114. slot_id = tray_id
  8115. else:
  8116. # AMS-HT: single tray per unit
  8117. mqtt_ams_id = ams_id
  8118. mqtt_tray_id = tray_id
  8119. slot_id = 0
  8120. command = {
  8121. "print": {
  8122. "command": "ams_filament_setting",
  8123. "ams_id": mqtt_ams_id,
  8124. "tray_id": mqtt_tray_id,
  8125. "slot_id": slot_id,
  8126. "tray_info_idx": "",
  8127. "tray_type": "",
  8128. "tray_sub_brands": "",
  8129. "tray_color": "00000000",
  8130. "nozzle_temp_min": 0,
  8131. "nozzle_temp_max": 0,
  8132. "sequence_id": "0",
  8133. }
  8134. }
  8135. command_json = json.dumps(command)
  8136. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  8137. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  8138. self._client.publish(self.topic_publish, command_json, qos=1)
  8139. self._last_ams_cmd_time = time.monotonic()
  8140. return True
  8141. def extrusion_cali_sel(
  8142. self,
  8143. ams_id: int,
  8144. tray_id: int,
  8145. cali_idx: int,
  8146. filament_id: str,
  8147. nozzle_diameter: str = "0.4",
  8148. ) -> bool:
  8149. """Set calibration profile (K value) for an AMS slot.
  8150. This command selects a K profile from the printer's calibration list.
  8151. Use cali_idx=-1 to use the default K value (0.020).
  8152. Note: Do NOT send setting_id in this command — BambuStudio never includes
  8153. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  8154. Args:
  8155. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  8156. tray_id: Tray ID within the AMS (0-3)
  8157. cali_idx: Calibration profile index (-1 for default)
  8158. filament_id: Filament preset ID (same as tray_info_idx)
  8159. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8160. Returns:
  8161. True if command was sent, False otherwise
  8162. """
  8163. if not self._client or not self.state.connected:
  8164. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  8165. return False
  8166. # Calculate mqtt IDs based on AMS type.
  8167. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  8168. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  8169. if ams_id == 255:
  8170. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  8171. # ams_filament_setting which uses LOCAL tray_id=0).
  8172. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8173. if len(vt_tray) > 1:
  8174. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8175. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  8176. mqtt_ams_id = external_tray_id(tray_id)
  8177. mqtt_tray_id = external_tray_id(tray_id)
  8178. else:
  8179. # Single external slot (X1C, P1S, A1): global tray_id=254
  8180. mqtt_ams_id = 254
  8181. mqtt_tray_id = 254
  8182. slot_id = 0
  8183. elif self._rack_ams_type(ams_id) is not None:
  8184. # AMS 3H: unit 32, slot k in tray_id and slot_id ({32, 8, 8} verified).
  8185. mqtt_ams_id = ams_id
  8186. mqtt_tray_id = slot_id = tray_id
  8187. elif ams_id <= 3:
  8188. mqtt_ams_id = ams_id
  8189. mqtt_tray_id = legacy_tray_index(ams_id, tray_id)
  8190. slot_id = tray_id
  8191. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8192. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  8193. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  8194. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  8195. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  8196. elif is_ams_ht_id(ams_id):
  8197. mqtt_ams_id = ams_id
  8198. mqtt_tray_id = tray_id
  8199. slot_id = 0
  8200. else:
  8201. mqtt_ams_id = ams_id
  8202. mqtt_tray_id = tray_id
  8203. slot_id = 0
  8204. command = {
  8205. "print": {
  8206. "command": "extrusion_cali_sel",
  8207. "cali_idx": cali_idx,
  8208. "filament_id": filament_id,
  8209. "nozzle_diameter": nozzle_diameter,
  8210. "ams_id": mqtt_ams_id,
  8211. "tray_id": mqtt_tray_id,
  8212. "slot_id": slot_id,
  8213. "sequence_id": "0",
  8214. }
  8215. }
  8216. command_json = json.dumps(command)
  8217. logger.info(
  8218. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  8219. )
  8220. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  8221. self._client.publish(self.topic_publish, command_json, qos=1)
  8222. return True
  8223. def extrusion_cali_set(
  8224. self,
  8225. tray_id: int,
  8226. k_value: float,
  8227. nozzle_diameter: str = "0.4",
  8228. nozzle_temp: int = 220,
  8229. filament_id: str = "",
  8230. setting_id: str = "",
  8231. name: str = "",
  8232. cali_idx: int = -1,
  8233. ) -> bool:
  8234. """Directly set K value (pressure advance) for a tray.
  8235. Uses the filaments array format required by current firmware.
  8236. Args:
  8237. tray_id: Global tray ID (ams_id * 4 + slot)
  8238. k_value: Pressure advance K value (e.g., 0.020)
  8239. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8240. nozzle_temp: Nozzle temperature for calibration reference
  8241. filament_id: Filament preset ID (e.g., "GFA02")
  8242. setting_id: Setting ID (e.g., "GFSA02_07")
  8243. name: Profile display name
  8244. cali_idx: Calibration index (-1 for new)
  8245. Returns:
  8246. True if command was sent, False otherwise
  8247. """
  8248. if not self._client or not self.state.connected:
  8249. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  8250. return False
  8251. # Was reusing the previous command's id — harmless while nothing
  8252. # correlated on it, but the printer echoes sequence_id back and the
  8253. # K-profile write path now matches acks by it (#2718).
  8254. self._sequence_id += 1
  8255. nozzle_id = f"HS00-{nozzle_diameter}"
  8256. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  8257. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  8258. # stays 0 (hardcoded, as for every other unit here).
  8259. wire_tray_id = tray_id
  8260. if (
  8261. 0 <= tray_id <= 253
  8262. and (_a2l := a2l_lite_wire_ids(self.tray_layout.slot_key(tray_id)[0], tray_id)) is not None
  8263. ):
  8264. wire_tray_id = _a2l[2]
  8265. filament_entry = {
  8266. "ams_id": 0,
  8267. "cali_idx": cali_idx,
  8268. "extruder_id": 0,
  8269. "filament_id": filament_id,
  8270. "k_value": f"{k_value:.6f}",
  8271. "n_coef": "1.400000",
  8272. "name": name,
  8273. "nozzle_diameter": nozzle_diameter,
  8274. "nozzle_id": nozzle_id,
  8275. "setting_id": setting_id,
  8276. "tray_id": wire_tray_id,
  8277. }
  8278. command = {
  8279. "print": {
  8280. "command": "extrusion_cali_set",
  8281. "filaments": [filament_entry],
  8282. "nozzle_diameter": nozzle_diameter,
  8283. "sequence_id": str(self._sequence_id),
  8284. }
  8285. }
  8286. command_json = json.dumps(command)
  8287. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  8288. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  8289. self._client.publish(self.topic_publish, command_json, qos=1)
  8290. return True
  8291. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  8292. """Dispatch the user's choice from the HMS-error modal as a printer command.
  8293. Args:
  8294. print_error: Canonical hex identifier for the fault — 8 chars for the
  8295. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  8296. (HMSError.full_code). Carried through unchanged from the route.
  8297. Converted to its DECIMAL string form for the `ignore` /
  8298. `idle_ignore` commands' `err` field, which is what the firmware
  8299. actually compares against the active fault. The pre-#1869
  8300. hex-string `err` was silently rejected because the firmware was
  8301. being asked to match `"05008051"` against int 0x05008051
  8302. (= 83918929 decimal) — see BambuStudio's
  8303. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  8304. `std::to_string(int m_error_code)`.
  8305. action: One of HMSAction's string values.
  8306. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  8307. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  8308. shapes; empty string is the no-job-id sentinel.
  8309. Returns False when the MQTT client is offline or when `action` is unknown
  8310. so the route surfaces it as a 4xx rather than a silent no-op.
  8311. """
  8312. if not self._client or not self.state.connected:
  8313. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  8314. return False
  8315. # Always re-push the full state after a command so the modal's underlying
  8316. # status query reflects the new error list (or absence) on the next tick.
  8317. def publish(payload: dict):
  8318. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  8319. self._client.publish(
  8320. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  8321. )
  8322. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  8323. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  8324. # every command_hms_* call). Our route hands us the hex string —
  8325. # convert. Falls back to the raw input if it's not parseable so the
  8326. # firmware can reject it and the route can surface 502 instead of us
  8327. # raising ValueError mid-dispatch.
  8328. try:
  8329. err_decimal = str(int(print_error, 16))
  8330. except ValueError:
  8331. err_decimal = print_error
  8332. def hms_resume():
  8333. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  8334. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  8335. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  8336. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  8337. # shape historically because it works, and changing it without a
  8338. # field test risks regressing a path that the user has confirmed.
  8339. publish(
  8340. {
  8341. "print": {
  8342. "command": "resume",
  8343. "param": "",
  8344. "sequence_id": "0",
  8345. }
  8346. }
  8347. )
  8348. def hms_stop():
  8349. # Same as hms_resume — plain shape, confirmed working by the user
  8350. # for "Stop Printing".
  8351. publish(
  8352. {
  8353. "print": {
  8354. "command": "stop",
  8355. "param": "",
  8356. "sequence_id": "0",
  8357. }
  8358. }
  8359. )
  8360. def hms_ignore_command():
  8361. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  8362. # what the "Ignore this and Resume" button actually publishes.
  8363. # Distinct from `idle_ignore`: this command has the firmware
  8364. # suppress the next re-check of the named fault AND resume the
  8365. # paused print in a single operation. The previous Bambuddy code
  8366. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  8367. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  8368. # the problem, re-check normally" so the firmware re-detected the
  8369. # wrong plate and re-paused with the same code (#1869).
  8370. #
  8371. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  8372. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  8373. # variant of "don't remind next time" lives on `idle_ignore`'s
  8374. # type=1, not as a separate ignore shape.
  8375. publish(
  8376. {
  8377. "print": {
  8378. "command": "ignore",
  8379. "err": err_decimal,
  8380. "param": "reserve",
  8381. "job_id": job_id or "",
  8382. "sequence_id": "0",
  8383. }
  8384. }
  8385. )
  8386. def hms_idle_ignore(persistent: bool = False):
  8387. # `idle_ignore` is BambuStudio's "dismiss this warning without
  8388. # resuming" command for non-pause warnings — what
  8389. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  8390. # type=0 dismisses once, type=1 suppresses the same warning
  8391. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  8392. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  8393. # NOT via the resume-bearing `ignore` command.
  8394. publish(
  8395. {
  8396. "print": {
  8397. "command": "idle_ignore",
  8398. "err": err_decimal,
  8399. "type": 1 if persistent else 0,
  8400. "sequence_id": "0",
  8401. }
  8402. }
  8403. )
  8404. def ams_control(param: str):
  8405. publish(
  8406. {
  8407. "print": {
  8408. "command": "ams_control",
  8409. "param": param,
  8410. "sequence_id": "0",
  8411. }
  8412. }
  8413. )
  8414. def clean_print_error():
  8415. # Matches the existing `clear_hms_errors` shape — Bambu does not
  8416. # expect `print_error` in the body; the command clears whatever
  8417. # error dialog is currently active on the printer.
  8418. publish(
  8419. {
  8420. "print": {
  8421. "command": "clean_print_error",
  8422. "sequence_id": "0",
  8423. }
  8424. }
  8425. )
  8426. def uiop_close():
  8427. # `err` is the 8-char hex short code (already a string from the
  8428. # frontend), uppercased for consistency with how BambuStudio sends it.
  8429. publish(
  8430. {
  8431. "system": {
  8432. "command": "uiop",
  8433. "name": "print_error",
  8434. "action": "close",
  8435. "source": 1,
  8436. "type": "dialog",
  8437. "err": print_error.upper(),
  8438. "sequence_id": "0",
  8439. }
  8440. }
  8441. )
  8442. match action:
  8443. case (
  8444. HMSAction.RESUME_PRINTING
  8445. | HMSAction.RESUME_PRINTING_DEFECTS
  8446. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  8447. | HMSAction.PROBLEM_SOLVED_RESUME
  8448. | HMSAction.FILAMENT_LOAD_RESUME
  8449. | HMSAction.PROCEED
  8450. ):
  8451. hms_resume()
  8452. case HMSAction.STOP_PRINTING:
  8453. hms_stop()
  8454. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  8455. # All three buttons map to BambuStudio's `command_hms_ignore`
  8456. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  8457. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  8458. # responsibility — the wire shape is identical.
  8459. hms_ignore_command()
  8460. case HMSAction.NO_REMINDER_NEXT_TIME:
  8461. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  8462. # `command_hms_idle_ignore` with type=0
  8463. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  8464. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  8465. # dismisses the dialog.
  8466. hms_idle_ignore(persistent=False)
  8467. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  8468. ams_control("done")
  8469. case (
  8470. HMSAction.RETRY_FILAMENT_EXTRUDED
  8471. | HMSAction.CONTINUE
  8472. | HMSAction.RETRY_PROBLEM_SOLVED
  8473. | HMSAction.DBL_CHECK_RETRY
  8474. ):
  8475. ams_control("resume")
  8476. case HMSAction.ABORT:
  8477. ams_control("abort")
  8478. case HMSAction.OK_BUTTON:
  8479. clean_print_error()
  8480. case HMSAction.DBL_CHECK_OK:
  8481. clean_print_error()
  8482. uiop_close()
  8483. case HMSAction.DBL_CHECK_RESUME:
  8484. # Plain resume — not HMS-aware, no err/job_id.
  8485. publish(
  8486. {
  8487. "print": {
  8488. "command": "resume",
  8489. "param": "",
  8490. "sequence_id": "0",
  8491. }
  8492. }
  8493. )
  8494. case HMSAction.REFRESH_NOZZLE:
  8495. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  8496. case HMSAction.TURN_OFF_FIRE_ALARM:
  8497. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  8498. case HMSAction.STOP_DRYING:
  8499. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  8500. case HMSAction.DISABLE_PURIFICATION:
  8501. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  8502. case (
  8503. HMSAction.CHECK_ASSISTANT
  8504. | HMSAction.JUMP_TO_LIVEVIEW
  8505. | HMSAction.OK_JUMP_RACK
  8506. | HMSAction.REMOVE_CLOSE_BTN
  8507. | HMSAction.LOAD_VIRTUAL_TRAY
  8508. | HMSAction.CANCLE
  8509. | HMSAction.DBL_CHECK_CANCEL
  8510. ):
  8511. # UI-only actions — the printer's own screen handles these; the
  8512. # modal still surfaces them so the user has parity with Studio.
  8513. pass
  8514. case _:
  8515. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  8516. return False
  8517. return True