bambu_mqtt.py 468 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263
  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. tray_flag_bit,
  40. unit_ams_type,
  41. unit_label,
  42. )
  43. logger = logging.getLogger(__name__)
  44. # How long a manual load's tray target stays a hint for an H2D's tray_now: long
  45. # enough for a real load to report, short enough that a refused one cannot
  46. # relabel a later print's load of the same slot number (FW-C7).
  47. PENDING_TRAY_TARGET_TTL = 120.0
  48. # AMS module name prefixes used in get_version responses.
  49. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  50. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  51. # "ams_f1/<id>" – AMS Lite (A1, A1 Mini; the A2L reports id 16, stored as 6)
  52. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  53. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  54. # "n10a" – AMS 3H (H3C), no suffix: read as "n10a/<its unit id>"
  55. _AMS_MODULE_PREFIXES = ("ams/", "ams_f1/", "n3f/", "n3s/", "n10a/")
  56. # gcode_state values that mean the printer is not idle and must not be handed a
  57. # new start-print (#2598). The firmware rejects a project_file while busy with
  58. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  59. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  60. # are valid start targets and are deliberately excluded. Mirrors
  61. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  62. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  63. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  64. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  65. # ended the cycle on schedule or aborted it. More than this many minutes still on
  66. # the clock means it was cut short, and the firmware's own reason codes are worth
  67. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  68. # left), and the log said only "drying complete", so the report carried no
  69. # evidence of why. The margin absorbs a stale last observation between AMS
  70. # pushes; it is not a judgement about how short "short" is.
  71. _EARLY_DRY_END_MINUTES = 5
  72. # CONNACK reason codes that mean the printer actively refused our credentials,
  73. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  74. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  75. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  76. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  77. # code (or, on some firmware, the serial used as the username) is wrong.
  78. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  79. # Short, stable slugs recorded on the client and surfaced to the connection
  80. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  81. # frontend picks a localized message key off these.
  82. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  83. CONNECT_ERROR_REFUSED = "refused"
  84. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  85. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  86. OrcaSlicer reads bit 18 of the hex string via
  87. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  88. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  89. that doesn't yield a clean integer so downstream consumers preserve today's
  90. behaviour rather than treating "absent" as "OFF".
  91. """
  92. if not isinstance(cfg_raw, str) or not cfg_raw:
  93. return None
  94. try:
  95. return bool((int(cfg_raw, 16) >> 18) & 1)
  96. except ValueError:
  97. return None
  98. def parse_ams_filament_backup_from_home_flag(home_flag: object) -> bool | None:
  99. """Extract AMS Filament Backup state from a push_status ``print.home_flag`` value.
  100. Bambu Studio reads bit 10 for every family (DeviceManager.cpp
  101. ``parse_home_flag``: ``SetAutoRefillEnabled((flag >> 10) & 0x1)``). It's
  102. the only source on the P1S, P1P, A1 and A1 Mini, which never send ``cfg``
  103. (#3259). On every printer that sends both, the two bits agree in all
  104. captured snapshots, ON and OFF alike. Returns ``None`` for anything that
  105. isn't an integer.
  106. """
  107. if isinstance(home_flag, bool) or not isinstance(home_flag, int):
  108. return None
  109. # Negative values are the 32-bit flag read as signed; bit 10 is the same.
  110. return bool((home_flag >> 10) & 1)
  111. def is_printer_status_frame(print_data: dict) -> bool:
  112. """True when a ``print`` payload is the printer reporting its own state.
  113. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  114. `project_file` ack carries whatever Bambuddy put on the wire — including
  115. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  116. telemetry means reading our own request back as the printer's state
  117. (#3040). Only `push_status` (and the odd firmware that omits `command`
  118. entirely on a status frame) describes the printer.
  119. """
  120. command = print_data.get("command")
  121. return command is None or command == "push_status"
  122. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  123. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  124. # firmware is internally inconsistent about it:
  125. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  126. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  127. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  128. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  129. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  130. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  131. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  132. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  133. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  134. A2L_LITE_PHYSICAL_AMS_ID = 16
  135. A2L_LITE_NORMALIZED_AMS_ID = 6
  136. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  137. def _ams_unit_order(unit: dict) -> tuple[int, str]:
  138. """Sort key for AMS units by id (#3499).
  139. Firmware sends unit ids as strings ("0"), while the A2L AMS Lite's id is
  140. normalised to the int 6, so an A2L with an AMS 2 Pro and an AMS Lite held
  141. both: comparing them raised, and the AMS card stayed empty. Numeric order,
  142. with anything unreadable last.
  143. """
  144. raw = unit.get("id", 0)
  145. try:
  146. return (int(raw), "")
  147. except (TypeError, ValueError):
  148. return (1 << 30, str(raw))
  149. def normalize_am_unit_id(ams_id: int) -> int:
  150. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  151. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  152. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  153. through untouched.
  154. """
  155. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  156. def wire_tray_color(tray_color: str | None) -> str:
  157. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  158. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  159. as a zero, and does it silently: the command response echoes the value you
  160. sent and reports ``result: "success"``, so only the next AMS push shows what
  161. was really stored. Measured on the reporter's machine (#2987), where the
  162. spool's own ``rgba`` is stored lowercase and went out verbatim:
  163. sent 09ff00ff -> AMS reports 09000000
  164. sent ff5100ff -> AMS reports 00510000
  165. sent 090000FF -> AMS reports 090000FF
  166. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  167. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  168. longer matches the spool that asked for it and the assignment is deleted
  169. seconds after being made -- and re-assigning through the slot modal writes
  170. the mangled colour back, because the modal seeds itself from the tray.
  171. Applied here, at the one place the command is built, rather than in each of
  172. the four callers: a caller that forgets is exactly how this arrived.
  173. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  174. blank stays blank, which is how a slot is cleared.
  175. """
  176. return (tray_color or "").strip().lstrip("#").upper()
  177. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  178. """Translate a normalised A2L slot back to the physical wire form.
  179. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  180. (normalised id 6), else ``None`` for every other unit.
  181. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  182. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  183. confirmed by capture: the physical **global** tray value the extrusion_cali
  184. commands put in `tray_id` — we extrapolate it as 16*4+slot = 64-67 to stay
  185. consistent with the physical unit id. BambuStudio's source sends 24+slot
  186. there instead (``GetTrayIndexMap``); a BambuStudio->A2L capture of a cali
  187. command would settle it, and it lives only here. Load's `target` is not this
  188. value: see ``change_filament_wire_ids``.
  189. """
  190. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  191. return None
  192. local_slot = tray_id % 4
  193. return (
  194. A2L_LITE_PHYSICAL_AMS_ID,
  195. local_slot,
  196. legacy_tray_index(A2L_LITE_PHYSICAL_AMS_ID, local_slot),
  197. )
  198. def change_filament_wire_ids(tray_id: int, layout: TrayLayout | None = None) -> tuple[int, int, int]:
  199. """``(ams_id, slot_id, target)`` of ``ams_change_filament`` for an AMS tray.
  200. As BambuStudio's ``command_ams_change_filament`` builds them: a regular AMS
  201. is addressed by unit and local slot with the global tray as target; a unit
  202. id of 16 or more (the A2L AMS-Lite's physical 16, an AMS-HT's 128-135) has
  203. the unit id itself as target. An AMS-HT holds one tray, so its global tray
  204. id is its unit id and its slot is 0.
  205. """
  206. if is_ams_ht_id(tray_id):
  207. return tray_id, 0, tray_id
  208. ams_id, slot_id = (layout or TrayLayout()).slot_key(tray_id)
  209. if (a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  210. return a2l[0], a2l[1], a2l[0]
  211. return ams_id, slot_id, tray_id
  212. # The H3C's AMS 3H is one unit (32, AMS type 6) with nine slots, numbered 28 + k
  213. # (utils.tray_ids). Its tray_now / tray_tar / tray_pre are the raw slot 0-8;
  214. # print.mapping and the snow fields encode a slot as (32 << 8) | k. Commands
  215. # address it as {ams_id: 32, slot_id: k}.
  216. AMS3H_MODULE_NAME = "n10a" # its get_version module (no "/<unit>" suffix)
  217. def _mqtt_int(value: object) -> int | None:
  218. """An MQTT id / number field as an int (they arrive as int or numeric str), else None."""
  219. if isinstance(value, bool) or not isinstance(value, (int, str)):
  220. return None
  221. try:
  222. return int(value)
  223. except ValueError:
  224. return None
  225. # AMS 3H drying (Bambu Studio 02.09, AMSDryControl.cpp): the unit reports
  226. # `zone_info[]` and only a zone with exactly two slots can dry; the others are
  227. # ambient readings. A drying start carries the filament's softening temperature
  228. # as `cooling_temp` (the preset's filament_dev_drying_softening_temperature).
  229. AMS3H_DRY_COOLING_TEMP = {"PLA": 65, "PETG": 75, "ABS": 95, "ASA": 95, "TPU": 70, "PA": 150, "PC": 120}
  230. AMS3H_DRY_COOLING_TEMP_DEFAULT = 50
  231. def ams3h_drying_zone(zone_info: object) -> dict | None:
  232. """The zone of an AMS 3H's `zone_info` that can dry: the first holding exactly two slots."""
  233. if not isinstance(zone_info, list):
  234. return None
  235. for zone in zone_info:
  236. if isinstance(zone, dict) and isinstance(zone.get("zone_slots"), list) and len(zone["zone_slots"]) == 2:
  237. return zone
  238. return None
  239. def ams3h_drying_cooling_temp(filament: str) -> int:
  240. """`cooling_temp` for an AMS 3H drying start: the filament's softening temperature."""
  241. base = (filament or "").upper().split("-")[0].split(" ")[0]
  242. return AMS3H_DRY_COOLING_TEMP.get(base, AMS3H_DRY_COOLING_TEMP_DEFAULT)
  243. def _ams3h_unit_drying_fields(unit: dict) -> dict:
  244. """An AMS 3H's drying state, which lives on its drying zone, lifted onto the unit."""
  245. zone = ams3h_drying_zone(unit.get("zone_info"))
  246. if zone is None:
  247. return {}
  248. fields: dict = {"dry_zone_id": zone.get("zone_id", 0), "dry_zone_slots": list(zone.get("zone_slots") or [])}
  249. for key in ("dry_time", "dry_setting", "dry_sf_reason"):
  250. if key in zone:
  251. fields[key] = zone[key]
  252. if "info" not in unit and "info" in zone:
  253. fields["info"] = zone["info"]
  254. if "humidity_raw" in zone:
  255. fields["dry_zone_humidity_raw"] = zone["humidity_raw"]
  256. if "temp" in zone:
  257. fields["dry_zone_temp"] = zone["temp"]
  258. return fields
  259. def _ams3h_unit_env_fields(unit: dict) -> dict:
  260. """An AMS 3H's humidity and temperature (the unit has none) from its first non-drying zone, as Studio shows it."""
  261. zones = unit.get("zone_info")
  262. if not isinstance(zones, list):
  263. return {}
  264. dry_zone = ams3h_drying_zone(zones)
  265. ambient = next((z for z in zones if isinstance(z, dict) and z is not dry_zone), None)
  266. if ambient is None:
  267. return {}
  268. return {key: ambient[key] for key in ("humidity_raw", "temp") if key in ambient and key not in unit}
  269. def apply_rack_ams_zone_fields(ams_list: object, known_types: dict[int, AmsType] | None = None) -> None:
  270. """Lift a rack AMS's per-zone readings and drying state onto the unit, in place (type from `info`, else ``known_types``)."""
  271. if not isinstance(ams_list, list):
  272. return
  273. for unit in ams_list:
  274. if not isinstance(unit, dict) or not isinstance(unit.get("zone_info"), list):
  275. continue
  276. uid = _mqtt_int(unit.get("id"))
  277. if uid is None:
  278. continue
  279. kind = ams_type_from_info(unit.get("info"))
  280. if kind is None:
  281. kind = (known_types or {}).get(uid, unit_ams_type(uid))
  282. if not is_rack_ams(kind):
  283. continue
  284. unit.update({**_ams3h_unit_env_fields(unit), **_ams3h_unit_drying_fields(unit)})
  285. def resolve_external_spools_in_mapping(
  286. ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool, layout: TrayLayout | None = None
  287. ) -> object:
  288. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  289. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  290. dispatch both write an external spool there as -1 -- the same value as a
  291. slot that isn't fed at all -- and carry the real target only in
  292. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  293. list alone turns "printed from the external spool" into "unmapped", and
  294. usage then lands on whatever tray the fallback guesses.
  295. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  296. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  297. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  298. printers, which have one external spool that the wire always calls 255.
  299. ``{255, 255}`` is the unmapped marker and stays -1.
  300. An A2L AMS-Lite tray is the local slot 0-3 in the flat list and
  301. ``{ams_id: 16, slot_id: n}`` in ``ams_mapping2``; it becomes its normalised
  302. global tray 24+n. Kept local, it read as a regular AMS tray, so usage was
  303. charged to the wrong spool. A rack AMS slot (``{ams_id: 32, slot_id: k}``)
  304. becomes its global tray 28+k, and on a rack printer each external input
  305. 247-255 keeps its own id. Every other entry is left exactly as captured.
  306. Without a usable ``ams_mapping2`` the input is returned unchanged.
  307. """
  308. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  309. return ams_mapping
  310. if len(ams_mapping2) != len(ams_mapping):
  311. return ams_mapping
  312. resolved = list(ams_mapping)
  313. layout = layout or TrayLayout()
  314. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  315. if not isinstance(detail, dict):
  316. continue
  317. ams_id = detail.get("ams_id")
  318. slot_id = detail.get("slot_id")
  319. if ams_id == A2L_LITE_PHYSICAL_AMS_ID and slot_id in (0, 1, 2, 3):
  320. resolved[i] = A2L_LITE_GLOBAL_BASE + slot_id
  321. continue
  322. if (
  323. isinstance(ams_id, int)
  324. and isinstance(slot_id, int)
  325. and not is_external_tray(ams_id, layout.rack)
  326. and is_rack_ams(layout.ams_type(ams_id))
  327. and 0 <= slot_id < RACK_SLOT_COUNT
  328. ):
  329. resolved[i] = layout.global_tray_id(ams_id, slot_id)
  330. continue
  331. if flat != -1 or not is_external_tray(ams_id, layout.rack) or slot_id == 255:
  332. continue
  333. resolved[i] = ams_id if is_dual_nozzle or layout.rack else 254
  334. return resolved
  335. def unit_reported_absent(ams_id, ams_list: list, ams_exist_bits) -> bool:
  336. """Whether a push that doesn't list AMS unit ``ams_id`` says it is unplugged.
  337. ``ams_exist_bits`` (hex) has bit n set for AMS unit n, measured on an X1C
  338. (unit 1 -> "2", none -> "0") and an H2C (units 0, 1, 2 and HT 128 -> "17").
  339. So an AMS unit 0-3 whose bit is clear is gone. An empty unit list with no
  340. bits set means no unit at all, which is what the X1C sends with its AMS
  341. unplugged. Anything else is kept, as the merge always did: a partial push
  342. lists only some units, and the bits of an AMS HT or AMS Lite next to other
  343. units are not measured well enough to read.
  344. """
  345. if ams_exist_bits is None:
  346. return False
  347. try:
  348. bits = int(ams_exist_bits, 16) if isinstance(ams_exist_bits, str) else int(ams_exist_bits)
  349. unit = int(ams_id)
  350. except (TypeError, ValueError):
  351. return False
  352. if bits == 0 and not ams_list:
  353. return True
  354. return 0 <= unit <= 3 and not bits >> unit & 1
  355. def apply_tray_exist_bits(
  356. units: list,
  357. tray_exist_bits_str: str | int | None,
  358. *,
  359. power_on_flag: bool = True,
  360. log_label: str | None = None,
  361. annotate_exists: bool = False,
  362. ) -> int:
  363. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  364. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  365. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  366. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  367. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  368. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  369. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  370. instead of guessing from payload shape (#1322, #147).
  371. Two callers share this helper to keep their views consistent:
  372. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  373. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  374. facing push_status (#1726 — without this the VP would forward stale
  375. per-tray fields for empty slots, and BambuStudio's Sync would render
  376. phantom loaded slots).
  377. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  378. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  379. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  380. so spool removal is detected without requiring a manual reconnect.
  381. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  382. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  383. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  384. authoritative empty signal for the HT — the only working clear path, since
  385. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  386. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  387. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  388. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  389. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  390. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  391. the raw physical id 16 get the same bit base as callers holding the
  392. normalised 6 (#2697).
  393. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  394. way). Ints are tolerated for defensive symmetry but typically not seen
  395. on the wire. ``None`` / empty / unparseable → no-op.
  396. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  397. every processed slot. This is firmware's authoritative "spool physically
  398. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  399. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  400. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  401. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  402. leaves it False so the ``exists`` key never reaches the slicer wire format.
  403. Mutates ``units`` in place. Returns the number of slots cleared.
  404. """
  405. if not tray_exist_bits_str:
  406. return 0
  407. try:
  408. if isinstance(tray_exist_bits_str, int):
  409. tray_exist_bits = tray_exist_bits_str
  410. else:
  411. tray_exist_bits = int(tray_exist_bits_str, 16)
  412. except (ValueError, TypeError):
  413. return 0
  414. if tray_exist_bits == 0 and not power_on_flag:
  415. return 0
  416. if not isinstance(units, list):
  417. return 0
  418. cleared = 0
  419. for ams_unit in units:
  420. if not isinstance(ams_unit, dict):
  421. continue
  422. ams_id_raw = ams_unit.get("id")
  423. if ams_id_raw is None:
  424. continue
  425. try:
  426. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  427. except (ValueError, TypeError):
  428. continue
  429. if not isinstance(ams_id, int):
  430. continue
  431. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  432. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  433. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  434. # the physical 16. Both mean bit base 24, so fold them together here
  435. # rather than relying on every caller to normalise first — reading 16 as
  436. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  437. ams_id = normalize_am_unit_id(ams_id)
  438. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  439. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  440. # A rack AMS (unit 32): its global tray id 28 + slot.
  441. # Anything outside those has no known bit layout — don't guess it.
  442. kind = unit_ams_type(ams_id, ams_unit.get("info"))
  443. if tray_flag_bit(ams_id, 0, kind) is None:
  444. continue
  445. for tray in ams_unit.get("tray", []):
  446. if not isinstance(tray, dict):
  447. continue
  448. tray_id_raw = tray.get("id")
  449. if tray_id_raw is None:
  450. continue
  451. try:
  452. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  453. except (ValueError, TypeError):
  454. continue
  455. if not isinstance(tray_id, int):
  456. continue
  457. global_bit = tray_flag_bit(ams_id, tray_id, kind)
  458. if global_bit is None or global_bit < 0:
  459. continue
  460. slot_exists = (tray_exist_bits >> global_bit) & 1
  461. if annotate_exists:
  462. tray["exists"] = bool(slot_exists)
  463. if slot_exists:
  464. continue
  465. tray["state"] = 9
  466. if tray.get("tray_type"):
  467. if log_label:
  468. logger.debug(
  469. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  470. f"(tray_exist_bits bit {global_bit} = 0)"
  471. )
  472. tray["tray_type"] = ""
  473. tray["tray_sub_brands"] = ""
  474. tray["tray_color"] = ""
  475. tray["tray_id_name"] = ""
  476. tray["tag_uid"] = "0000000000000000"
  477. tray["tray_uuid"] = "00000000000000000000000000000000"
  478. tray["tray_info_idx"] = ""
  479. tray["remain"] = 0
  480. cleared += 1
  481. return cleared
  482. def _external_slot_to_merge(pushed: object, existing: object) -> dict | None:
  483. """The one cached external slot a pushed ``vt_tray`` dict updates, or None (#3513).
  484. It updates the slot when it names no slot or the cached one's. A push that
  485. empties the slot (``tray_type`` ``""``) replaces it, so a removed spool
  486. keeps no preset, K value or temperatures, as does one naming another slot.
  487. """
  488. if not isinstance(pushed, dict) or not isinstance(existing, list) or len(existing) != 1:
  489. return None
  490. cached = existing[0]
  491. if not isinstance(cached, dict) or pushed.get("tray_type") == "":
  492. return None
  493. if "id" in pushed and str(pushed["id"]) != str(cached.get("id")):
  494. return None
  495. return cached
  496. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  497. #
  498. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  499. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  500. # rack position is never mistakable for the nozzle on the other carriage.
  501. #
  502. # Extruder indices are a different namespace that happens to overlap these
  503. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  504. # Nothing below may pass a value from one namespace to the other untranslated;
  505. # doing exactly that is what #2800 was.
  506. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  507. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  508. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  509. #
  510. # Briefly changed to the plate's own slot count on the strength of a single
  511. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  512. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  513. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  514. # a calibration job, so the length varies with whatever Studio is doing rather
  515. # than with the filament count -- which makes it the wrong thing to derive.
  516. _RACK_WIRE_SLOTS = 32
  517. # The two carriages, as extruder indices in the form the queue stores (already
  518. # translated through the file's physical_extruder_map).
  519. #
  520. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  521. #
  522. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  523. # extruder 1, AMS 1 and 2 feed extruder 0;
  524. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  525. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  526. # and that print completed. So extruder 1 is the fixed hotend and extruder
  527. # 0 is the rack;
  528. # - our own constants were internally inconsistent about it: physical nozzle
  529. # id N sits on extruder N (see the L/R split in PrintersPage), and
  530. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  531. # extruder index of 0.
  532. #
  533. # These were the other way round until then, which is what dispatched a plate
  534. # to the carriage that had not been levelled and printed its first layer in
  535. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  536. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  537. # which *wire* worked, and the extruder indices were only inferred from it by
  538. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  539. # wire result stands; the inference from it did not.
  540. _FIXED_EXTRUDER_ID = 1
  541. _RACK_EXTRUDER_ID = 0
  542. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  543. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  544. # outright, which would not start the job at all. Native BambuStudio captures
  545. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  546. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  547. _FIXED_NOZZLE_ID = 1
  548. def resolve_rack_nozzle_mapping(
  549. slot_extruders: list[int],
  550. rack_nozzle_id: int | None,
  551. ) -> list[int] | None:
  552. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  553. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  554. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  555. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  556. reports as live.
  557. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  558. when the mapping cannot be resolved with confidence -- in which case the
  559. caller omits the field entirely and the firmware falls back to its own
  560. nozzle pick, exactly as it did before this translation existed. Omitting
  561. is deliberately the failure mode: a *wrong* physical ID makes the printer
  562. level with one nozzle and print with another several millimetres off the
  563. bed, which is far worse than letting the firmware choose.
  564. Returns None specifically when:
  565. - a slot needs the rack but the printer has not reported a live rack
  566. position (mid-swap, or a stale connection);
  567. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  568. for a plate sliced for the fixed hotend only (#2800 capture), so this
  569. matches it rather than naming a nozzle it does not have to name;
  570. - a slot names a carriage that is neither of the two an H2C has, which
  571. means the file was mapped for a machine this translation does not model;
  572. - the plate needs more slots than the wire format carries;
  573. - the input is not a list of whole numbers.
  574. Total by construction: it raises nothing, because the only caller is
  575. building an MQTT print command with no exception handler above it and the
  576. queue item has already been committed as `printing` by then. An
  577. unparseable input has to degrade to "let the firmware pick", not to a job
  578. wedged in a state no print will ever leave.
  579. """
  580. if not isinstance(slot_extruders, list) or not slot_extruders:
  581. return None
  582. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  583. return None
  584. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  585. return None
  586. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  587. return None
  588. # Normalise first so the checks below, and the values that reach the wire,
  589. # are known ints. bool is an int subclass and would otherwise serialise as
  590. # a JSON `true`; None means "slot not printed" and is folded into -1.
  591. normalised: list[int] = []
  592. for extruder in slot_extruders:
  593. if extruder is None:
  594. normalised.append(-1)
  595. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  596. normalised.append(extruder)
  597. else:
  598. return None
  599. if _RACK_EXTRUDER_ID not in normalised:
  600. return None
  601. wire = [-1] * _RACK_WIRE_SLOTS
  602. for index, extruder in enumerate(normalised):
  603. if extruder < 0:
  604. continue
  605. if extruder == _RACK_EXTRUDER_ID:
  606. wire[index] = rack_nozzle_id
  607. elif extruder == _FIXED_EXTRUDER_ID:
  608. wire[index] = _FIXED_NOZZLE_ID
  609. else:
  610. # An H2C has these two carriages and no others. A third index is a
  611. # file mapped for something else, and forwarding it raw would name
  612. # a physical nozzle by an index that does not identify one.
  613. return None
  614. return wire
  615. # A rack position as the operator counts it (and as the printer card and
  616. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  617. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  618. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  619. _RACK_POSITION_BASE = 15
  620. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  621. def rack_position_to_nozzle_id(position: int) -> int | None:
  622. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  623. if not isinstance(position, int) or isinstance(position, bool):
  624. return None
  625. if position not in RACK_POSITIONS:
  626. return None
  627. return _RACK_POSITION_BASE + position
  628. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  629. """Whether a live rack slot can print a group wanting this nozzle.
  630. Mirrors the filter BambuStudio applies in its own picker: the position has
  631. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  632. and flow type. A mismatch here is not cosmetic -- it is the printer being
  633. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  634. """
  635. if not isinstance(slot, dict):
  636. return False
  637. slot_diameter = str(slot.get("diameter") or "").strip()
  638. slot_type = str(slot.get("type") or "").strip()
  639. if not slot_diameter and not slot_type:
  640. return False # empty position
  641. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  642. # the printer does not.
  643. try:
  644. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  645. return False
  646. except (TypeError, ValueError):
  647. return False
  648. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  649. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  650. # printer that omits the code is not thereby ruled ineligible.
  651. wanted = volume_type.strip().lower()
  652. if wanted and slot_type:
  653. is_high_flow = slot_type.upper().startswith("HH")
  654. if wanted.startswith("high flow") != is_high_flow:
  655. return False
  656. return True
  657. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  658. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  659. _RACK_CARRIAGE_NOZZLE_ID = 0
  660. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  661. """Live rack contents keyed by 1-based position, mounted nozzle included.
  662. The firmware omits a rack id entirely while that nozzle is picked up onto
  663. the carriage (#943) -- it does not send an empty placeholder. Taking the
  664. omission at face value would rule the nozzle ineligible for the very print
  665. that wants it, and it is the single most likely position to be picked,
  666. because it is the one the last print left mounted.
  667. The absent id is recoverable only when exactly one is missing: rack ids are
  668. fixed at 16..21, so a single gap alongside a loaded carriage is that
  669. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  670. with four nozzles in six positions looks the same -- so those stay absent
  671. and the caller treats them as empty.
  672. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  673. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  674. """
  675. by_position: dict[int, dict] = {}
  676. carriage: dict | None = None
  677. for slot in rack_slots or []:
  678. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  679. continue
  680. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  681. carriage = slot
  682. continue
  683. position = slot["id"] - _RACK_POSITION_BASE
  684. if position in RACK_POSITIONS:
  685. by_position[position] = slot
  686. missing = [position for position in RACK_POSITIONS if position not in by_position]
  687. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  688. by_position[missing[0]] = carriage
  689. return by_position
  690. def resolve_rack_plan_mapping(
  691. slot_groups: list[int],
  692. groups: dict[int, dict],
  693. choice: dict[int, int],
  694. rack_slots: list[dict],
  695. ) -> tuple[list[int] | None, str | None]:
  696. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  697. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  698. That one can only name the single live rack position, so a plate wanting a
  699. different hotend per group is unresolvable to it. Here each group carries
  700. its own position, which is the operator's choice (#1784) -- the 3MF states
  701. it nowhere, proven by dispatching one plate twice with different picks and
  702. diffing the two files down to float noise.
  703. ``choice`` may be partial or empty; groups it does not name are assigned
  704. from the live rack, preferring a position already loaded with the group's
  705. own filament colour and otherwise taking the lowest eligible one.
  706. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  707. is a sentence naming what could not be satisfied. The caller decides what
  708. to do with a failure, and the two cases differ: a stale *explicit* pick
  709. should stop the print, while a failed auto-assignment should degrade to
  710. letting the firmware choose, exactly as before this existed.
  711. """
  712. if not isinstance(slot_groups, list) or not slot_groups:
  713. return None, "the plate lists no filament slots"
  714. if len(slot_groups) > _RACK_WIRE_SLOTS:
  715. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  716. by_position = _rack_by_position(rack_slots)
  717. # Assign every rack-bound group a position before building the wire, so a
  718. # group can never be handed one an earlier group already took. Explicit
  719. # picks are placed first: an auto-assignment must yield to them rather than
  720. # claim a position the operator asked for.
  721. assigned: dict[int, int] = {}
  722. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  723. for group_id in rack_group_ids:
  724. position = choice.get(group_id)
  725. if position is None:
  726. continue
  727. group = groups[group_id]
  728. if rack_position_to_nozzle_id(position) is None:
  729. return None, f"rack position {position} does not exist"
  730. if position in assigned.values():
  731. return None, f"rack position {position} is picked for more than one filament group"
  732. slot = by_position.get(position)
  733. if slot is None:
  734. return None, f"the printer reports nothing at rack position {position}"
  735. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  736. return None, (
  737. f"rack position {position} holds a "
  738. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  739. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  740. )
  741. assigned[group_id] = position
  742. for group_id in rack_group_ids:
  743. if group_id in assigned:
  744. continue
  745. group = groups[group_id]
  746. eligible = [
  747. position
  748. for position in RACK_POSITIONS
  749. if position not in assigned.values()
  750. and position in by_position
  751. and _rack_slot_is_eligible(
  752. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  753. )
  754. ]
  755. if not eligible:
  756. return None, (
  757. f"no free rack position holds a {group.get('nozzle_diameter')} "
  758. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  759. )
  760. # Prefer a position already carrying this group's colour: picking it
  761. # means the operator does not have to move filament to make the print
  762. # match what they asked for.
  763. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  764. assigned[group_id] = next(
  765. (
  766. position
  767. for position in eligible
  768. if wanted_colour
  769. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  770. == wanted_colour
  771. ),
  772. eligible[0],
  773. )
  774. wire = [-1] * _RACK_WIRE_SLOTS
  775. for index, group_id in enumerate(slot_groups):
  776. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  777. continue # slot this plate does not print
  778. group = groups.get(group_id)
  779. if group is None:
  780. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  781. if not group.get("on_rack"):
  782. wire[index] = _FIXED_NOZZLE_ID
  783. continue
  784. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  785. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  786. return None, f"filament group {group_id} resolved to no rack position"
  787. wire[index] = nozzle_id
  788. if all(value == -1 for value in wire):
  789. return None, "the plate assigns no filament to a nozzle"
  790. return wire, None
  791. @dataclass(frozen=True)
  792. class DryingCycleEnd:
  793. """What Bambuddy saw of one AMS drying cycle, reported when it ends (#2863).
  794. ``peak_minutes`` is the highest ``dry_time`` observed during the cycle and
  795. ``remaining_minutes`` the last one before the drop to 0. ``start_seen`` says
  796. whether the countdown was watched from its first minute; when it was not
  797. (Bambuddy started mid-cycle) the peak is only a lower bound on the length.
  798. ``target_temp`` / ``target_hours`` are known only for cycles Bambuddy itself
  799. started, because the printer never echoes them.
  800. """
  801. ams_id: int
  802. remaining_minutes: int
  803. peak_minutes: int
  804. start_seen: bool
  805. target_temp: int | None = None
  806. target_hours: int | None = None
  807. @dataclass
  808. class MQTTLogEntry:
  809. """Log entry for MQTT message debugging."""
  810. timestamp: str
  811. topic: str
  812. direction: str # "in" or "out"
  813. payload: dict
  814. @dataclass
  815. class HMSError:
  816. """Health Management System error from printer."""
  817. code: str
  818. attr: int # Attribute value for constructing wiki URL
  819. module: int
  820. # Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  821. # 3 notification, 0 invalid. From `code >> 16` for `hms[]` faults, and from
  822. # the error's first hex digit for `print_error` (#2728).
  823. severity: int
  824. # The bundled catalogue's sentence for this fault, resolved once here so
  825. # every surface that reports it — the status response, the WebSocket
  826. # broadcast, the completion payload, notifications — says the same thing.
  827. # None when Bambu publishes no text for the code; see `describe_fault`.
  828. # Replaces a `message` field that was never set or read anywhere.
  829. description: str | None = None
  830. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  831. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  832. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  833. # HMSError without explicitly passing actions can't silently land None on the schema
  834. # boundary and raise ValidationError at routes/printers.py response time.
  835. actions: list[str] = field(default_factory=list)
  836. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  837. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  838. job_id: str | None = None
  839. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  840. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  841. # 32-bit `print_error` path. The frontend echoes this back to
  842. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  843. # used to send caused the firmware to silently reject HMS commands on H2C
  844. # (#1830) and on `hms[]`-sourced faults generally.
  845. full_code: str = ""
  846. def completion_payload(self) -> dict:
  847. """This error as a print-complete payload carries it, for the failure reason."""
  848. return {
  849. "code": self.code,
  850. "attr": self.attr,
  851. "module": self.module,
  852. "severity": self.severity,
  853. # Lets the queue's failure reason label an `hms[]` fault
  854. # with its full code rather than a lossy short one (#2728).
  855. "full_code": self.full_code,
  856. # Carried so the queue's failure reason quotes the same
  857. # sentence the status response and the broadcast do,
  858. # rather than resolving the code a fourth time (#2926).
  859. "description": self.description,
  860. }
  861. def _is_print_error_entry(error: HMSError) -> bool:
  862. """Whether this entry came from the 32-bit `print_error` field, whose
  863. full code has 8 hex digits; an `hms[]` entry's has 16."""
  864. return len(error.full_code) == 8
  865. def _hms_short_code(error: HMSError) -> str:
  866. """The MMMM_EEEE short code of an entry from either source."""
  867. module = (error.attr >> 16) & 0xFFFF
  868. # The low half only: an hms[] code carries its alert level above it
  869. # (0x18061 for 0500_8061), and read whole it never matched, listing the
  870. # fault twice (M-U9).
  871. number = (int(error.code.replace("0x", ""), 16) & 0xFFFF) if error.code else 0
  872. return f"{module:04X}_{number:04X}"
  873. def _hms_short_codes(errors: list) -> set[str]:
  874. return {_hms_short_code(e) for e in errors}
  875. # HMS short codes the firmware emits during normal user-cancel sequences.
  876. # These aren't faults — they're status echoes that confirm the cancel happened.
  877. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  878. # so they don't drive the printer card's "X problem" badge, the red pip, or
  879. # any other consumer that treats hms_errors as the active-fault list.
  880. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  881. {
  882. "0300_400C", # "The task was canceled."
  883. "0500_400E", # "Printing was cancelled."
  884. }
  885. )
  886. # "MQTT command verification failed" — the printer's authorization/authentication
  887. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  888. # command it could not verify. Queries (get_version, extrusion_cali_get,
  889. # pushall) still answer, so the connection looks perfectly healthy while
  890. # project_file, gcode_line and ams_change_filament are all silently dropped —
  891. # which is exactly how it presents: uploads succeed, the printer echoes our
  892. # subtask_id, then sits at IDLE forever (#2732).
  893. #
  894. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  895. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  896. # "0500_0007", which matches nothing in any catalog.
  897. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  898. @dataclass
  899. class KProfile:
  900. """Pressure advance (K) calibration profile from printer."""
  901. slot_id: int
  902. extruder_id: int
  903. nozzle_id: str
  904. nozzle_diameter: str
  905. filament_id: str
  906. name: str
  907. k_value: str
  908. n_coef: str = "0.000000"
  909. ams_id: int = 0
  910. tray_id: int = -1
  911. setting_id: str | None = None
  912. @dataclass
  913. class NozzleInfo:
  914. """Nozzle hardware configuration."""
  915. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  916. nozzle_diameter: str = "" # e.g., "0.4"
  917. # What await_cali_ack reports when the printer did not answer a K-profile write
  918. # in time. Not a refusal: firmware that predates the ack never answers.
  919. CALI_ACK_UNCONFIRMED = "no acknowledgement from printer"
  920. class KProfileReadError(Exception):
  921. """The printer's K-profile table could not be read: not connected, or no
  922. answer to any attempt. Not an empty table, which is a printer without
  923. profiles for that nozzle (#3404)."""
  924. # Time the printer has to list a skipped object in s_obj before the skip is
  925. # logged as not confirmed.
  926. SKIP_CONFIRM_TIMEOUT_S = 60.0
  927. # Answers to K-profile commands: they echo the command's own fields (the nozzle
  928. # diameter among them), never the printer's status.
  929. _KPROFILE_COMMAND_ANSWERS = frozenset(
  930. {"extrusion_cali_get", "extrusion_cali_set", "extrusion_cali_del", "extrusion_cali_sel"}
  931. )
  932. @dataclass
  933. class FilaSwitchState:
  934. """Filament Track Switch (FTS) accessory state.
  935. The FTS is an external accessory that mediates filament routing between an
  936. AMS and the printer's extruders. When installed, the AMS no longer has a
  937. fixed extruder assignment — any slot can be routed to any extruder via the
  938. track switch. Detected from print.device.fila_switch in MQTT.
  939. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  940. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  941. stable, operator-visible relationship — it is set on the printer's "Manual
  942. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  943. Field semantics below are taken from BambuStudio's own parser
  944. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  945. """
  946. installed: bool = False
  947. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  948. # the arrays are ordered B-then-A, which is the opposite of how they read.
  949. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  950. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  951. in_slots: list[int] = field(default_factory=list)
  952. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  953. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  954. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  955. # inlet is currently paired with which outlet is not reported at all.
  956. out_extruders: list[int] = field(default_factory=list)
  957. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  958. info: int = 0 # bit 0 = inlet has filament
  959. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  960. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  961. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  962. one of A/B.
  963. """
  964. index = {"A": 1, "B": 0}.get(inlet.upper())
  965. if index is None or index >= len(self.in_slots):
  966. return None
  967. raw = self.in_slots[index]
  968. if raw < 0:
  969. return None
  970. return (raw >> 8) & 0xFF, raw & 0xFF
  971. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  972. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  973. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  974. # as empty everywhere is strictly safer than reading it as the external spool.
  975. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  976. @dataclass
  977. class ExtruderSlot:
  978. """Which AMS slot an extruder is currently fed from.
  979. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  980. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  981. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  982. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  983. ``state.tray_now`` cannot answer this: it is a single value for the whole
  984. printer, so on a dual-nozzle machine with both hotends loaded it names only
  985. one of them. Unloading a specific slot needs to know which extruder is
  986. holding it, which is what this is for.
  987. """
  988. ams_id: int | None = None
  989. slot_id: int | None = None
  990. has_filament: bool = False
  991. def holds(self, ams_id: int, slot_id: int) -> bool:
  992. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  993. return self.ams_id == ams_id and self.slot_id == slot_id
  994. @dataclass
  995. class PrintOptions:
  996. """AI detection and print options from xcam data."""
  997. # Core AI detectors
  998. spaghetti_detector: bool = False
  999. print_halt: bool = False
  1000. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  1001. first_layer_inspector: bool = False
  1002. printing_monitor: bool = False # AI print quality monitoring
  1003. buildplate_marker_detector: bool = False
  1004. allow_skip_parts: bool = False
  1005. # Additional AI detectors - decoded from cfg bitmask
  1006. nozzle_clumping_detector: bool = True
  1007. nozzle_clumping_sensitivity: str = "medium"
  1008. pileup_detector: bool = True
  1009. pileup_sensitivity: str = "medium"
  1010. airprint_detector: bool = True
  1011. airprint_sensitivity: str = "medium"
  1012. auto_recovery_step_loss: bool = True # Uses print.print_option command
  1013. filament_tangle_detect: bool = False
  1014. @dataclass
  1015. class PrinterState:
  1016. connected: bool = False
  1017. state: str = "unknown"
  1018. current_print: str | None = None
  1019. subtask_name: str | None = None
  1020. progress: float = 0.0
  1021. remaining_time: int = 0
  1022. layer_num: int = 0
  1023. total_layers: int = 0
  1024. temperatures: dict = field(default_factory=dict)
  1025. raw_data: dict = field(default_factory=dict)
  1026. gcode_file: str | None = None
  1027. subtask_id: str | None = None
  1028. hms_errors: list = field(default_factory=list) # List of HMSError
  1029. kprofiles: list = field(default_factory=list) # List of KProfile
  1030. sdcard: bool = False # SD card inserted
  1031. # Whether the printer has ever actually told us about `sdcard`. Without this
  1032. # the default False is indistinguishable from a real "no card", and any
  1033. # consumer that treats False as evidence would act on silence — which is how
  1034. # a storage gate turns into a regression for every printer whose firmware
  1035. # simply doesn't publish the field (#2780).
  1036. sdcard_reported: bool = False
  1037. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  1038. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  1039. # whoever sent it (the slicer or us). Bambu states where the sliced file
  1040. # went: `ftp://<name>` is external storage, which FTPS serves, while
  1041. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  1042. #
  1043. # Two fields, because the two readers need different guarantees.
  1044. # ``current_project_url`` belongs to the print now running and is cleared
  1045. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  1046. # "unknown" rather than inheriting the previous job's answer. That matters:
  1047. # 18% of the print starts in #2780's bundle had no dispatch on the request
  1048. # topic at all (touchscreen reprints, restart recovery), and a stale
  1049. # internal-storage URL would make those skip an FTPS sweep that could have
  1050. # found the file — losing an archive that works today.
  1051. #
  1052. # ``last_project_url`` is sticky and exists for reporting only: the
  1053. # connection diagnostic is usually run *after* the print that prompted it,
  1054. # by which point the per-print value is rightly gone.
  1055. #
  1056. # None means we never saw a dispatch — say nothing, don't guess.
  1057. current_project_url: str | None = None
  1058. last_project_url: str | None = None
  1059. timelapse: bool = False # Timelapse recording active
  1060. ipcam: bool = False # Live view / camera streaming enabled
  1061. wifi_signal: int | None = None # WiFi signal strength in dBm
  1062. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  1063. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  1064. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  1065. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  1066. # right. (The legacy parser below writes left -> [0], but it only ever runs
  1067. # for single-nozzle printers -- every dual-nozzle model reports
  1068. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  1069. # than indexing it directly.
  1070. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  1071. # AI detection and print options
  1072. print_options: PrintOptions = field(default_factory=PrintOptions)
  1073. # Calibration stage tracking (from stg_cur and stg fields)
  1074. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  1075. stg: list = field(default_factory=list) # List of stages to execute
  1076. # Air conditioning mode (0=cooling, 1=heating)
  1077. airduct_mode: int = 0
  1078. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1079. speed_level: int = 2
  1080. # Chamber light on/off
  1081. chamber_light: bool = False
  1082. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  1083. active_extruder: int = 0
  1084. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  1085. tray_now: int = 255
  1086. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  1087. # tray_tar = the slot the paused/loading print now expects
  1088. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  1089. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  1090. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  1091. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  1092. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  1093. tray_tar: int = 255
  1094. tray_pre: int = 255
  1095. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  1096. last_loaded_tray: int = -1
  1097. # Pending load target - used to track what tray we're loading for H2D disambiguation
  1098. pending_tray_target: int | None = None
  1099. # When it was set (time.monotonic): see PENDING_TRAY_TARGET_TTL.
  1100. pending_tray_target_at: float | None = None
  1101. # AMS status for filament change tracking (from print.ams.ams_status field)
  1102. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1103. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  1104. ams_status: int = 0
  1105. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  1106. ams_status_sub: int = 0 # ams_status & 0xFF
  1107. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  1108. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  1109. mc_print_sub_stage: int = 0
  1110. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  1111. ams_mapping: list = field(default_factory=list)
  1112. # The running print's AMS mapping (global tray per filament, -1 = none),
  1113. # as captured from its print command. None when no print has one.
  1114. print_ams_mapping: list | None = None
  1115. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  1116. ams_extruder_map: dict = field(default_factory=dict)
  1117. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  1118. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  1119. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  1120. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  1121. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  1122. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  1123. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  1124. ams_switch_inlet: dict = field(default_factory=dict)
  1125. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  1126. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  1127. # series). Empty elsewhere, which every reader has to tolerate — see
  1128. # ExtruderSlot for why tray_now cannot stand in for it.
  1129. extruder_slots: dict = field(default_factory=dict)
  1130. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  1131. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  1132. # regex used to derive the plate number from the path always falls back to
  1133. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  1134. # Bambuddy dispatches the print itself we know the plate authoritatively;
  1135. # we record it here and prefer it over the gcode_file regex. The subtask
  1136. # field guards against staleness: if the printer is currently running a
  1137. # different subtask (e.g. a Studio-direct dispatch), these values are
  1138. # ignored. Cleared on disconnect.
  1139. dispatched_plate_id: int | None = None
  1140. dispatched_subtask: str | None = None
  1141. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  1142. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  1143. h2d_extruder_snow: dict = field(default_factory=dict)
  1144. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  1145. nozzle_rack: list = field(default_factory=list)
  1146. # H2C rack position currently mounted / being moved to, from
  1147. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  1148. # the six rack slots), not extruder indices, and they are what the
  1149. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  1150. # can tell us which hotend is in the carriage right now, so this is read
  1151. # live rather than derived from the queued job.
  1152. nozzle_rack_src_id: int | None = None
  1153. nozzle_rack_tar_id: int | None = None
  1154. # Timestamp of last AMS data update (for RFID refresh detection)
  1155. last_ams_update: float = 0.0
  1156. # Printable objects for skip object functionality: {identify_id: object_name}
  1157. printable_objects: dict = field(default_factory=dict)
  1158. # Objects that have been skipped during the current print
  1159. skipped_objects: list = field(default_factory=list)
  1160. # Pauses the slicer put into the running print, from its archived 3MF
  1161. # (#2984): threemf_tools.PausePoint, in print order. Empty when unknown.
  1162. pause_points: list = field(default_factory=list)
  1163. # Layers of those pauses a heads-up notification already went out for.
  1164. pause_warned_layers: set = field(default_factory=set)
  1165. # Fan speeds (0-100 percentage, None if not available for this model)
  1166. cooling_fan_speed: int | None = None # Part cooling fan
  1167. big_fan1_speed: int | None = None # Auxiliary fan
  1168. big_fan2_speed: int | None = None # Chamber/exhaust fan
  1169. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  1170. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  1171. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  1172. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  1173. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  1174. left_aux_fan_speed: int | None = None
  1175. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  1176. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  1177. # omits it, which is the case this flag exists to detect.
  1178. #
  1179. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  1180. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  1181. # harmless because only the P2S/X2D badge consults it — those models keep
  1182. # their unconditional "Chamber Fan" badge — but do not read this as
  1183. # "an exhaust kit is fitted" without also checking the model.
  1184. exhaust_fan_present: bool = False
  1185. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  1186. # Used by usage tracker to split filament weight on mid-print tray switch
  1187. tray_change_log: list = field(default_factory=list)
  1188. # Spools assigned to a tray during the current print, and the spool each
  1189. # assigned tray held at its start (services.spool_swaps, #3325).
  1190. spool_change_log: list = field(default_factory=list)
  1191. # Firmware version info (from info.module[name="ota"].sw_ver)
  1192. firmware_version: str | None = None
  1193. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  1194. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  1195. developer_mode: bool | None = None
  1196. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  1197. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  1198. # which uses the old protocol path; field not yet found). Consumers must treat
  1199. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  1200. ams_filament_backup: bool | None = None
  1201. # Stage name mapping from BambuStudio DeviceManager.cpp
  1202. STAGE_NAMES = {
  1203. 0: "Printing",
  1204. 1: "Auto bed leveling",
  1205. 2: "Heatbed preheating",
  1206. 3: "Vibration compensation",
  1207. 4: "Changing filament",
  1208. 5: "M400 pause",
  1209. 6: "Paused (filament ran out)",
  1210. 7: "Heating nozzle",
  1211. 8: "Calibrating dynamic flow",
  1212. 9: "Scanning bed surface",
  1213. 10: "Inspecting first layer",
  1214. 11: "Identifying build plate type",
  1215. 12: "Calibrating Micro Lidar",
  1216. 13: "Homing toolhead",
  1217. 14: "Cleaning nozzle tip",
  1218. 15: "Checking extruder temperature",
  1219. 16: "Paused by the user",
  1220. 17: "Pause (front cover fall off)",
  1221. 18: "Calibrating the micro lidar",
  1222. 19: "Calibrating flow ratio",
  1223. 20: "Pause (nozzle temperature malfunction)",
  1224. 21: "Pause (heatbed temperature malfunction)",
  1225. 22: "Filament unloading",
  1226. 23: "Pause (step loss)",
  1227. 24: "Filament loading",
  1228. 25: "Motor noise cancellation",
  1229. 26: "Pause (AMS offline)",
  1230. 27: "Pause (low speed of the heatbreak fan)",
  1231. 28: "Pause (chamber temperature control problem)",
  1232. 29: "Cooling chamber",
  1233. 30: "Pause (Gcode inserted by user)",
  1234. 31: "Motor noise showoff",
  1235. 32: "Pause (nozzle clumping)",
  1236. 33: "Pause (cutter error)",
  1237. 34: "Pause (first layer error)",
  1238. 35: "Pause (nozzle clog)",
  1239. 36: "Measuring motion precision",
  1240. 37: "Enhancing motion precision",
  1241. 38: "Measure motion accuracy",
  1242. 39: "Nozzle offset calibration",
  1243. 40: "High temperature auto bed leveling",
  1244. 41: "Auto Check: Quick Release Lever",
  1245. 42: "Auto Check: Door and Upper Cover",
  1246. 43: "Laser Calibration",
  1247. 44: "Auto Check: Platform",
  1248. 45: "Confirming BirdsEye Camera location",
  1249. 46: "Calibrating BirdsEye Camera",
  1250. 47: "Auto bed leveling - phase 1",
  1251. 48: "Auto bed leveling - phase 2",
  1252. 49: "Heating chamber",
  1253. 50: "Cooling heatbed",
  1254. 51: "Printing calibration lines",
  1255. 52: "Auto Check: Material",
  1256. 53: "Live View Camera Calibration",
  1257. 54: "Waiting for heatbed temperature",
  1258. 55: "Auto Check: Material Position",
  1259. 56: "Cutting Module Offset Calibration",
  1260. 57: "Measuring Surface",
  1261. 58: "Thermal Preconditioning",
  1262. 59: "Homing Blade Holder",
  1263. 60: "Calibrating Camera Offset",
  1264. 61: "Calibrating Blade Holder Position",
  1265. 62: "Hotend Pick and Place Test",
  1266. 63: "Waiting for Chamber temperature",
  1267. 64: "Preparing Hotend",
  1268. 65: "Calibrating nozzle clumping detection",
  1269. 66: "Purifying the chamber air",
  1270. 74: "Preparing", # Seen on H2D during print preparation
  1271. 77: "Preparing AMS",
  1272. }
  1273. def get_stage_name(stage: int) -> str:
  1274. """Get human-readable stage name from stage number."""
  1275. try:
  1276. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1277. except TypeError:
  1278. # `stage` is an int by convention only -- it comes straight out of the
  1279. # printer's JSON, and an unhashable value there would otherwise raise
  1280. # from inside the f-string that builds the stage-change log line, which
  1281. # is evaluated on every transition whatever the log level is set to.
  1282. # Labelling a value must not be able to abort the state update.
  1283. return f"Unknown stage ({stage})"
  1284. # #2547 end-of-print telemetry probe.
  1285. #
  1286. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1287. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1288. # but fires on no model in the field: across 247 support bundles there is not a
  1289. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1290. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1291. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1292. #
  1293. # We can't design a replacement from bundles we already have, because out of
  1294. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1295. # every other stage/action field is dropped unread. The obvious candidates
  1296. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1297. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1298. # own. Dumping the raw values for the window between the last object layer and
  1299. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1300. # anything — marks that moment.
  1301. #
  1302. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1303. # Nothing identifying, and nothing that could carry an access code.
  1304. _END_OF_PRINT_PROBE_FIELDS = (
  1305. "gcode_state",
  1306. "state",
  1307. "print_error",
  1308. "stg_cur",
  1309. "stg",
  1310. "stg_cd",
  1311. "mc_print_stage",
  1312. "mc_print_sub_stage",
  1313. "mc_action",
  1314. "mc_stage",
  1315. "print_real_action",
  1316. "print_gcode_action",
  1317. "spd_lvl",
  1318. "mc_percent",
  1319. "mc_remaining_time",
  1320. "layer_num",
  1321. "total_layer_num",
  1322. "home_flag",
  1323. "prepare_per",
  1324. )
  1325. # Frame budget for one print's probe. A long final layer can hold the window
  1326. # open for minutes at ~1 frame/second; this stops a single print from filling
  1327. # the log the user then has to upload.
  1328. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1329. # States that close the window. FINISH is the interesting one — the probe's
  1330. # whole job is to show what happened in the run-up to it.
  1331. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1332. class BambuMQTTClient:
  1333. """MQTT client for Bambu Lab printer communication."""
  1334. MQTT_PORT = 8883
  1335. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1336. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1337. _request_topic_cache: dict[str, bool] = {}
  1338. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1339. # the request topic. A SUBACK failure is the broker answering the question;
  1340. # a disconnect is only circumstantial, and any drop inside the window looks
  1341. # identical -- a network blip, the printer rebooting, the container being
  1342. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1343. # the rest of the process on a printer that supports it perfectly well
  1344. # (#2953). Require the drop to repeat before believing it; a printer that
  1345. # really does refuse the topic answers the same way every time and pays one
  1346. # extra reconnect for it.
  1347. _request_topic_probe_failures: dict[str, int] = {}
  1348. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1349. # Counter for generating unique MQTT client IDs across instances.
  1350. _client_instance_counter: int = 0
  1351. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1352. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1353. # every few seconds (and register_assignment_verification nudges a fresh
  1354. # pushall), so this only has to survive a couple of idle push intervals.
  1355. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1356. def __init__(
  1357. self,
  1358. ip_address: str,
  1359. serial_number: str,
  1360. access_code: str,
  1361. model: str | None = None,
  1362. on_state_change: Callable[[PrinterState], None] | None = None,
  1363. on_print_start: Callable[[dict], None] | None = None,
  1364. on_print_complete: Callable[[dict], None] | None = None,
  1365. on_ams_change: Callable[[list], None] | None = None,
  1366. on_layer_change: Callable[[int], None] | None = None,
  1367. on_print_progress: Callable[[int], None] | None = None,
  1368. on_bed_temp_update: Callable[[float], None] | None = None,
  1369. on_drying_complete: Callable[[int], None] | None = None,
  1370. on_drying_cycle_end: Callable[[DryingCycleEnd], None] | None = None,
  1371. on_print_running_observed: Callable[[dict], None] | None = None,
  1372. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1373. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1374. on_tray_change: Callable[[int, int], None] | None = None,
  1375. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1376. ):
  1377. self.ip_address = ip_address
  1378. self.serial_number = serial_number
  1379. self.access_code = access_code
  1380. self.model = model
  1381. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1382. self._debug_last: dict[str, object] = {}
  1383. self.on_state_change = on_state_change
  1384. self.on_print_start = on_print_start
  1385. self.on_print_complete = on_print_complete
  1386. self.on_ams_change = on_ams_change
  1387. # Fired when an AMS is moved to the switch's other inlet, which changes
  1388. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1389. self.on_fts_inlet_change = on_fts_inlet_change
  1390. self.on_layer_change = on_layer_change
  1391. # #2547: fired when `mc_percent` advances during a running print.
  1392. # `on_layer_change` stops firing the instant the final layer starts, so
  1393. # it is blind to the last few percent of a print — which is exactly the
  1394. # window the finish-photo frame bank needs to keep refreshing through.
  1395. # Progress is the one field that keeps ticking there and then freezes
  1396. # before the end G-code runs, so banking on it stays inside the print.
  1397. self.on_print_progress = on_print_progress
  1398. self.on_bed_temp_update = on_bed_temp_update
  1399. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1400. # the drying cycle just finished (auto- or manually-triggered).
  1401. # Receives the AMS id of the unit that finished drying.
  1402. self.on_drying_complete = on_drying_complete
  1403. # #2863: fired on the same edge with what was seen of the cycle, so the
  1404. # spools in that AMS can be stamped as dried.
  1405. self.on_drying_cycle_end = on_drying_cycle_end
  1406. # #1485 follow-up: fired the first time we see RUNNING state in a
  1407. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1408. # print, the #1304 first-push guard skipped the start event). Lets
  1409. # main.py capture a fresh timelapse baseline at restart-recovery
  1410. # time so the completion-time snapshot-diff still works. Receives
  1411. # the same shape as on_print_start (filename / subtask_name /
  1412. # remaining_time / raw_data / ams_mapping).
  1413. self.on_print_running_observed = on_print_running_observed
  1414. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1415. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1416. # with the process, and a long print outliving a restart would
  1417. # otherwise lose the segment boundaries the usage tracker splits on.
  1418. # Receives (global_tray_id, layer_num).
  1419. self.on_tray_change = on_tray_change
  1420. # #1721: fired the moment the printer enters the end-of-print
  1421. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1422. # we've hit the last layer / remaining_time<=0). This is the
  1423. # framing #1397 was after — toolhead parked, bed not yet
  1424. # dropped — but reached via a clean state signal instead of
  1425. # the per-layer M622 J1 macros which caused per-layer nozzle
  1426. # parks on slicer profiles with Timelapse Type = Smooth.
  1427. # A FINISH-state fallback below fires this same callback if
  1428. # stage 22 never arrives (cancel mid-print, external-spool-
  1429. # only prints, HMS halt before unload, firmware variants).
  1430. self.on_finish_photo_moment = on_finish_photo_moment
  1431. # #2582: fired after a spool assignment (ams_filament_setting +
  1432. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1433. # push landed or a timeout elapses without it. Receives
  1434. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1435. # tell the user "loaded" vs "assignment didn't take" instead of the
  1436. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1437. # feel random. See _check_assignment_verifications.
  1438. self.on_assignment_verified = on_assignment_verified
  1439. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1440. # value is the desired end-state we just pushed plus a monotonic
  1441. # deadline. Populated by register_assignment_verification, drained by
  1442. # _check_assignment_verifications on every AMS push.
  1443. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1444. # Per-AMS previous dry_time, used to detect the falling edge above.
  1445. # Seeded lazily as we observe each AMS unit.
  1446. self._previous_dry_times: dict[int, int] = {}
  1447. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1448. # A live cycle's countdown ticks once a minute; a command the firmware
  1449. # accepted but never actually started (observed on an H2D mid-print
  1450. # with two AMS-HT cycles already running: the third unit's timer sat
  1451. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1452. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1453. # reported as dry_countdown_stalled so the UI can stop claiming an
  1454. # active cycle that is not running.
  1455. self._dry_time_changed_at: dict[int, float] = {}
  1456. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1457. # last start. Bambu does not echo these back in the per-tick AMS push
  1458. # — only the dry_time countdown — so we cache what we sent to drive
  1459. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1460. self._drying_targets: dict[int, dict[str, object]] = {}
  1461. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1462. # ends a cycle far short of its duration, which on the telemetry alone
  1463. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1464. # log would otherwise blame the printer for our own decision (#2770).
  1465. self._drying_stops_sent: set[int] = set()
  1466. # Per-AMS record of the cycle in progress: the highest dry_time seen,
  1467. # whether its first minute was observed, and the target we sent for it.
  1468. # The target is copied here when the countdown starts because a stop
  1469. # drops _drying_targets before the cycle ends (#2863).
  1470. self._dry_cycles: dict[int, dict[str, object]] = {}
  1471. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1472. # for, so each is reported once rather than on every transition into it.
  1473. self._unnamed_stages_seen: set[int] = set()
  1474. self.state = PrinterState()
  1475. self._client: mqtt.Client | None = None
  1476. self._loop: asyncio.AbstractEventLoop | None = None
  1477. self._previous_gcode_state: str | None = None
  1478. self._previous_gcode_file: str | None = None
  1479. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1480. # #3485: the first state after startup was PAUSE with a print loaded,
  1481. # e.g. a printer in power-loss recovery when Bambuddy came back. Its
  1482. # PAUSE -> RUNNING is that print resuming, not a new one.
  1483. self._paused_at_startup: bool = False
  1484. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1485. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1486. # #1721: one-shot guard so the end-of-print stage-22 detector
  1487. # and the FINISH-state fallback don't both fire on the same
  1488. # print. Reset to False on every print start.
  1489. self._finish_photo_captured: bool = False
  1490. # #2702: one-shot re-request of the layer total. Armed at print start
  1491. # when the starting frame carried no `total_layer_num`, spent on the
  1492. # first layer advance that still has no denominator. Bambu firmware
  1493. # only re-sends *changed* fields, so a total we never received (or
  1494. # dropped) is only recoverable via a full pushall.
  1495. self._total_layers_refresh_armed: bool = False
  1496. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1497. # window has run for a print so a late FINISH re-send can't reopen it.
  1498. self._eop_probe_armed: bool = True
  1499. self._eop_probe_open: bool = False
  1500. self._eop_probe_frames: int = 0
  1501. self._eop_probe_last: dict = {}
  1502. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1503. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1504. # #3317: the layer the previous print ended on. Right after a print
  1505. # starts, the printer can send one frame that still carries it (H2S:
  1506. # `layer_num` 357 with `mc_percent` 0, then 0 a second later). Taken at
  1507. # face value, the 0 that follows saved 357 as this print's last layer,
  1508. # and a print failing at layer 0 was charged as finished. Frames with
  1509. # this value are ignored until the new print reports another layer.
  1510. self._stale_layer_num: int = 0
  1511. # The subtask_id minted for the most recent start_print() command. The
  1512. # printer echoes it back in status, but often not within the first few
  1513. # seconds — so on_print_start uses this as the id source when the
  1514. # printer hasn't reported it yet, letting queue/scheduled archives
  1515. # persist a restart-stable id from the moment they dispatch (#1485).
  1516. self.last_dispatch_subtask_id: str | None = None
  1517. # The printer's answer to the last print start it refused, as (result,
  1518. # reason); cleared when the next start is sent. The start watchdog
  1519. # reads it to stop waiting for a print that will not come.
  1520. self.last_start_refusal: tuple[str, str | None] | None = None
  1521. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1522. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1523. self._logging_enabled: bool = False
  1524. self._last_message_time: float = 0.0 # Track when we last received a message
  1525. # Count of report-topic messages received since the last (re)connect.
  1526. # Lets check_staleness() distinguish "printer never sent a status
  1527. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1528. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1529. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1530. self._report_messages_since_connect: int = 0
  1531. self._zero_report_hint_logged: bool = False
  1532. # Set by mark_power_off() to the gcode_state held just before we
  1533. # optimistically forced the printer to "unknown" (#2629). Restored on
  1534. # the next inbound message, because message traffic proves the power
  1535. # was never actually cut. None whenever no power-off is presumed.
  1536. self._state_before_power_off: str | None = None
  1537. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1538. # printer's pushes verbatim to slicers connected to a virtual printer).
  1539. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1540. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1541. self._disconnection_event: threading.Event | None = None
  1542. self._previous_ams_hash: str | None = None # Track AMS changes
  1543. # Track external-spool (vt_tray) identity changes separately: the AMS
  1544. # hash above covers only AMS units, so an external-spool-only filament
  1545. # swap would never re-trigger inventory reconciliation (#2575).
  1546. self._previous_vt_tray_hash: str | None = None
  1547. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1548. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1549. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1550. # Track which (ams_id, field) warnings have already been emitted this connection
  1551. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1552. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1553. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1554. # keyed by the sequence_id we sent, so two concurrent requests for
  1555. # different nozzle sizes can't steal each other's response (#1748).
  1556. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1557. self._sequence_id: int = 0
  1558. self._pending_kprofile_requests: dict[str, dict] = {}
  1559. # The printer's calibration table, one bucket per nozzle diameter.
  1560. #
  1561. # An extrusion_cali_get response is the complete table for *one* nozzle
  1562. # size, and the printer answers whoever asks — including BambuStudio,
  1563. # whose queries land on the same report topic we subscribe to. Assigning
  1564. # each response straight to state.kprofiles therefore let any single
  1565. # answer stand for the whole printer: a GitHub backup probing
  1566. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1567. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1568. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1569. # card because H2-series trays carry no `k` of their own — the slot's
  1570. # K value is resolved from cali_idx against exactly this list.
  1571. #
  1572. # Keyed by diameter so a response only ever replaces the bucket it
  1573. # actually describes; state.kprofiles is then the union across buckets.
  1574. # An empty answer for a nozzle the printer doesn't have empties that
  1575. # bucket alone.
  1576. self._kprofiles_by_nozzle: dict[str, list] = {}
  1577. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1578. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1579. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1580. # by await_cali_ack.
  1581. self._pending_cali_acks: dict[str, dict | None] = {}
  1582. # Objects sent in skip_objects that the printer's s_obj list has not
  1583. # shown yet: object id -> when it was sent. And the ids of each
  1584. # command by its sequence_id, for its answer.
  1585. self._unconfirmed_skips: dict[int, float] = {}
  1586. self._skip_commands: dict[str, list[int]] = {}
  1587. # Acks for RFID re-reads (ams_get_rfid, and the M620 R gcode_line
  1588. # fallback), keyed the same way. Drained by ams_refresh_tray (#3206).
  1589. self._pending_rfid_acks: dict[str, dict | None] = {}
  1590. # Identifies the one project_file *we* dispatched, so its echo on the
  1591. # topic can be told apart from a slicer's. One-shot: consumed by the
  1592. # first frame that matches. See _project_file_key.
  1593. self._own_project_file_key: str | None = None
  1594. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1595. # Key: module_name, Value: timestamp when command was sent
  1596. self._xcam_hold_start: dict[str, float] = {}
  1597. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1598. # True once the printer has sent `cfg`; from then on AMS Filament Backup
  1599. # is read from cfg only, never from home_flag (#3259).
  1600. self._backup_cfg_seen: bool = False
  1601. # True once a full status report arrived without `cfg`; from then on
  1602. # home_flag bit 10 is read from every status frame (#3259).
  1603. self._backup_home_flag_trusted: bool = False
  1604. # Whether the frame being handled carried the nozzles' snow: only then
  1605. # may snow overrule the slot the same frame reports as tray_now.
  1606. self._snow_in_frame = False
  1607. # The captured ams_mapping lives on the state (print_ams_mapping), so
  1608. # the status the card reads carries it; see _captured_ams_mapping.
  1609. # The destination of the dispatch it was captured from.
  1610. self._captured_mapping_url: str | None = None
  1611. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1612. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1613. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1614. self._has_a2l_am_unit: bool = False
  1615. # Rack AMS units already logged as detected (once per unit).
  1616. self._rack_ams_logged: set[int] = set()
  1617. self._tray_layout_key: tuple | None = None
  1618. self._tray_layout = TrayLayout()
  1619. # Why the last connection attempt was refused by the printer, or None
  1620. # when we have never seen a CONNACK failure since the last success.
  1621. # Without this a rejected access code was completely invisible: paho
  1622. # reports the follow-up disconnect as the generic "Unspecified error"
  1623. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1624. # printer stuck in a reconnect loop looked identical whether it was
  1625. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1626. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1627. # string, kept for the log line only.
  1628. self.last_connect_error: str | None = None
  1629. self.last_connect_error_name: str | None = None
  1630. # Request topic subscription tracking
  1631. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1632. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1633. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1634. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1635. self._request_topic_sub_mid: int | None = None
  1636. self._request_topic_sub_time: float = 0.0
  1637. self._request_topic_confirmed: bool = False
  1638. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1639. # we probe by sending an ams_filament_setting and checking the response.
  1640. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1641. self._dev_mode_probed: bool = False
  1642. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1643. self._dev_mode_probe_seq: str | None = None
  1644. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1645. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1646. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1647. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1648. # the printer reports it until the fault clears, so when a later hms[]
  1649. # arrives without it (user enabled Developer Mode and restarted the
  1650. # printer) we drop back to "unknown" and let the probe re-run instead of
  1651. # leaving a permanently-wrong False behind (#2732).
  1652. self._dev_mode_from_hms: bool = False
  1653. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1654. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1655. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1656. self._stale_reconnecting: bool = False
  1657. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1658. # when the frontend polls status faster than paho can reconnect.
  1659. self._last_stale_reconnect: float = 0.0
  1660. # Zombie session detection via ams_filament_setting response tracking (#887).
  1661. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1662. # that develop later (telemetry flows but publishes silently fail).
  1663. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1664. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1665. @property
  1666. def topic_subscribe(self) -> str:
  1667. return f"device/{self.serial_number}/report"
  1668. @property
  1669. def topic_publish(self) -> str:
  1670. return f"device/{self.serial_number}/request"
  1671. @property
  1672. def report_messages_since_connect(self) -> int:
  1673. """Count of report-topic messages received since the latest (re)connect.
  1674. Exposed for the connection diagnostic so it can distinguish "MQTT
  1675. broker accepted us but the printer never published" (typically a
  1676. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1677. bridge that happens to be idle right now. Zero immediately after a
  1678. fresh connect is normal; zero after a full status push cycle is the
  1679. wrong-serial failure mode.
  1680. """
  1681. return self._report_messages_since_connect
  1682. # Maximum time (seconds) without a message before considering connection stale
  1683. STALE_TIMEOUT = 60.0
  1684. def is_stale(self) -> bool:
  1685. """Check if the connection is stale (no messages for too long)."""
  1686. if self._last_message_time == 0:
  1687. return False # Never received a message yet
  1688. time_since_last = time.time() - self._last_message_time
  1689. return time_since_last > self.STALE_TIMEOUT
  1690. def mark_power_off(self) -> bool:
  1691. """Presume the printer lost power (smart plug switched off).
  1692. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1693. The presumption is undone by ``_on_message`` if the printer keeps
  1694. talking — inbound traffic proves the power was never cut (#2629).
  1695. Returns True when the state was actually changed.
  1696. """
  1697. if not self.state.connected:
  1698. return False
  1699. previous = self.state.state
  1700. # Blank the state BEFORE recording what to restore. This runs on the
  1701. # event loop while _on_message runs on the paho thread, and the restore
  1702. # is a two-step (read saved state, compare against "unknown"). Writing
  1703. # "unknown" first means an interleaved message either sees no saved
  1704. # state yet (and skips, leaving the next message to restore) or sees a
  1705. # consistent pair — never a saved state paired with a live state it
  1706. # then discards, which would strand the printer on "unknown".
  1707. self.state.connected = False
  1708. self.state.state = "unknown"
  1709. # Only the first mark wins: a second call before any message arrives
  1710. # must not overwrite the real state with the "unknown" it just wrote.
  1711. # Nothing to restore if the state was already blank.
  1712. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1713. self._state_before_power_off = previous
  1714. return True
  1715. def _restore_state_after_false_power_off(self) -> bool:
  1716. """Undo a presumed power-off once the printer proves it is alive.
  1717. ``connected`` self-heals on the next message, but ``state`` does not:
  1718. it is only rewritten when a payload carries ``gcode_state``, and the
  1719. steady-state ``push_status`` frames are partial. Without this the
  1720. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1721. and the queue scheduler treats the printer as not idle the whole time
  1722. (#2629). Returns True when a state was restored.
  1723. """
  1724. previous = self._state_before_power_off
  1725. self._state_before_power_off = None
  1726. if previous is None or self.state.state != "unknown":
  1727. return False
  1728. logger.info(
  1729. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1730. self.serial_number,
  1731. previous,
  1732. )
  1733. self.state.state = previous
  1734. return True
  1735. # Minimum seconds between stale reconnect attempts. Frontend polls
  1736. # status every few seconds — without a cooldown, each poll would
  1737. # force-close the socket before paho has time to reconnect.
  1738. STALE_RECONNECT_COOLDOWN = 30.0
  1739. def check_staleness(self) -> bool:
  1740. """Check staleness and update connected state if stale. Returns True if connected."""
  1741. if self.state.connected and self.is_stale():
  1742. # Don't force-close again if we already did recently — give paho
  1743. # time to reconnect and the printer time to send its first message.
  1744. now = time.time()
  1745. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1746. return self.state.connected
  1747. logger.warning(
  1748. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1749. )
  1750. # A connection that keeps going stale without ever receiving a
  1751. # status report is almost always a wrong or mis-cased serial
  1752. # number — the broker accepts the connection and the subscription
  1753. # regardless, but the printer publishes to device/<real-serial>/
  1754. # report, which is case-sensitive. Surface that once so the user
  1755. # has something actionable instead of an endless reconnect loop.
  1756. # Only meaningful once the *current* session has had time to receive
  1757. # something. _report_messages_since_connect is reset by _on_connect,
  1758. # so a reconnect that lands microseconds before this check leaves it
  1759. # at 0 for reasons that have nothing to do with the serial — which is
  1760. # how a healthy P1S ended up being told to go check its serial number
  1761. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1762. # on this session means the hint only fires when the printer really
  1763. # has published nothing to the topic we subscribed to.
  1764. # _connect_time of 0 means we have no timestamp to judge by (never went
  1765. # through _on_connect); fall back to the old unconditional behaviour
  1766. # rather than silently swallowing the hint.
  1767. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1768. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1769. self._zero_report_hint_logged = True
  1770. logger.warning(
  1771. "[%s] Connected and subscribed, but the printer has sent zero "
  1772. "status reports. The most common cause is a wrong or mis-cased "
  1773. "serial number — the device/<serial>/report MQTT topic is "
  1774. "case-sensitive. Verify the serial number configured in Bambuddy "
  1775. "exactly matches the printer.",
  1776. self.serial_number,
  1777. )
  1778. self._last_stale_reconnect = now
  1779. self.state.connected = False
  1780. if self.on_state_change:
  1781. self.on_state_change(self.state)
  1782. # Route based on caller thread — see force_reconnect_stale_session.
  1783. # check_staleness is normally called from FastAPI handlers (async,
  1784. # gets the hard-reset path) but the dispatcher exists for safety.
  1785. self._stale_reconnecting = True
  1786. self._reset_client_for_reconnect()
  1787. return self.state.connected
  1788. def force_reconnect_stale_session(self, reason: str) -> None:
  1789. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1790. # arriving but our publishes don't reach the printer.
  1791. #
  1792. # Two routing paths:
  1793. #
  1794. # Async-context callers (queue dispatch deadline)
  1795. # → full client teardown + fresh client_id. Wipes paho's client-side
  1796. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1797. # `project_file` from the broken session would otherwise replay on
  1798. # reconnect, mixing stale commands into the next dispatch and
  1799. # triggering 0500_4003 SD R/W on the printer.
  1800. #
  1801. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1802. # zombie detection, both inside `_update_state`)
  1803. # → socket-close fallback. There is no running loop on that thread to
  1804. # hand the rebuilt client, so close the socket and let paho's own
  1805. # loop detect the broken connection and auto-reconnect (same
  1806. # instance, same client_id). paho would re-send its old outbox on
  1807. # that reconnect; _on_connect empties it first (#3454).
  1808. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1809. self._stale_reconnecting = True
  1810. self.state.connected = False
  1811. if self.on_state_change:
  1812. self.on_state_change(self.state)
  1813. self._reset_client_for_reconnect()
  1814. def _reset_client_for_reconnect(self) -> None:
  1815. """Route between hard-reset and socket-close based on caller thread.
  1816. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1817. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1818. answers that and identifies the caller in one go — paho's callback
  1819. thread has no loop; every legitimate hard-reset caller (FastAPI
  1820. handlers, background async tasks) does."""
  1821. try:
  1822. loop = asyncio.get_running_loop()
  1823. except RuntimeError:
  1824. loop = None
  1825. if loop is not None:
  1826. self._loop = loop
  1827. self._hard_reset_client()
  1828. else:
  1829. self._socket_close_for_reconnect()
  1830. def _hard_reset_client(self) -> None:
  1831. """Tear down the paho client entirely and rebuild it with a fresh
  1832. client_id, so the broker drops the old session and paho's local
  1833. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1834. Caller is responsible for setting ``_stale_reconnecting`` and
  1835. broadcasting the disconnected state.
  1836. Returns as fast as it can build a client: the old one's teardown is
  1837. handed off rather than waited on, because waiting on it is what
  1838. stopped the event loop in #3068. See ``retire_paho_client``."""
  1839. old_client = self._client
  1840. self._client = None
  1841. if old_client is not None:
  1842. retire_paho_client(old_client, self.serial_number)
  1843. # Skip reconnect if no asyncio loop is available (test environment or
  1844. # pre-init). The next initial connect() call from PrinterManager will
  1845. # set up the client fresh.
  1846. if self._loop is None:
  1847. return
  1848. try:
  1849. self.connect(loop=self._loop)
  1850. except Exception as e:
  1851. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1852. def _socket_close_for_reconnect(self) -> None:
  1853. """Close the underlying socket so paho's loop thread detects the
  1854. broken connection and triggers auto-reconnect on the SAME client
  1855. instance. Safe to call from paho's own network thread (the loop
  1856. polls the socket on every iteration and handles a closed socket
  1857. gracefully). Used as a fallback when hard-reset isn't safe. The old
  1858. outbox is not re-sent: _on_connect empties it first (#3454)."""
  1859. if self._client:
  1860. try:
  1861. sock = self._client.socket()
  1862. if sock:
  1863. sock.close()
  1864. except Exception:
  1865. pass
  1866. def _drop_previous_connection_commands(self, client) -> None:
  1867. """Forget every command queued on an earlier connection (#3454).
  1868. Called first in on_connect, which paho runs before it re-sends its
  1869. old outbox. Makes every printer command at most once per connection;
  1870. a command lost in the seconds before a drop is clicked again."""
  1871. dropped = discard_queued_publishes(client)
  1872. if dropped is None:
  1873. logger.warning(
  1874. "[%s] Cannot clear paho's outbox on reconnect (paho internals changed); "
  1875. "commands from the previous connection may be sent again",
  1876. self.serial_number,
  1877. )
  1878. elif dropped:
  1879. logger.info(
  1880. "[%s] Dropped %d command(s) queued on the previous MQTT connection",
  1881. self.serial_number,
  1882. dropped,
  1883. )
  1884. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1885. if rc == 0:
  1886. # First, before anything here publishes on the new connection.
  1887. self._drop_previous_connection_commands(client)
  1888. self.state.connected = True
  1889. self.last_connect_error = None
  1890. self.last_connect_error_name = None
  1891. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1892. # A dropped-and-restored MQTT session means the presumed power-off was
  1893. # real (or at least that the printer restarted): there is nothing
  1894. # legitimate left to restore, and the printer will send a full status
  1895. # push shortly. Dropping the saved state keeps a stale one from being
  1896. # broadcast ahead of the first real report (#2629, #1679).
  1897. self._state_before_power_off = None
  1898. # Reset per-connection warning state so warnings fire once per (re)connection
  1899. self._ams_version_warned = set()
  1900. # Preserve cached developer_mode across auto-reconnects to avoid
  1901. # re-probing on every reconnect. The probe (ams_filament_setting to
  1902. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1903. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1904. # once when developer_mode is truly unknown (first connect).
  1905. # Reset probe tracking so stale timeout state doesn't carry over.
  1906. self._dev_mode_probed = False
  1907. self._dev_mode_needs_probe = False
  1908. self._dev_mode_probe_seq = None
  1909. self._dev_mode_probe_time = 0.0
  1910. self._dev_mode_probe_failures = 0
  1911. self._connect_time = time.monotonic()
  1912. self._report_messages_since_connect = 0
  1913. self._last_ams_cmd_time = 0.0
  1914. self._ams_cmd_unanswered = 0
  1915. # Drop any assignment verifications that were mid-flight before the
  1916. # reconnect — their deadlines are stale and the tray state we would
  1917. # compare against is about to be re-pushed from scratch (#2582).
  1918. # Dropping is silent (no failure event) on purpose.
  1919. self._pending_assignments.clear()
  1920. client.subscribe(self.topic_subscribe)
  1921. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1922. if self._request_topic_supported:
  1923. result, mid = client.subscribe(self.topic_publish)
  1924. if result == mqtt.MQTT_ERR_SUCCESS:
  1925. self._request_topic_sub_mid = mid
  1926. self._request_topic_sub_time = time.time()
  1927. self._request_topic_confirmed = False
  1928. else:
  1929. logger.warning(
  1930. "[%s] Failed to send request topic subscription",
  1931. self.serial_number,
  1932. )
  1933. self._request_topic_supported = False
  1934. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1935. # Request full status update (includes nozzle info in push_status response)
  1936. self._request_push_all()
  1937. # Request firmware version info
  1938. self._request_version()
  1939. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1940. # The correct nozzle data comes from push_status.
  1941. # Prime K-profile request (Bambu printers often ignore first request)
  1942. self._prime_kprofile_request()
  1943. # Immediately broadcast connection state change
  1944. if self.on_state_change:
  1945. self.on_state_change(self.state)
  1946. else:
  1947. self.state.connected = False
  1948. self._record_connect_refusal(rc)
  1949. def _record_connect_refusal(self, rc) -> None:
  1950. """Log and remember why the printer refused the MQTT connection.
  1951. The failure branch of ``_on_connect`` used to be a bare
  1952. ``connected = False``, which threw away the only signal that says
  1953. *why* a printer never comes online. The user-visible result was a
  1954. 30-second reconnect loop logging nothing but paho's generic
  1955. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1956. powered-off printer, so "my printer won't print" reports could not be
  1957. triaged without a round trip (#2698).
  1958. Never logs the access code itself; the code is the likely culprit but
  1959. printing it would put a credential in every support bundle.
  1960. """
  1961. code = getattr(rc, "value", rc)
  1962. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1963. self.last_connect_error_name = name
  1964. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1965. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1966. logger.warning(
  1967. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1968. "or serial number is wrong — the access code changes every time LAN Only or "
  1969. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1970. self.serial_number,
  1971. name,
  1972. code,
  1973. )
  1974. else:
  1975. self.last_connect_error = CONNECT_ERROR_REFUSED
  1976. logger.warning(
  1977. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1978. self.serial_number,
  1979. name,
  1980. code,
  1981. )
  1982. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1983. """Handle SUBACK responses to detect request topic subscription rejection."""
  1984. if mid == self._request_topic_sub_mid:
  1985. for rc in reason_code_list:
  1986. if rc.is_failure:
  1987. logger.warning(
  1988. "[%s] Request topic subscription rejected (code=%d: %s). "
  1989. "ams_mapping capture from slicer-initiated prints unavailable.",
  1990. self.serial_number,
  1991. rc.value,
  1992. rc.getName(),
  1993. )
  1994. self._request_topic_supported = False
  1995. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1996. else:
  1997. logger.info(
  1998. "[%s] Request topic subscription accepted. "
  1999. "ams_mapping capture enabled for slicer-initiated prints.",
  2000. self.serial_number,
  2001. )
  2002. self._request_topic_confirmed = True
  2003. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  2004. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  2005. self._request_topic_sub_mid = None
  2006. self._request_topic_sub_time = 0.0
  2007. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  2008. # Always unblock disconnect() callers, regardless of whether we suppress
  2009. # the state broadcast below. disconnect() sets _disconnection_event and
  2010. # waits on it — every callback path must fire it.
  2011. if self._disconnection_event:
  2012. self._disconnection_event.set()
  2013. # If we intentionally closed the socket for stale reconnect, don't broadcast
  2014. # another state change — check_staleness() already set connected=False and
  2015. # notified the UI. Just log and let paho auto-reconnect.
  2016. if self._stale_reconnecting:
  2017. logger.info(
  2018. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  2019. self.serial_number,
  2020. rc,
  2021. )
  2022. return
  2023. # Ignore spurious disconnect callbacks if we've received a message recently
  2024. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  2025. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  2026. # — only suppress when rc indicates a clean/normal disconnect.
  2027. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  2028. time_since_last_message = time.time() - self._last_message_time
  2029. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  2030. logger.debug(
  2031. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  2032. )
  2033. return
  2034. # Carry the last CONNACK refusal into the disconnect line. paho reports
  2035. # the drop that follows a refused CONNACK as "Unspecified error", so on
  2036. # its own this line says nothing useful about a printer that is looping
  2037. # on bad credentials — and this is the line that fills a support bundle
  2038. # (#2698).
  2039. if self.last_connect_error:
  2040. logger.warning(
  2041. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  2042. self.serial_number,
  2043. rc,
  2044. disconnect_flags,
  2045. self.last_connect_error_name,
  2046. )
  2047. else:
  2048. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  2049. # Detect if request topic subscription caused the disconnect.
  2050. # If we just subscribed and got disconnected before any SUBACK confirmation,
  2051. # the broker likely killed the connection due to the unauthorized subscription.
  2052. if (
  2053. self._request_topic_sub_time > 0
  2054. and not self._request_topic_confirmed
  2055. and time.time() - self._request_topic_sub_time < 10.0
  2056. # A disconnect we asked for says nothing about the subscription.
  2057. and self._disconnection_event is None
  2058. ):
  2059. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  2060. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  2061. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  2062. logger.warning(
  2063. "[%s] Disconnected shortly after request topic subscription %d times. "
  2064. "Disabling request topic for this printer — ams_mapping capture from "
  2065. "slicer-initiated prints is unavailable, and their filament will be "
  2066. "attributed from the printer's own tray reporting instead.",
  2067. self.serial_number,
  2068. failures,
  2069. )
  2070. self._request_topic_supported = False
  2071. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  2072. else:
  2073. logger.info(
  2074. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  2075. "Retrying it on the next connection before giving up.",
  2076. self.serial_number,
  2077. failures,
  2078. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  2079. )
  2080. self._request_topic_sub_mid = None
  2081. self._request_topic_sub_time = 0.0
  2082. self.state.connected = False
  2083. if self.on_state_change:
  2084. self.on_state_change(self.state)
  2085. def _log_message(self, topic: str, direction: str, raw: str) -> None:
  2086. """Record a message for the MQTT Debug log, as it arrived.
  2087. Parsed again from the raw text rather than shared with the handlers:
  2088. processing keeps the payload's "print" dict as the new raw_data and
  2089. writes Bambuddy's merged AMS list and other state into it, so a shared
  2090. dict showed Bambuddy's state instead of what the printer sent (#3356).
  2091. """
  2092. self._message_log.append(
  2093. MQTTLogEntry(
  2094. timestamp=datetime.now(timezone.utc).isoformat(),
  2095. topic=topic,
  2096. direction=direction,
  2097. payload=json.loads(raw),
  2098. )
  2099. )
  2100. def _on_message(self, client, userdata, msg):
  2101. for handler in self._raw_message_handlers:
  2102. try:
  2103. handler(msg.topic, msg.payload)
  2104. except Exception:
  2105. logger.exception(
  2106. "[%s] raw-message handler crashed for topic=%s",
  2107. self.serial_number,
  2108. msg.topic,
  2109. )
  2110. try:
  2111. try:
  2112. raw = msg.payload.decode()
  2113. except UnicodeDecodeError:
  2114. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  2115. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  2116. raw = msg.payload.decode(errors="replace")
  2117. logger.warning(
  2118. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  2119. self.serial_number,
  2120. msg.topic,
  2121. len(msg.payload),
  2122. )
  2123. payload = json.loads(raw)
  2124. # Track last message time - receiving a message proves we're connected
  2125. self._last_message_time = time.time()
  2126. self.state.connected = True
  2127. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  2128. if msg.topic == self.topic_publish:
  2129. # Record it before returning. This topic carries every command
  2130. # travelling *to* the printer, including the ones Bambu Studio
  2131. # sends, and it used to be the one thing an MQTT capture could
  2132. # never show -- which is why "what does Studio put in the drying
  2133. # command?" had no answer from a user's log (#2774). Filed as
  2134. # "out" so the direction filter groups it with our own commands
  2135. # rather than with printer telemetry; anything we send
  2136. # lands twice, once on publish and once on the
  2137. # broker's echo, and the pair is itself evidence the command
  2138. # reached the broker.
  2139. if self._logging_enabled:
  2140. self._log_message(msg.topic, "out", raw)
  2141. self._handle_request_message(payload)
  2142. return
  2143. # Count status reports per connection so check_staleness() can tell
  2144. # "printer never sent a report" apart from a mid-session quiet gap.
  2145. if msg.topic == self.topic_subscribe:
  2146. self._report_messages_since_connect += 1
  2147. # Only report-topic traffic proves the *printer* is alive — the
  2148. # request topic also carries slicer/Bambuddy commands.
  2149. if self._state_before_power_off is not None:
  2150. if self._restore_state_after_false_power_off() and self.on_state_change:
  2151. self.on_state_change(self.state)
  2152. # Log message if logging is enabled
  2153. if self._logging_enabled:
  2154. self._log_message(msg.topic, "in", raw)
  2155. self._process_message(payload)
  2156. except json.JSONDecodeError:
  2157. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  2158. @property
  2159. def _captured_ams_mapping(self):
  2160. """The ams_mapping captured from the current print's command.
  2161. Kept on the state so the status shows it (the slot pills, #1762): the
  2162. printer's own push almost never carries one.
  2163. """
  2164. return self.state.print_ams_mapping
  2165. @_captured_ams_mapping.setter
  2166. def _captured_ams_mapping(self, mapping) -> None:
  2167. self.state.print_ams_mapping = mapping
  2168. def _handle_request_message(self, data: dict) -> None:
  2169. """Intercept print commands on the request topic to capture ams_mapping."""
  2170. print_data = data.get("print", {})
  2171. if not isinstance(print_data, dict):
  2172. return
  2173. command = print_data.get("command", "")
  2174. if command == "project_file":
  2175. # Where the dispatcher put the sliced file. Captured for every
  2176. # project_file, ours included: we publish to this same topic and
  2177. # subscribe to it, so whoever dispatched last wins, which is exactly
  2178. # the print the archive lookup is about to go looking for (#2780).
  2179. url = print_data.get("url")
  2180. if isinstance(url, str) and url:
  2181. self.state.current_project_url = url
  2182. self.state.last_project_url = url
  2183. if "ams_mapping" in print_data:
  2184. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2185. self._captured_mapping_url = url if isinstance(url, str) else None
  2186. logger.info(
  2187. "[%s] Captured ams_mapping from print command: %s",
  2188. self.serial_number,
  2189. self._captured_ams_mapping,
  2190. )
  2191. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  2192. # slicer-launched project_file passes through the request topic,
  2193. # log the full payload so we can diff Studio's field set against
  2194. # ours.
  2195. #
  2196. # This used to read `sequence_id != "20000"`, on the belief that
  2197. # 20000 was ours alone. It is not: 20000 is the slicer convention
  2198. # Bambuddy adopted -- bind_server documents the slicer sending it
  2199. # during detect, and measured on the wire OrcaSlicer dispatched
  2200. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  2201. # counting up from the same base. So the test swallowed whichever
  2202. # slicer dispatch happened to land on 20000, which on a fresh
  2203. # slicer start is the first one. Match our own dispatch instead.
  2204. if self._project_file_key(print_data) == self._own_project_file_key:
  2205. self._own_project_file_key = None
  2206. else:
  2207. logger.info(
  2208. "[%s] External project_file payload: %s",
  2209. self.serial_number,
  2210. json.dumps(print_data),
  2211. )
  2212. def _capture_report_project_file(self, print_data: dict) -> None:
  2213. """Read a print's destination off a ``project_file`` *response* (#1820).
  2214. ``_handle_request_message`` only ever sees the request topic, so a print
  2215. started from the printer's own touchscreen -- which publishes nothing --
  2216. left ``current_project_url`` at None, and the storage verdict fell
  2217. through to the ``sdcard`` fallback for the one case it was written for.
  2218. On an H2S that flag is True (its "card" is the internal eMMC), so the
  2219. verdict came back reachable and the ~110-connection sweep ran in full.
  2220. The printer does announce it: an unsolicited ``project_file`` response
  2221. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  2222. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  2223. This also covers an install nobody had in view: some brokers refuse the
  2224. request-topic subscription, and on those no print of any kind has ever
  2225. populated the field.
  2226. Both kinds of ``project_file`` on this topic are read -- the printer's
  2227. echo of a dispatch and a screen start -- because both name the
  2228. destination in ``url``, which is the only thing the verdict wants. What
  2229. this must NOT do is reuse ``_handle_request_message``'s "External
  2230. project_file payload" diagnostic: our own dispatch is echoed on *both*
  2231. topics, the request-topic echo arrives first and clears
  2232. ``_own_project_file_key``, so by the time this frame lands the key is
  2233. already None and every Bambuddy-started print would log itself as
  2234. someone else's.
  2235. """
  2236. # Same shape as _handle_request_message: the frame is whatever the
  2237. # printer put on the wire, and this is the first thing to touch it.
  2238. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  2239. return
  2240. # A refused dispatch names a file that was never written. Acting on it
  2241. # would pin an archive on a destination nothing ever went to. Logged:
  2242. # nothing else says the printer refused a print it was sent.
  2243. result = str(print_data.get("result") or "")
  2244. if result.upper() != "SUCCESS":
  2245. logger.info(
  2246. "[%s] Printer refused a print start (project_file): result=%s reason=%s url=%s",
  2247. self.serial_number,
  2248. result,
  2249. print_data.get("reason"),
  2250. print_data.get("url"),
  2251. )
  2252. self.last_start_refusal = (result, print_data.get("reason"))
  2253. return
  2254. url = print_data.get("url")
  2255. if not isinstance(url, str) or not url:
  2256. return
  2257. if self.state.current_project_url != url:
  2258. logger.info(
  2259. "[%s] Print destination from the report topic: %s",
  2260. self.serial_number,
  2261. url,
  2262. )
  2263. self.state.current_project_url = url
  2264. self.state.last_project_url = url
  2265. # On a screen start this frame is the only place the mapping appears --
  2266. # no slicer ever sent one. Fill a gap only: when the request topic
  2267. # already captured this print's mapping that copy is the slicer's own,
  2268. # and the echo can arrive without the field at all. A mapping captured
  2269. # for another destination is from a dispatch that never ran (refused,
  2270. # or cancelled before it started, so no completion cleared it).
  2271. stale = self._captured_ams_mapping is not None and self._captured_mapping_url != url
  2272. if (self._captured_ams_mapping is None or stale) and isinstance(print_data.get("ams_mapping"), list):
  2273. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2274. self._captured_mapping_url = url
  2275. logger.info(
  2276. "[%s] Captured ams_mapping from print response: %s",
  2277. self.serial_number,
  2278. self._captured_ams_mapping,
  2279. )
  2280. def _resolve_captured_mapping(self, print_data: dict) -> object:
  2281. """The ``ams_mapping`` of a project_file, with external spools resolved
  2282. from its ``ams_mapping2`` (#3166)."""
  2283. from backend.app.utils.printer_models import is_dual_nozzle_model
  2284. return resolve_external_spools_in_mapping(
  2285. print_data.get("ams_mapping"),
  2286. print_data.get("ams_mapping2"),
  2287. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  2288. self.tray_layout,
  2289. )
  2290. @staticmethod
  2291. def _project_file_key(print_data: dict) -> str:
  2292. """Identity of a project_file dispatch, for telling ours from a slicer's.
  2293. Sequence id alone cannot do it -- every slicer counts up from the same
  2294. 20000 -- so this also carries the file and its destination, which differ
  2295. between any two real dispatches.
  2296. """
  2297. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  2298. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  2299. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  2300. The state dumps in the push_status handler fire whenever their field is
  2301. *present* in the frame — and a full push_status carries every field, so
  2302. they fire on every frame regardless of whether anything changed. Several
  2303. even say "updated" or "changes" in their own comment while doing nothing
  2304. of the sort.
  2305. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  2306. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  2307. minutes: the reporter enabled debug logging as asked and the support
  2308. bundle came back holding under five minutes of history, almost none of it
  2309. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  2310. these dumps.
  2311. Deduplicating on the value keeps every transition — which is the only part
  2312. anyone reads these lines for — and drops the steady-state repetition.
  2313. ``value`` must capture everything interpolated into ``msg``, or a change
  2314. will be swallowed; pass a tuple when the message renders several fields.
  2315. """
  2316. if not logger.isEnabledFor(logging.DEBUG):
  2317. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  2318. # and these clients outlive the toggle. Letting INFO-level frames warm
  2319. # the cache would be self-defeating: the operator turns debug on
  2320. # precisely to see the printer's current state, and a cache already
  2321. # holding every steady-state value would suppress that baseline until
  2322. # something happened to change. On an idle printer the bundle would
  2323. # come back with none of these lines at all.
  2324. #
  2325. # So while debug is off we record nothing and drop whatever we had.
  2326. # Every enable then starts cold and dumps a full baseline on the next
  2327. # frame, exactly as it did before this method existed.
  2328. self._debug_last.clear()
  2329. return
  2330. if self._debug_last.get(key) == value:
  2331. return
  2332. self._debug_last[key] = value
  2333. logger.debug(msg, *args)
  2334. def _process_message(self, payload: dict):
  2335. """Process incoming MQTT message from printer."""
  2336. # Handle top-level AMS data (comes outside of "print" key)
  2337. # Wrap in try/except to prevent breaking the MQTT connection
  2338. if "ams" in payload:
  2339. try:
  2340. self._snow_in_frame = False # a bare AMS frame carries no extruder data
  2341. self._handle_ams_data(payload["ams"])
  2342. except Exception as e:
  2343. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  2344. # Handle xcam data (camera settings and AI detection) at top level
  2345. if "xcam" in payload:
  2346. xcam_data = payload["xcam"]
  2347. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  2348. self._parse_xcam_data(xcam_data)
  2349. # Fire state change callback for top-level xcam (not nested in "print")
  2350. if "print" not in payload and self.on_state_change:
  2351. self.on_state_change(self.state)
  2352. # Handle system responses (accessories info, etc.)
  2353. if "system" in payload:
  2354. system_data = payload["system"]
  2355. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  2356. self._handle_system_response(system_data)
  2357. # Handle info responses (firmware version info from get_version command)
  2358. if "info" in payload:
  2359. info_data = payload["info"]
  2360. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2361. self._handle_version_info(info_data)
  2362. # Parse WiFi signal at top level (some printers send it here)
  2363. if "wifi_signal" in payload:
  2364. wifi_signal = payload["wifi_signal"]
  2365. if isinstance(wifi_signal, (int, float)):
  2366. self.state.wifi_signal = int(wifi_signal)
  2367. elif isinstance(wifi_signal, str):
  2368. try:
  2369. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2370. except ValueError:
  2371. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2372. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2373. from backend.app.utils.printer_models import has_ethernet
  2374. if has_ethernet(self.model):
  2375. self.state.wired_network = self.state.wifi_signal == -90
  2376. # Parse developer LAN mode from top-level "fun" field
  2377. # Some firmware versions send "fun" at the top level, others inside "print"
  2378. if "fun" in payload:
  2379. try:
  2380. fun_val = payload["fun"]
  2381. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2382. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2383. except (ValueError, TypeError):
  2384. pass
  2385. if "print" in payload:
  2386. print_data = payload["print"]
  2387. # Before anything reads the state: this is where a touchscreen-
  2388. # started print announces where its file lives, and the print-start
  2389. # handler asks ~2 s later (#1820).
  2390. self._capture_report_project_file(print_data)
  2391. # Check if xcam is nested inside print data
  2392. if "xcam" in print_data:
  2393. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2394. self._parse_xcam_data(print_data["xcam"])
  2395. # Log when we see gcode_state changes
  2396. if "gcode_state" in print_data:
  2397. logger.debug(
  2398. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2399. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2400. )
  2401. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2402. # new-protocol printers. Verified against OrcaSlicer's
  2403. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2404. # and live H2D ON/OFF capture 2026-06-20.
  2405. #
  2406. # Families without cfg (P1S, P1P, A1, A1 Mini) carry it in home_flag
  2407. # bit 10 (#3259). Trusted once a full status report (the same
  2408. # >30-key test as the developer-mode probe) arrived without cfg;
  2409. # from then on every status frame that carries home_flag is read,
  2410. # so a toggle in the slicer shows up without a Force Refresh (P1S
  2411. # capture: each toggle came in a 4-6 key update frame). Before
  2412. # that nothing is read from small frames, so a cfg printer can't
  2413. # be misread from a frame that arrives ahead of its first cfg.
  2414. # Printers that send cfg keep reading it alone.
  2415. #
  2416. # Hold-timer guard: when the user just toggled via the badge, the
  2417. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2418. # for ~3 s before the firmware reflects the change. Without this
  2419. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2420. # Only from a status frame: a project_file ack echoes our own
  2421. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2422. # stuck on every family that doesn't repeat `cfg` in its periodic
  2423. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2424. new_backup = None
  2425. if is_printer_status_frame(print_data):
  2426. if "cfg" in print_data:
  2427. self._backup_cfg_seen = True
  2428. new_backup = parse_ams_filament_backup_from_cfg(print_data["cfg"])
  2429. elif not self._backup_cfg_seen:
  2430. if len(print_data) > 30:
  2431. self._backup_home_flag_trusted = True
  2432. if self._backup_home_flag_trusted:
  2433. new_backup = parse_ams_filament_backup_from_home_flag(print_data.get("home_flag"))
  2434. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2435. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2436. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2437. logger.debug(
  2438. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2439. self.serial_number,
  2440. time.time() - hold_start,
  2441. )
  2442. else:
  2443. logger.info(
  2444. "[%s] AMS Filament Backup: %s",
  2445. self.serial_number,
  2446. "ON" if new_backup else "OFF",
  2447. )
  2448. self.state.ams_filament_backup = new_backup
  2449. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2450. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2451. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2452. if not self._is_dual_nozzle and "device" in print_data:
  2453. dev = print_data.get("device")
  2454. if isinstance(dev, dict):
  2455. ext_info = dev.get("extruder", {}).get("info", [])
  2456. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2457. self._is_dual_nozzle = True
  2458. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2459. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2460. # out of the AMS info bits, but only means anything once we know a
  2461. # switch is installed. Parsing them the other way round would lose
  2462. # the binding on every frame where the two arrive together.
  2463. self._parse_fila_switch(print_data)
  2464. # Before _handle_ams_data too: an H2D's tray_now is a bare slot that
  2465. # this frame's extruder data places (which nozzle, which AMS).
  2466. self._snow_in_frame = self._parse_extruder_position(print_data)
  2467. self._parse_extruder_slots(print_data)
  2468. # Handle AMS data that comes inside print key
  2469. if "ams" in print_data:
  2470. try:
  2471. self._handle_ams_data(print_data["ams"])
  2472. except Exception as e:
  2473. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2474. # Handle vir_slot (H2-series external spool data) — list of external trays
  2475. # Process vir_slot FIRST so it takes priority over vt_tray
  2476. if "vir_slot" in print_data:
  2477. vir_slot = print_data["vir_slot"]
  2478. if isinstance(vir_slot, list) and vir_slot:
  2479. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2480. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2481. # Remap id=255→254 for single-slot printers so active detection works.
  2482. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2483. # A nozzle-rack printer (H3C) reports one input per hotend,
  2484. # 247-255, kept as reported.
  2485. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2486. vir_slot[0]["id"] = "254"
  2487. self.state.raw_data["vt_tray"] = vir_slot
  2488. # Handle vt_tray (virtual tray / external spool) data
  2489. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2490. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2491. # which would overwrite the correct multi-slot vir_slot data)
  2492. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2493. vt_tray = print_data["vt_tray"]
  2494. existing = self.state.raw_data.get("vt_tray")
  2495. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2496. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2497. pass # Keep the vir_slot data
  2498. elif (cached_slot := _external_slot_to_merge(vt_tray, existing)) is not None:
  2499. # A delta carries only what changed, often without the
  2500. # id: a colour-only change on an A1 mini pushes just
  2501. # {"tray_color": ...}. Stored as it came, it emptied the
  2502. # slot until the next full push (#3513).
  2503. self.state.raw_data["vt_tray"] = [{**cached_slot, **vt_tray}]
  2504. else:
  2505. if isinstance(vt_tray, dict):
  2506. vt_tray = [vt_tray]
  2507. self.state.raw_data["vt_tray"] = vt_tray
  2508. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2509. # units, and _handle_ams_data runs before this block — so a change
  2510. # to the external spool alone (e.g. swapping generic TPU for generic
  2511. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2512. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2513. # external-spool identity changes here and fire the same callback.
  2514. self._maybe_trigger_external_spool_change()
  2515. # The external slot's own read-back: its delta can come without
  2516. # any AMS data, which is where the check otherwise runs (#3513).
  2517. if "vt_tray" in print_data and self._pending_assignments:
  2518. self._check_assignment_verifications()
  2519. # Parse ams_status directly from print data (NOT from print.ams)
  2520. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2521. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2522. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2523. if "ams_status" in print_data:
  2524. raw_ams_status = print_data["ams_status"]
  2525. if isinstance(raw_ams_status, str):
  2526. try:
  2527. self.state.ams_status = int(raw_ams_status)
  2528. except ValueError:
  2529. self.state.ams_status = 0
  2530. else:
  2531. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2532. # Compute main and sub status
  2533. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2534. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2535. # Log when ams_status changes (for filament change tracking debug)
  2536. self._debug_on_change(
  2537. "ams_status:print",
  2538. self.state.ams_status,
  2539. "[%s] ams_status: %s (main=%s, sub=%s)",
  2540. self.serial_number,
  2541. self.state.ams_status,
  2542. self.state.ams_status_main,
  2543. self.state.ams_status_sub,
  2544. )
  2545. # Check for command responses
  2546. if "command" in print_data:
  2547. cmd = print_data.get("command")
  2548. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2549. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2550. # INFO, not debug: this is the printer's verdict on a write
  2551. # the user just made, and it was invisible in support
  2552. # bundles for as long as it sat at DEBUG (#2718). Same
  2553. # reasoning as ams_filament_drying below.
  2554. logger.info(
  2555. "[%s] %s response: result=%s reason=%s seq=%s",
  2556. self.serial_number,
  2557. cmd,
  2558. print_data.get("result"),
  2559. print_data.get("reason", ""),
  2560. print_data.get("sequence_id"),
  2561. )
  2562. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2563. ack_seq = str(print_data.get("sequence_id", ""))
  2564. if ack_seq in self._pending_cali_acks:
  2565. self._pending_cali_acks[ack_seq] = print_data
  2566. elif cmd == "skip_objects":
  2567. self._handle_skip_objects_answer(print_data)
  2568. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2569. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2570. # A refused ams_filament_setting is the printer's verdict on
  2571. # a write the user just made, and at DEBUG it never reached
  2572. # a support bundle: #2756 reported six manual Configure Slot
  2573. # attempts on an X1C, each returning HTTP 200 with the
  2574. # read-back still showing the previous profile, and no
  2575. # record of what the printer said about any of them. Same
  2576. # promotion as extrusion_cali_set (#2718) and
  2577. # ams_filament_drying (#1447) — but only on a non-success,
  2578. # because unlike those two this command is not rare: every
  2579. # spool assignment and every K-profile re-apply sends one,
  2580. # so promoting each ack would bury the interesting line.
  2581. #
  2582. # The developer-mode probe is excluded. It sends this exact
  2583. # command to the external slot precisely to see it refused
  2584. # on P1 firmware, so its failure is a normal reading rather
  2585. # than a fault. Its response is still matched below (this
  2586. # runs before _handle_dev_mode_probe_response clears the
  2587. # seq), and user-initiated commands can't be mistaken for
  2588. # it — they publish a hardcoded sequence_id of "0".
  2589. result = print_data.get("result")
  2590. is_dev_mode_probe = (
  2591. self._dev_mode_probe_seq is not None
  2592. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2593. )
  2594. # extrusion_cali_sel too (FW-C3): every RFID re-read
  2595. # re-applies the spool's K-profile and logs "Applied PA
  2596. # profile", so its refusal must reach the bundle beside it.
  2597. # The printer's word, not a verdict: the extrusion_cali_*
  2598. # acks are known to say "fail" for writes that applied.
  2599. if not is_dev_mode_probe and isinstance(result, str) and result.lower() != "success":
  2600. logger.info(
  2601. "[%s] %s refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2602. self.serial_number,
  2603. cmd,
  2604. result,
  2605. print_data.get("reason", ""),
  2606. print_data.get("ams_id"),
  2607. print_data.get("tray_id"),
  2608. )
  2609. # AMS drying responses are rare (user-initiated only) and the
  2610. # full payload — including `result` and any `reason` code —
  2611. # is the only way to diagnose silent rejections like #1447.
  2612. # INFO level so the body lands in support bundles by default.
  2613. elif cmd == "ams_filament_drying":
  2614. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2615. # RFID re-reads are user-initiated and rare, and a refusal was
  2616. # invisible until #3206 (X1Plus answering FAIL / ERROR STATE).
  2617. # gcode_line acks are only of interest when they answer our
  2618. # M620 R fallback, so those are matched by sequence_id alone.
  2619. ack_seq = str(print_data.get("sequence_id", ""))
  2620. if (
  2621. cmd in ("ams_get_rfid", "gcode_line")
  2622. and ack_seq in self._pending_rfid_acks
  2623. and "result" in print_data
  2624. ):
  2625. logger.info(
  2626. "[%s] %s response: result=%s reason=%s seq=%s",
  2627. self.serial_number,
  2628. cmd,
  2629. print_data.get("result"),
  2630. print_data.get("reason", ""),
  2631. ack_seq,
  2632. )
  2633. self._pending_rfid_acks[ack_seq] = print_data
  2634. # Check for developer mode probe response
  2635. if (
  2636. cmd == "ams_filament_setting"
  2637. and self._dev_mode_probe_seq is not None
  2638. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2639. ):
  2640. self._handle_dev_mode_probe_response(print_data)
  2641. # Track user-initiated ams_filament_setting responses (#887
  2642. # zombie detection). Reset both the timer AND the unanswered
  2643. # counter on ANY response — the response proves the channel is
  2644. # alive, so the counter must not stay armed even when the
  2645. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2646. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2647. # caused #1164: one sluggish response (>10s) would set the
  2648. # counter to 1 and zero the timer; the late response arrived
  2649. # but was ignored by this branch (timer is 0); the counter
  2650. # stayed at 1 indefinitely; the very next slow response —
  2651. # possibly hours later, on a totally unrelated command — would
  2652. # take it to 2 and force-reconnect, surfacing as "filament
  2653. # config doesn't reach the printer ~6 changes in".
  2654. elif cmd == "ams_filament_setting":
  2655. self._last_ams_cmd_time = 0.0
  2656. self._ams_cmd_unanswered = 0
  2657. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2658. if is_kprofile_response:
  2659. self._handle_kprofile_response(print_data)
  2660. # An extrusion_cali_get response echoes the *requested* nozzle
  2661. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2662. # installed hardware. Feeding it to _update_state clobbered the real
  2663. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2664. # which then failed the #1899 dispatch guard. The response carries no
  2665. # status telemetry, so skip it; the true nozzle comes from pushall.
  2666. # (Same reasoning as get_accessories in _handle_system_response.)
  2667. # The answers to K-profile writes and selections echo the diameter
  2668. # the command named in the same way, so none of them is status.
  2669. if print_data.get("command") not in _KPROFILE_COMMAND_ANSWERS:
  2670. self._update_state(print_data)
  2671. def _handle_system_response(self, data: dict):
  2672. """Handle system responses including accessories info.
  2673. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2674. The correct nozzle data comes from push_status, so we don't update
  2675. nozzle type/diameter from get_accessories. We just log the response
  2676. for debugging purposes.
  2677. """
  2678. command = data.get("command")
  2679. if command == "get_accessories":
  2680. # Log response for debugging - but DON'T use it to update nozzle data
  2681. # because it returns stale values (e.g., 'stainless_steel' when the
  2682. # actual nozzle is 'HH01' hardened steel high-flow)
  2683. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2684. def _handle_version_info(self, data: dict):
  2685. """Handle version info response from get_version command.
  2686. Parses firmware version from the 'ota' module in the module list.
  2687. Also extracts AMS unit firmware versions from AMS modules and stores
  2688. them on the corresponding AMS unit in raw_data so the status route can
  2689. expose them to the frontend.
  2690. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2691. - ``ams/<id>`` – original AMS
  2692. - ``ams_f1/<id>`` – AMS Lite (#3348)
  2693. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2694. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2695. Message format:
  2696. {
  2697. "command": "get_version",
  2698. "module": [
  2699. {"name": "ota", "sw_ver": "01.08.05.00"},
  2700. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2701. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2702. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2703. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2704. ...
  2705. ]
  2706. }
  2707. """
  2708. modules = data.get("module", [])
  2709. if not isinstance(modules, list):
  2710. return
  2711. state_changed = False
  2712. for module in modules:
  2713. if not isinstance(module, dict):
  2714. continue
  2715. if module.get("name") == "ota":
  2716. version = module.get("sw_ver")
  2717. if version:
  2718. old_version = self.state.firmware_version
  2719. self.state.firmware_version = version
  2720. if old_version != version:
  2721. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2722. state_changed = True
  2723. break
  2724. # Extract AMS unit firmware versions from AMS modules.
  2725. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2726. # Always cache regardless of whether AMS data has arrived yet — get_version
  2727. # often arrives before the first push_status, so caching must be unconditional.
  2728. ams_raw = self.state.raw_data.get("ams")
  2729. for module in modules:
  2730. if not isinstance(module, dict):
  2731. continue
  2732. name = module.get("name", "")
  2733. if name == AMS3H_MODULE_NAME:
  2734. name = f"{name}/{self._ams3h_unit_id()}"
  2735. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2736. continue
  2737. try:
  2738. # The A2L's AMS Lite is unit 16 here but stored as 6, like
  2739. # everywhere else it is ingested.
  2740. ams_id = normalize_am_unit_id(int(name.split("/", 1)[1]))
  2741. except (ValueError, IndexError):
  2742. continue
  2743. sw_ver = module.get("sw_ver", "")
  2744. sn = module.get("sn", "")
  2745. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2746. module_type = name.split("/", 1)[0]
  2747. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2748. if sw_ver or sn or module_type:
  2749. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2750. state_changed = True
  2751. # Also directly update any AMS unit already present in raw_data
  2752. if ams_raw and isinstance(ams_raw, list):
  2753. for ams_unit in ams_raw:
  2754. if not isinstance(ams_unit, dict):
  2755. continue
  2756. try:
  2757. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2758. except (ValueError, TypeError):
  2759. unit_id = None
  2760. if unit_id == ams_id:
  2761. if sw_ver:
  2762. ams_unit["sw_ver"] = sw_ver
  2763. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2764. # Only set sn from version info if not already present in AMS data
  2765. if sn and not ams_unit.get("sn"):
  2766. ams_unit["sn"] = sn
  2767. if module_type:
  2768. ams_unit["module_type"] = module_type
  2769. break
  2770. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2771. # included in the broadcast (not just the printer firmware version).
  2772. if state_changed and self.on_state_change:
  2773. self.on_state_change(self.state)
  2774. # Warn if any AMS unit is still missing serial number or firmware version
  2775. # after processing the version info response. Warn only once per connection
  2776. # to avoid repeated noise on older firmware that doesn't report these fields.
  2777. if ams_raw and isinstance(ams_raw, list):
  2778. for ams_unit in ams_raw:
  2779. if not isinstance(ams_unit, dict):
  2780. continue
  2781. ams_id = ams_unit.get("id", "?")
  2782. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2783. key = (ams_id, "sn")
  2784. if key not in self._ams_version_warned:
  2785. self._ams_version_warned.add(key)
  2786. logger.warning(
  2787. "[%s] AMS unit %s: serial number not available in version info",
  2788. self.serial_number,
  2789. ams_id,
  2790. )
  2791. if not ams_unit.get("sw_ver"):
  2792. key = (ams_id, "sw_ver")
  2793. if key not in self._ams_version_warned:
  2794. self._ams_version_warned.add(key)
  2795. logger.warning(
  2796. "[%s] AMS unit %s: firmware version not available in version info",
  2797. self.serial_number,
  2798. ams_id,
  2799. )
  2800. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2801. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2802. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2803. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2804. sw_ver/sn fields without overwriting values already present.
  2805. """
  2806. if not ams_list or not isinstance(ams_list, list):
  2807. return
  2808. cache = self._ams_version_cache
  2809. if not cache:
  2810. return
  2811. for unit in ams_list:
  2812. if not isinstance(unit, dict):
  2813. continue
  2814. raw_id = unit.get("id")
  2815. try:
  2816. unit_id = int(raw_id) if raw_id is not None else None
  2817. except (ValueError, TypeError):
  2818. unit_id = None
  2819. if unit_id is None:
  2820. continue
  2821. cached = cache.get(unit_id)
  2822. if not cached:
  2823. continue
  2824. sw_ver = cached.get("sw_ver") or ""
  2825. sn = cached.get("sn") or ""
  2826. if sw_ver and not unit.get("sw_ver"):
  2827. unit["sw_ver"] = sw_ver
  2828. # Only set sn if not already present in AMS data
  2829. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2830. unit["sn"] = sn
  2831. module_type = cached.get("module_type") or ""
  2832. if module_type and not unit.get("module_type"):
  2833. unit["module_type"] = module_type
  2834. def _parse_xcam_data(self, xcam_data):
  2835. """Parse xcam data for camera settings and AI detection options."""
  2836. if not isinstance(xcam_data, dict):
  2837. return
  2838. current_time = time.time()
  2839. # Helper to check if we should accept incoming value for a module
  2840. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2841. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2842. """Check if we should accept an incoming xcam value.
  2843. OrcaSlicer pattern: After sending a command, ignore incoming data
  2844. for 3 seconds. After that, accept whatever the printer sends.
  2845. """
  2846. if module_name not in self._xcam_hold_start:
  2847. return True # No hold timer, accept incoming
  2848. hold_start = self._xcam_hold_start[module_name]
  2849. elapsed = current_time - hold_start
  2850. if elapsed > self._xcam_hold_time:
  2851. # Hold timer expired - accept incoming and clear hold
  2852. del self._xcam_hold_start[module_name]
  2853. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2854. return True
  2855. # Within hold period - ignore incoming data
  2856. logger.debug(
  2857. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2858. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2859. )
  2860. return False
  2861. # Log all xcam fields for debugging
  2862. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2863. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2864. # fields (spaghetti_detector, etc.) are often stale/cached.
  2865. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2866. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2867. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2868. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2869. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2870. # Sensitivity values: 0=low, 1=medium, 2=high
  2871. if "cfg" in xcam_data:
  2872. cfg = xcam_data["cfg"]
  2873. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2874. def decode_detector(start_bit):
  2875. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2876. sens_bits = (cfg >> start_bit) & 0x3
  2877. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2878. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2879. return enabled, sensitivity
  2880. # Spaghetti detector (bits 5-7)
  2881. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2882. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2883. old_value = self.state.print_options.spaghetti_detector
  2884. if cfg_spaghetti != old_value:
  2885. logger.debug(
  2886. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2887. )
  2888. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2889. # Check hold timer for sensitivity before accepting
  2890. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2891. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2892. logger.debug(
  2893. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2894. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2895. )
  2896. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2897. else:
  2898. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2899. elapsed = current_time - hold_start
  2900. if elapsed <= self._xcam_hold_time:
  2901. logger.debug(
  2902. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2903. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2904. )
  2905. else:
  2906. # Hold expired - accept from cfg
  2907. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2908. logger.debug(
  2909. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2910. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2911. )
  2912. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2913. del self._xcam_hold_start["halt_print_sensitivity"]
  2914. # Pileup detector (bits 8-10)
  2915. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2916. if should_accept_value("pileup_detector", cfg_pileup):
  2917. if cfg_pileup != self.state.print_options.pileup_detector:
  2918. logger.debug(
  2919. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2920. )
  2921. self.state.print_options.pileup_detector = cfg_pileup
  2922. # Pileup sensitivity with hold timer
  2923. if "pileup_sensitivity" not in self._xcam_hold_start:
  2924. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2925. logger.debug(
  2926. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2927. )
  2928. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2929. else:
  2930. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2931. elapsed = current_time - hold_start
  2932. if elapsed > self._xcam_hold_time:
  2933. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2934. logger.debug(
  2935. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2936. )
  2937. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2938. del self._xcam_hold_start["pileup_sensitivity"]
  2939. # Clump/nozzle clumping detector (bits 11-13)
  2940. cfg_clump, cfg_clump_sens = decode_detector(11)
  2941. if should_accept_value("clump_detector", cfg_clump):
  2942. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2943. logger.debug(
  2944. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2945. )
  2946. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2947. # Clump sensitivity with hold timer
  2948. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2949. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2950. logger.debug(
  2951. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2952. )
  2953. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2954. else:
  2955. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2956. elapsed = current_time - hold_start
  2957. if elapsed > self._xcam_hold_time:
  2958. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2959. logger.debug(
  2960. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2961. )
  2962. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2963. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2964. # Airprint detector (bits 14-16)
  2965. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2966. if should_accept_value("airprint_detector", cfg_airprint):
  2967. if cfg_airprint != self.state.print_options.airprint_detector:
  2968. logger.debug(
  2969. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2970. )
  2971. self.state.print_options.airprint_detector = cfg_airprint
  2972. # Airprint sensitivity with hold timer
  2973. if "airprint_sensitivity" not in self._xcam_hold_start:
  2974. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2975. logger.debug(
  2976. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2977. )
  2978. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2979. else:
  2980. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2981. elapsed = current_time - hold_start
  2982. if elapsed > self._xcam_hold_time:
  2983. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2984. logger.debug(
  2985. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2986. )
  2987. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2988. del self._xcam_hold_start["airprint_sensitivity"]
  2989. # Camera settings
  2990. if "ipcam_record" in xcam_data:
  2991. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2992. if "timelapse" in xcam_data:
  2993. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2994. # Track if timelapse was ever active during this print
  2995. if self.state.timelapse and self._was_running:
  2996. self._timelapse_during_print = True
  2997. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2998. if "print_halt" in xcam_data:
  2999. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  3000. # Skip halt_print_sensitivity field - it's always stale ("medium")
  3001. # We read the actual sensitivity from cfg bits 5-6 above
  3002. if "first_layer_inspector" in xcam_data:
  3003. new_value = bool(xcam_data.get("first_layer_inspector"))
  3004. if should_accept_value("first_layer_inspector", new_value):
  3005. self.state.print_options.first_layer_inspector = new_value
  3006. if "printing_monitor" in xcam_data:
  3007. new_value = bool(xcam_data.get("printing_monitor"))
  3008. if should_accept_value("printing_monitor", new_value):
  3009. self.state.print_options.printing_monitor = new_value
  3010. if "buildplate_marker_detector" in xcam_data:
  3011. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  3012. if should_accept_value("buildplate_marker_detector", new_value):
  3013. self.state.print_options.buildplate_marker_detector = new_value
  3014. if "allow_skip_parts" in xcam_data:
  3015. new_value = bool(xcam_data.get("allow_skip_parts"))
  3016. if should_accept_value("allow_skip_parts", new_value):
  3017. self.state.print_options.allow_skip_parts = new_value
  3018. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  3019. # individual boolean fields (which are not sent by the printer)
  3020. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  3021. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  3022. if "auto_recovery_step_loss" in xcam_data:
  3023. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  3024. if "filament_tangle_detect" in xcam_data:
  3025. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  3026. @staticmethod
  3027. def _resolve_local_slot_from_mapping(
  3028. local_slot: int, mapping_raw: list | None, units: list[int] | None = None
  3029. ) -> int | None:
  3030. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  3031. The MQTT mapping field is an array of snow-encoded values:
  3032. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  3033. Finds entries where the local slot matches, then computes the global tray ID.
  3034. When several match and ``units`` is given (the AMS units on the active
  3035. extruder of a dual-nozzle printer), only those units' trays count.
  3036. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  3037. """
  3038. if not isinstance(mapping_raw, list) or not mapping_raw:
  3039. return None
  3040. candidates = mapped_trays_with_slot(mapping_raw, local_slot) # global tray ID -> AMS unit
  3041. if len(candidates) > 1 and units:
  3042. candidates = {tray: unit for tray, unit in candidates.items() if unit in units}
  3043. if len(candidates) == 1:
  3044. return next(iter(candidates))
  3045. return None
  3046. def _maybe_trigger_external_spool_change(self):
  3047. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  3048. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  3049. an external-spool-only filament swap would otherwise never re-run the
  3050. inventory reconciliation that unlinks a stale ams_id=255 assignment
  3051. (#2575). The reconciliation reads vt_tray from live status itself, so we
  3052. just need to re-fire the callback with the current merged AMS data.
  3053. """
  3054. import hashlib
  3055. vt_tray = self.state.raw_data.get("vt_tray")
  3056. if not isinstance(vt_tray, list):
  3057. return
  3058. # Identity fields only — deliberately exclude `remain` so a print's
  3059. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  3060. fp_parts = [
  3061. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  3062. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  3063. for vt in vt_tray
  3064. if isinstance(vt, dict)
  3065. ]
  3066. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  3067. if vt_hash == self._previous_vt_tray_hash:
  3068. return
  3069. self._previous_vt_tray_hash = vt_hash
  3070. if self.on_ams_change:
  3071. logger.debug(
  3072. "[%s] External spool (vt_tray) changed, triggering sync callback",
  3073. self.serial_number,
  3074. )
  3075. self.on_ams_change(self.state.raw_data.get("ams") or [])
  3076. def _normalize_a2l_am_units(self, ams_list) -> None:
  3077. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  3078. id 16 -> 6 in place, as early as possible, so every downstream reader —
  3079. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  3080. the DB constraint — sees the normalised id and needs no special-casing.
  3081. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  3082. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  3083. both the dict-wrapped and bare-list AMS shapes.
  3084. """
  3085. if not isinstance(ams_list, list):
  3086. return
  3087. for unit in ams_list:
  3088. if not isinstance(unit, dict):
  3089. continue
  3090. try:
  3091. uid = int(unit.get("id"))
  3092. except (TypeError, ValueError):
  3093. continue
  3094. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  3095. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  3096. if not self._has_a2l_am_unit:
  3097. logger.info(
  3098. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  3099. self.serial_number,
  3100. A2L_LITE_NORMALIZED_AMS_ID,
  3101. )
  3102. self._has_a2l_am_unit = True
  3103. @property
  3104. def tray_layout(self) -> TrayLayout:
  3105. """How this printer numbers its trays (utils.tray_ids); rebuilt only when its units change."""
  3106. raw = self.state.raw_data
  3107. units, vt_trays = raw.get("ams"), raw.get("vt_tray")
  3108. key = (
  3109. tuple((u.get("id"), u.get("info")) for u in units if isinstance(u, dict))
  3110. if isinstance(units, list)
  3111. else (),
  3112. tuple(vt.get("id") for vt in vt_trays if isinstance(vt, dict)) if isinstance(vt_trays, list) else (),
  3113. self.model,
  3114. )
  3115. if key != self._tray_layout_key:
  3116. from backend.app.utils.printer_models import has_ams3h
  3117. self._tray_layout = TrayLayout.from_state(self.state, has_ams3h(self.model))
  3118. self._tray_layout_key = key
  3119. return self._tray_layout
  3120. def _layout_with(self, ams_list: object) -> TrayLayout:
  3121. """``tray_layout`` including the units of a push not merged into the state yet."""
  3122. if not isinstance(ams_list, list) or not any(isinstance(u, dict) for u in ams_list):
  3123. return self.tray_layout
  3124. units = [u for u in ams_list if isinstance(u, dict)]
  3125. known = self.state.raw_data.get("ams")
  3126. if isinstance(known, list):
  3127. units.extend(u for u in known if isinstance(u, dict))
  3128. vt_trays = self.state.raw_data.get("vt_tray")
  3129. return TrayLayout.from_units(units, vt_trays if isinstance(vt_trays, list) else None)
  3130. def _note_rack_ams(self, layout: TrayLayout) -> None:
  3131. """Log a rack AMS the first time this connection sees it."""
  3132. for ams_id, kind in layout.rack_units:
  3133. if ams_id in self._rack_ams_logged:
  3134. continue
  3135. self._rack_ams_logged.add(ams_id)
  3136. logger.info(
  3137. "[%s] Rack AMS detected: unit %s (AMS type %s), global tray ids %s-%s",
  3138. self.serial_number,
  3139. ams_id,
  3140. int(kind),
  3141. global_tray_id(ams_id, 0, kind),
  3142. global_tray_id(ams_id, RACK_SLOT_COUNT - 1, kind),
  3143. )
  3144. def _ams3h_unit_id(self) -> int:
  3145. """The unit id of this printer's AMS 3H (32 on the H3C)."""
  3146. return next((uid for uid, kind in self.tray_layout.rack_units if kind == AmsType.ZMULTI_A), AMS3H_UNIT_ID)
  3147. def _rack_ams_type(self, ams_id: int) -> AmsType | None:
  3148. """The type of unit ``ams_id`` when it is one of this printer's rack AMS units, else None."""
  3149. for uid, kind in self.tray_layout.rack_units:
  3150. if uid == ams_id:
  3151. return kind
  3152. return None
  3153. def _parse_fila_switch(self, data: dict) -> None:
  3154. """Read the Filament Track Switch block out of a print payload — #1162.
  3155. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  3156. separate from the rest of the state update because ``_handle_ams_data``
  3157. needs the answer before it parses the AMS info bits, and that runs first.
  3158. """
  3159. if not isinstance(data.get("device"), dict):
  3160. return
  3161. fs_data = data["device"].get("fila_switch")
  3162. if not isinstance(fs_data, dict):
  3163. return
  3164. in_raw = fs_data.get("in")
  3165. out_raw = fs_data.get("out")
  3166. self.state.fila_switch = FilaSwitchState(
  3167. installed=True,
  3168. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  3169. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  3170. stat=int(fs_data.get("stat", 0) or 0),
  3171. info=int(fs_data.get("info", 0) or 0),
  3172. )
  3173. def _parse_extruder_position(self, data: dict) -> bool:
  3174. """Read which nozzle is active and which tray each nozzle holds.
  3175. From ``device.extruder``: ``state`` bit 8 is the active nozzle, each
  3176. ``info`` entry's ``snow`` names its AMS and slot. Run on a frame before
  3177. its AMS block, because an H2D's tray_now is a bare slot that only the
  3178. extruder data of the same frame places. Returns True when the frame
  3179. carried the active nozzle's snow. A malformed value is skipped, never
  3180. raised: this runs ahead of everything else the frame carries.
  3181. """
  3182. device = data.get("device")
  3183. extruder = device.get("extruder") if isinstance(device, dict) else None
  3184. if not isinstance(extruder, dict):
  3185. return False
  3186. try:
  3187. state_val = int(extruder["state"]) if "state" in extruder else None
  3188. except (TypeError, ValueError):
  3189. state_val = None
  3190. if state_val is not None:
  3191. # Extract bit 8 for extruder position
  3192. new_extruder = (state_val >> 8) & 0x1
  3193. if new_extruder != self.state.active_extruder:
  3194. logger.debug(
  3195. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  3196. )
  3197. self.state.active_extruder = new_extruder
  3198. extruder_info = extruder.get("info")
  3199. if not isinstance(extruder_info, list) or len(extruder_info) < 2:
  3200. return False
  3201. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  3202. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  3203. snow_read: set[int] = set()
  3204. for ext_info in extruder_info:
  3205. if not isinstance(ext_info, dict) or "id" not in ext_info or "snow" not in ext_info:
  3206. continue
  3207. try:
  3208. ext_id = int(ext_info["id"])
  3209. snow = int(ext_info["snow"])
  3210. except (TypeError, ValueError):
  3211. continue
  3212. if ext_id <= 1:
  3213. snow_read.add(ext_id)
  3214. # Normalize H2D snow value to global tray ID (255 = unloaded)
  3215. global_tray = 255 if snow == 0xFFFF else decode_wire_slot(snow)
  3216. if global_tray is None:
  3217. continue
  3218. if self.state.h2d_extruder_snow.get(ext_id) != global_tray:
  3219. logger.debug(
  3220. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: raw={snow} -> global tray {global_tray}"
  3221. )
  3222. self.state.h2d_extruder_snow[ext_id] = global_tray
  3223. return self.state.active_extruder in snow_read
  3224. def _parse_extruder_slots(self, data: dict) -> None:
  3225. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  3226. Absent on printers that do not report the block, in which case the
  3227. previous answer is kept rather than cleared: a partial payload carrying
  3228. only temperatures must not look like "both hotends are now empty".
  3229. """
  3230. device = data.get("device")
  3231. if not isinstance(device, dict):
  3232. return
  3233. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  3234. if not isinstance(info, list) or not info:
  3235. return
  3236. slots: dict[int, ExtruderSlot] = {}
  3237. for entry in info:
  3238. if not isinstance(entry, dict) or "id" not in entry:
  3239. continue
  3240. try:
  3241. ext_id = int(entry["id"])
  3242. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  3243. flags = int(entry.get("info", 0) or 0)
  3244. except (TypeError, ValueError):
  3245. continue
  3246. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  3247. ams_id = slot_id = None
  3248. else:
  3249. ams_id = (snow >> 8) & 0xFF
  3250. slot_id = snow & 0xFF
  3251. slots[ext_id] = ExtruderSlot(
  3252. ams_id=ams_id,
  3253. slot_id=slot_id,
  3254. has_filament=bool(flags & 0b10),
  3255. )
  3256. if slots:
  3257. self.state.extruder_slots = slots
  3258. def _handle_ams_data(self, ams_data):
  3259. """Handle AMS data changes for Spoolman integration.
  3260. This is called when we receive top-level AMS data in MQTT messages.
  3261. It detects changes and triggers the callback for Spoolman sync.
  3262. """
  3263. import hashlib
  3264. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  3265. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  3266. ams_list = None
  3267. if isinstance(ams_data, dict):
  3268. if "ams" in ams_data:
  3269. ams_list = ams_data["ams"]
  3270. self._normalize_a2l_am_units(ams_list)
  3271. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3272. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  3273. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  3274. if non_list_fields:
  3275. self._debug_on_change(
  3276. "ams_dict_fields",
  3277. non_list_fields,
  3278. "[%s] AMS dict fields: %s",
  3279. self.serial_number,
  3280. non_list_fields,
  3281. )
  3282. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  3283. # when checking if we're in filament change mode for tray_now disambiguation
  3284. if "ams_status" in ams_data:
  3285. raw_ams_status = ams_data["ams_status"]
  3286. if isinstance(raw_ams_status, str):
  3287. try:
  3288. self.state.ams_status = int(raw_ams_status)
  3289. except ValueError:
  3290. self.state.ams_status = 0
  3291. else:
  3292. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  3293. # Compute main and sub status
  3294. self.state.ams_status_sub = self.state.ams_status & 0xFF
  3295. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  3296. self._debug_on_change(
  3297. "ams_status:ams",
  3298. self.state.ams_status,
  3299. "[%s] ams_status: %s (main=%s, sub=%s)",
  3300. self.serial_number,
  3301. self.state.ams_status,
  3302. self.state.ams_status_main,
  3303. self.state.ams_status_sub,
  3304. )
  3305. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  3306. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  3307. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  3308. # next compatible slot (#2587). Stored raw here; globalised at the API
  3309. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  3310. # these are local slot numbers (0-3), not global IDs.
  3311. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  3312. if _tk in ams_data:
  3313. _raw = ams_data[_tk]
  3314. if isinstance(_raw, str):
  3315. try:
  3316. _val = int(_raw)
  3317. except ValueError:
  3318. _val = 255
  3319. else:
  3320. _val = _raw if _raw is not None else 255
  3321. prev = getattr(self.state, _attr)
  3322. setattr(self.state, _attr, _val)
  3323. # Log changes only while paused — the moment the operator cares —
  3324. # so a healthy print's normal tar churn doesn't spam the log.
  3325. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  3326. logger.info(
  3327. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  3328. self.serial_number,
  3329. _tk,
  3330. _val,
  3331. )
  3332. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  3333. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  3334. if "tray_now" in ams_data:
  3335. raw_tray_now = ams_data["tray_now"]
  3336. # Convert string to int if needed
  3337. if isinstance(raw_tray_now, str):
  3338. try:
  3339. parsed_tray_now = int(raw_tray_now)
  3340. except ValueError:
  3341. parsed_tray_now = 255
  3342. else:
  3343. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  3344. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  3345. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  3346. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  3347. # — disambiguated below using MQTT mapping field
  3348. ams_map = self.state.ams_extruder_map
  3349. # A rack AMS reports tray_now as its raw slot 0-8 (global 28 +
  3350. # slot). Its units may arrive in this same push, before the merge.
  3351. rack_layout = self._layout_with(ams_list)
  3352. self._note_rack_ams(rack_layout)
  3353. if rack_layout.rack_units and not self._is_dual_nozzle:
  3354. rack_tray = rack_layout.raw_slot_to_global(parsed_tray_now)
  3355. # 255 (nothing on the toolhead, also mid-swap) and any
  3356. # external input id are kept as reported.
  3357. self.state.tray_now = rack_tray if rack_tray is not None else parsed_tray_now
  3358. elif self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3359. # First, check if we have a pending target that matches this slot
  3360. pending_target = self.state.pending_tray_target
  3361. pending_at = self.state.pending_tray_target_at
  3362. if (
  3363. pending_target is not None
  3364. and pending_at is not None
  3365. and time.monotonic() - pending_at > PENDING_TRAY_TARGET_TTL
  3366. ):
  3367. # A load the printer refused or dropped: nothing clears
  3368. # it (tray_now stays 255), and a print loading the same
  3369. # slot number on another AMS long after was shown as
  3370. # this target (FW-C7). Fall through to the snow field.
  3371. self.state.pending_tray_target = None
  3372. self.state.pending_tray_target_at = None
  3373. pending_target = None
  3374. if pending_target is not None:
  3375. # Same slot rule as the snow branch below: an AMS-HT
  3376. # (128-135) has its one tray in slot 0.
  3377. pending_slot = 0 if is_ams_ht_id(pending_target) else pending_target % 4
  3378. if pending_slot == parsed_tray_now:
  3379. # Slot matches our pending target - use the full global ID
  3380. logger.debug(
  3381. f"[{self.serial_number}] H2D tray_now disambiguation: "
  3382. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  3383. )
  3384. self.state.tray_now = pending_target
  3385. # Clear pending target now that load is confirmed
  3386. self.state.pending_tray_target = None
  3387. else:
  3388. # Slot doesn't match our pending target - something changed, use slot as-is
  3389. logger.warning(
  3390. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  3391. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  3392. )
  3393. self.state.tray_now = parsed_tray_now
  3394. # Clear pending target since it's stale
  3395. self.state.pending_tray_target = None
  3396. else:
  3397. # No pending target - use h2d_extruder_snow for accurate disambiguation
  3398. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  3399. active_ext = self.state.active_extruder # 0=right, 1=left
  3400. # Best source: use snow value from device.extruder.info if available
  3401. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  3402. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  3403. snow_slot = (
  3404. None
  3405. if snow_tray is None
  3406. else snow_tray % 4
  3407. if snow_tray < 128
  3408. else (0 if is_ams_ht_id(snow_tray) else -1)
  3409. )
  3410. # A snow from an earlier frame may predate a swap: it
  3411. # names the tray only while it agrees with the slot.
  3412. snow_usable = (
  3413. snow_tray is not None
  3414. and snow_tray != 255
  3415. and (snow_slot == parsed_tray_now or self._snow_in_frame)
  3416. )
  3417. if snow_usable and snow_tray is not None:
  3418. # snow_tray is already normalized to global ID
  3419. if snow_slot == parsed_tray_now:
  3420. if self.state.tray_now != snow_tray:
  3421. logger.debug(
  3422. f"[{self.serial_number}] H2D tray_now from snow: "
  3423. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  3424. )
  3425. self.state.tray_now = snow_tray
  3426. else:
  3427. # Slot mismatch in one frame: the extruder's own
  3428. # report is the complete answer, trust snow
  3429. logger.debug(
  3430. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  3431. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  3432. )
  3433. self.state.tray_now = snow_tray
  3434. else:
  3435. # Fallback: snow not available, use ams_extruder_map (less reliable)
  3436. # Find ALL AMS units on the active extruder
  3437. ams_on_extruder = []
  3438. for ams_id_str, ext_id in ams_map.items():
  3439. if ext_id == active_ext:
  3440. try:
  3441. ams_on_extruder.append(int(ams_id_str))
  3442. except ValueError:
  3443. pass # Skip AMS IDs that aren't valid integers
  3444. # Several AMS (or none the map knows of) leave the
  3445. # slot ambiguous. The printer's own mapping names the
  3446. # trays the running print uses: one of them at this
  3447. # slot is the one feeding (#3242). Only while a print
  3448. # runs: an idle H2 keeps reporting the previous
  3449. # print's mapping.
  3450. mapped_tray = None
  3451. if len(ams_on_extruder) != 1 and self._was_running and not self._completion_triggered:
  3452. mapped_tray = self._resolve_local_slot_from_mapping(
  3453. parsed_tray_now, self.state.raw_data.get("mapping"), ams_on_extruder
  3454. )
  3455. if mapped_tray is not None:
  3456. if self.state.tray_now != mapped_tray:
  3457. logger.debug(
  3458. f"[{self.serial_number}] H2D tray_now: AMS {ams_on_extruder} on extruder "
  3459. f"{active_ext}, slot {parsed_tray_now} -> global ID {mapped_tray} (from mapping)"
  3460. )
  3461. self.state.tray_now = mapped_tray
  3462. elif len(ams_on_extruder) == 1:
  3463. # Single AMS on this extruder - unambiguous
  3464. active_ams_id = ams_on_extruder[0]
  3465. # AMS-HT: single slot per unit, global ID = unit ID
  3466. fallback_tray = global_tray_id(active_ams_id, parsed_tray_now)
  3467. logger.debug(
  3468. f"[{self.serial_number}] H2D tray_now fallback: "
  3469. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {fallback_tray}"
  3470. )
  3471. self.state.tray_now = fallback_tray
  3472. elif len(ams_on_extruder) > 1:
  3473. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  3474. current_tray = self.state.tray_now
  3475. # Determine which AMS unit and slot the current tray belongs to
  3476. if 0 <= current_tray <= 15 or is_ams_ht_id(current_tray):
  3477. # AMS-HT: ID = tray ID, one slot
  3478. current_ams, current_slot = rack_layout.slot_key(current_tray)
  3479. else:
  3480. current_ams = -1
  3481. current_slot = -1
  3482. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  3483. # Current is valid and matches slot - keep it
  3484. logger.debug(
  3485. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3486. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  3487. )
  3488. else:
  3489. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  3490. if parsed_tray_now > 0:
  3491. candidates = [a for a in ams_on_extruder if a <= 3]
  3492. else:
  3493. candidates = ams_on_extruder
  3494. if len(candidates) == 1:
  3495. cand = candidates[0]
  3496. resolved = global_tray_id(cand, parsed_tray_now)
  3497. logger.debug(
  3498. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3499. f"narrowed to AMS {cand} -> global ID {resolved}"
  3500. )
  3501. self.state.tray_now = resolved
  3502. else:
  3503. # Genuinely ambiguous. This is the second between a
  3504. # filament change reaching the AMS report and the
  3505. # extruder's snow, which then names the tray. Using
  3506. # the bare slot would point at AMS 0 and put that
  3507. # tray in the usage change log (#3242), so keep the
  3508. # current tray until snow arrives.
  3509. logger.debug(
  3510. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on "
  3511. f"extruder {active_ext}, slot {parsed_tray_now} is ambiguous without snow, "
  3512. f"keeping {current_tray}"
  3513. )
  3514. else:
  3515. # No AMS on this extruder that the map knows of: the
  3516. # slot can't be placed, keep the current tray (#3242)
  3517. logger.debug(
  3518. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  3519. f"slot {parsed_tray_now} can't be placed without snow, keeping {self.state.tray_now}"
  3520. )
  3521. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3522. # Single-nozzle printer with tray_now in 0-3 range.
  3523. # #1822: H2S firmware reports tray_now as the AMS's idle
  3524. # slot (typically 0) when the active feed is actually the
  3525. # external spool. X1C / P1S / A1 correctly report 254 in
  3526. # that case; H2S does not. When the slicer-captured
  3527. # ams_mapping is all-external (every entry is 254, or -1
  3528. # when the command carried no ams_mapping2 to resolve it
  3529. # from, #3166), the print can only be feeding from the
  3530. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  3531. # AMS-only mappings are NOT overridden — there's no
  3532. # evidence the firmware misreports in those cases. Prints
  3533. # started without a captured mapping (printer-screen start,
  3534. # or before Bambuddy connected) fall through unchanged.
  3535. captured = self._captured_ams_mapping
  3536. if captured and all(s in (-1, 254, 255) for s in captured):
  3537. if self.state.tray_now != 254:
  3538. logger.debug(
  3539. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  3540. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  3541. )
  3542. self.state.tray_now = 254
  3543. else:
  3544. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  3545. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  3546. # (snow-encoded) to resolve the correct AMS unit.
  3547. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  3548. try:
  3549. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  3550. except (ValueError, TypeError):
  3551. ams_exist = 0
  3552. num_ams = bin(ams_exist).count("1")
  3553. if self._has_a2l_am_unit and num_ams <= 1:
  3554. # A2L AMS-Lite (normalised unit 6): the firmware reports
  3555. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  3556. # otherwise usage tracking keys the wrong spool (it would
  3557. # deduct from AMS 0's slot). Confirmed by capture:
  3558. # tray_now="2" while printing physical slot 3.
  3559. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  3560. elif num_ams > 1:
  3561. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  3562. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  3563. if self._has_a2l_am_unit:
  3564. # A2L Lite + a regular AMS attached together is out of
  3565. # scope: the flat mapping ids are unknown for that combo
  3566. # and could collide with AMS 0. Fall through to the
  3567. # mapping-based resolve, but warn — a capture is needed.
  3568. logger.warning(
  3569. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3570. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3571. self.serial_number,
  3572. )
  3573. mapping_raw = self.state.raw_data.get("mapping")
  3574. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3575. if resolved is not None:
  3576. if resolved != parsed_tray_now:
  3577. logger.debug(
  3578. f"[{self.serial_number}] Multi-AMS tray_now: "
  3579. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3580. )
  3581. self.state.tray_now = resolved
  3582. else:
  3583. # No mapping available (not printing, or ambiguous) — use as-is.
  3584. # This matches the old behavior and is correct for AMS 0.
  3585. self.state.tray_now = parsed_tray_now
  3586. else:
  3587. # Single AMS — local slot 0-3 equals global ID
  3588. self.state.tray_now = parsed_tray_now
  3589. else:
  3590. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3591. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3592. # During filament change, the printer sends 255 first (unload), then the slot.
  3593. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3594. # Trust the printer's reported value.
  3595. self.state.tray_now = parsed_tray_now
  3596. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3597. tn = self.state.tray_now
  3598. if rack_layout.is_loaded_tray(tn):
  3599. # Log tray change for mid-print usage splitting. Gate on the
  3600. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3601. # new print, `_completion_triggered` set when on_print_complete
  3602. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3603. # firmware briefly transitions out of RUNNING during AMS
  3604. # auto-fallback (#957), so a literal-string gate misses the
  3605. # switch and the usage tracker double-credits at completion.
  3606. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3607. self.state.tray_change_log.append((tn, self.state.layer_num))
  3608. logger.info(
  3609. "[%s] Tray change during print: tray=%d at layer=%d",
  3610. self.serial_number,
  3611. tn,
  3612. self.state.layer_num,
  3613. )
  3614. if self.on_tray_change:
  3615. self.on_tray_change(tn, self.state.layer_num)
  3616. self.state.last_loaded_tray = self.state.tray_now
  3617. self._debug_on_change(
  3618. "tray_now",
  3619. self.state.tray_now,
  3620. "[%s] tray_now updated: %s",
  3621. self.serial_number,
  3622. self.state.tray_now,
  3623. )
  3624. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3625. # state when checking filament change mode for H2D disambiguation
  3626. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3627. # We've already processed the status fields above, so just return if no ams list
  3628. if ams_list is None:
  3629. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3630. return
  3631. elif isinstance(ams_data, list):
  3632. ams_list = ams_data
  3633. self._normalize_a2l_am_units(ams_list)
  3634. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3635. else:
  3636. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3637. return
  3638. # Merge AMS data instead of replacing, to handle partial updates
  3639. # During prints, the printer may only send updates for active AMS units
  3640. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3641. existing_ams = self.state.raw_data.get("ams")
  3642. # #3499: anything but the merged unit list (once, the frame's own AMS
  3643. # object) would fail every later frame on its string keys.
  3644. if not isinstance(existing_ams, list):
  3645. existing_ams = []
  3646. existing_by_id = {
  3647. ams.get("id"): ams for ams in existing_ams if isinstance(ams, dict) and ams.get("id") is not None
  3648. }
  3649. # Update existing units with new data, add new units
  3650. for ams_unit in ams_list:
  3651. ams_id = ams_unit.get("id")
  3652. if ams_id is not None:
  3653. existing_unit = existing_by_id.get(ams_id)
  3654. if existing_unit and "tray" in ams_unit:
  3655. # Deep merge trays to preserve fields from previous updates
  3656. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3657. merged_trays = []
  3658. for new_tray in ams_unit.get("tray", []):
  3659. tray_id = new_tray.get("id")
  3660. if tray_id is not None and tray_id in existing_trays:
  3661. # Merge: start with existing, update with new non-empty values
  3662. merged_tray = existing_trays[tray_id].copy()
  3663. # Detect slot-clearing updates (spool removal):
  3664. # When tray_type is explicitly empty, clear everything
  3665. # including RFID data (tag_uid/tray_uuid).
  3666. slot_clearing = new_tray.get("tray_type") == ""
  3667. # Some printers (e.g. H2D) only send {id, state} in
  3668. # incremental updates when a tray is not fully loaded.
  3669. # state=11 means loaded; other values (9=empty,
  3670. # 10=spool present but filament not in feeder) indicate
  3671. # the slot should be cleared. Without this, old
  3672. # tray_type/tray_color persist indefinitely (#784).
  3673. #
  3674. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3675. # tray high-temp dry box, id >= 128) reports its loaded
  3676. # tray as state=9, not 11 — it doesn't feed filament into
  3677. # a shared buffer the way a 4-slot AMS does. Applying the
  3678. # `state != 11 → empty` rule to an HT unit wiped a present
  3679. # spool on every power-on, when the printer sends a partial
  3680. # {id, state=9} for the HT tray (#2594). Skip the state
  3681. # heuristic for HT units — a genuine HT spool removal still
  3682. # clears via the explicit tray_type=="" case above and the
  3683. # tray_exist_bits cleanup below.
  3684. #
  3685. # A rack AMS (the H3C's AMS 3H) reports a loaded slot
  3686. # as state=27, so it is skipped the same way.
  3687. try:
  3688. _is_ht_unit = int(ams_id) >= 128 or is_rack_ams(
  3689. unit_ams_type(int(ams_id), ams_unit.get("info") or existing_unit.get("info"))
  3690. )
  3691. except (TypeError, ValueError):
  3692. _is_ht_unit = False
  3693. tray_state = new_tray.get("state")
  3694. if (
  3695. tray_state is not None
  3696. and tray_state != 11
  3697. and not _is_ht_unit
  3698. and "tray_type" not in new_tray
  3699. and merged_tray.get("tray_type")
  3700. ):
  3701. logger.info(
  3702. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3703. self.serial_number,
  3704. ams_id,
  3705. tray_id,
  3706. tray_state,
  3707. )
  3708. slot_clearing = True
  3709. # The incremental update only has {id, state} — inject
  3710. # empty values for all content fields so the merge loop
  3711. # below clears the stale data from merged_tray.
  3712. new_tray.update(
  3713. {
  3714. "tray_type": "",
  3715. "tray_sub_brands": "",
  3716. "tray_color": "",
  3717. "tray_id_name": "",
  3718. "tray_info_idx": "",
  3719. "tag_uid": "0000000000000000",
  3720. "tray_uuid": "00000000000000000000000000000000",
  3721. "remain": 0,
  3722. "k": None,
  3723. "cali_idx": None,
  3724. }
  3725. )
  3726. for key, value in new_tray.items():
  3727. # Fields that should always be updated (even with empty/zero values):
  3728. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3729. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3730. # tray_id_name: slot content indicators that must be cleared
  3731. # when a spool is removed (fixes #147 - old AMS empty slot)
  3732. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3733. # They are only cleared during spool removal (slot_clearing=True).
  3734. # Periodic AMS updates often include empty RFID fields which
  3735. # would overwrite valid data from the initial pushall.
  3736. always_update_fields = (
  3737. "remain",
  3738. "k",
  3739. "id",
  3740. "cali_idx",
  3741. "tray_type",
  3742. "tray_sub_brands",
  3743. "tray_info_idx",
  3744. "tray_color",
  3745. "tray_id_name",
  3746. )
  3747. if (
  3748. key in always_update_fields
  3749. or slot_clearing
  3750. or value
  3751. not in (
  3752. None,
  3753. "",
  3754. "0000000000000000",
  3755. "00000000000000000000000000000000",
  3756. )
  3757. ):
  3758. merged_tray[key] = value
  3759. merged_trays.append(merged_tray)
  3760. else:
  3761. merged_trays.append(new_tray)
  3762. # Update ams_unit with merged trays. Spread existing_unit
  3763. # FIRST so top-level fields the partial update omits —
  3764. # dry_time, info (which drives dry_status / dry_sub_status),
  3765. # humidity, temp — are preserved instead of dropped. The
  3766. # printer sends tray-bearing partials that carry no drying
  3767. # fields; without this, dry_time reads as absent → 0 and the
  3768. # falling-edge detector below fires a false "drying complete"
  3769. # (#1462). Mirrors the no-tray branch's merge semantics.
  3770. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3771. elif existing_unit:
  3772. # Partial update without tray data: merge new fields into existing
  3773. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3774. ams_unit = {**existing_unit, **ams_unit}
  3775. existing_by_id[ams_id] = ams_unit
  3776. # The merge keeps a unit the push doesn't list, so an unplugged AMS used
  3777. # to stay until Bambuddy restarted (#3356). Drop one only on the
  3778. # printer's own word that it is gone.
  3779. if isinstance(ams_data, dict):
  3780. listed = {ams_unit.get("id") for ams_unit in ams_list}
  3781. for ams_id in [i for i in existing_by_id if i not in listed]:
  3782. if unit_reported_absent(ams_id, ams_list, ams_data.get("ams_exist_bits")):
  3783. logger.info("[%s] AMS %s no longer attached, removing it", self.serial_number, ams_id)
  3784. del existing_by_id[ams_id]
  3785. # Convert back to list, sorted by ID for consistent ordering
  3786. merged_ams = sorted(existing_by_id.values(), key=_ams_unit_order)
  3787. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3788. # Shared with the VP bridge cache so the slicer-facing view stays in
  3789. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3790. # for the full rationale and the printer-shutdown guard.
  3791. if isinstance(ams_data, dict):
  3792. apply_tray_exist_bits(
  3793. merged_ams,
  3794. ams_data.get("tray_exist_bits"),
  3795. power_on_flag=ams_data.get("power_on_flag", True),
  3796. log_label=self.serial_number,
  3797. annotate_exists=True,
  3798. )
  3799. self.state.raw_data["ams"] = merged_ams
  3800. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3801. self._apply_ams_version_cache(merged_ams)
  3802. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3803. self.state.last_ams_update = time.time()
  3804. self._debug_on_change(
  3805. "merged_ams",
  3806. (len(ams_list), len(merged_ams)),
  3807. "[%s] Merged AMS data: %s new units, %s total",
  3808. self.serial_number,
  3809. len(ams_list),
  3810. len(merged_ams),
  3811. )
  3812. # Extract ams_extruder_map from each AMS unit's info field
  3813. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3814. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3815. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3816. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3817. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3818. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3819. #
  3820. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3821. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3822. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3823. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3824. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3825. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3826. # the switch being installed.
  3827. #
  3828. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3829. # the full map. Merge into existing map to preserve entries from prior updates.
  3830. fts_installed = self.state.fila_switch.installed
  3831. inlet_moves: list[tuple[int, str]] = []
  3832. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3833. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3834. # A rack AMS feeds the one extruder of a rack printer; listed here it
  3835. # would make the slot/dispatch code assume two nozzles.
  3836. rack_ams_ids = {uid for uid, _ in TrayLayout.from_units(merged_ams).rack_units}
  3837. for ams_unit in merged_ams:
  3838. ams_id = ams_unit.get("id")
  3839. info = ams_unit.get("info")
  3840. if _mqtt_int(ams_id) in rack_ams_ids:
  3841. continue
  3842. if ams_id is not None and info is not None:
  3843. try:
  3844. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3845. info_val = int(str(info), 16)
  3846. # Extract 4 bits starting at bit 8 for extruder assignment
  3847. extruder_id = (info_val >> 8) & 0xF
  3848. if extruder_id == 0xE:
  3849. if fts_installed:
  3850. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3851. if inlet is not None:
  3852. previous = ams_switch_inlet.get(str(ams_id))
  3853. ams_switch_inlet[str(ams_id)] = inlet
  3854. self._debug_on_change(
  3855. f"ams_inlet:{ams_id}",
  3856. inlet,
  3857. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3858. self.serial_number,
  3859. ams_id,
  3860. info,
  3861. inlet,
  3862. )
  3863. if previous is not None and previous != inlet:
  3864. # Only a genuine move, never the first sighting:
  3865. # re-applying K-profiles on every reconnect would
  3866. # fight a binding the operator set deliberately.
  3867. logger.info(
  3868. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3869. self.serial_number,
  3870. ams_id,
  3871. inlet,
  3872. previous,
  3873. )
  3874. inlet_moves.append((int(ams_id), inlet))
  3875. continue
  3876. ams_extruder_map[str(ams_id)] = extruder_id
  3877. self._debug_on_change(
  3878. f"ams_info:{ams_id}",
  3879. (info, extruder_id),
  3880. "[%s] AMS %s info=0x%s -> extruder %s",
  3881. self.serial_number,
  3882. ams_id,
  3883. info,
  3884. extruder_id,
  3885. )
  3886. except (ValueError, TypeError):
  3887. pass # Skip AMS units with unparseable info bitmask values
  3888. if ams_extruder_map:
  3889. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3890. self.state.ams_extruder_map = ams_extruder_map
  3891. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3892. if ams_switch_inlet:
  3893. self.state.ams_switch_inlet = ams_switch_inlet
  3894. for moved_ams_id, moved_inlet in inlet_moves:
  3895. if self.on_fts_inlet_change:
  3896. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3897. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3898. # BambuStudio DevFilaSystem.cpp parses info bits:
  3899. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3900. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3901. for ams_unit in merged_ams:
  3902. info = ams_unit.get("info")
  3903. if info is not None:
  3904. try:
  3905. info_val = int(str(info), 16)
  3906. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3907. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3908. except (ValueError, TypeError):
  3909. pass # Skip unparseable info values
  3910. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3911. if "dry_sf_reason" in ams_unit:
  3912. sf_reason = ams_unit["dry_sf_reason"]
  3913. if isinstance(sf_reason, list):
  3914. ams_unit["dry_sf_reason"] = [
  3915. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3916. ]
  3917. else:
  3918. ams_unit["dry_sf_reason"] = []
  3919. # Persist updated drying fields back to raw_data
  3920. self.state.raw_data["ams"] = merged_ams
  3921. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3922. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3923. # — fire the callback so smart-plug auto-off-after-drying can run,
  3924. # and drop our cached target-cycle params so the badge stops claiming
  3925. # an active cycle. Works identically for queue-triggered, ambient,
  3926. # and manual drying because we observe the firmware-reported state.
  3927. for ams_unit in merged_ams:
  3928. try:
  3929. ams_id = int(ams_unit.get("id", -1))
  3930. except (TypeError, ValueError):
  3931. continue
  3932. if ams_id < 0:
  3933. continue
  3934. # The firmware phase outranks the stalled-countdown heuristic even
  3935. # on a transient-zero frame, which the completion guard below skips.
  3936. # Clear a previously raised flag before that early continue.
  3937. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3938. ams_unit["dry_countdown_stalled"] = False
  3939. # Only evaluate the edge when this update carries an explicit
  3940. # dry_time. An absent / unparseable value is NOT zero — treating
  3941. # it as 0 lets a tray-only partial fake a drying-complete edge
  3942. # (#1462). Skip without touching the remembered value so the
  3943. # next update that DOES carry dry_time sees the true previous.
  3944. raw_dry_time = ams_unit.get("dry_time")
  3945. if raw_dry_time is None:
  3946. continue
  3947. try:
  3948. current = int(raw_dry_time)
  3949. except (TypeError, ValueError):
  3950. continue
  3951. # A dry_time of 0 only means "finished" when the unit also reports
  3952. # an idle phase. Between the command ack and the countdown settling
  3953. # the firmware publishes a transient 0 while the AMS is still
  3954. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3955. # 12-hour cycle. Taking that at face value dropped the cached target
  3956. # (leaving the badge to guess the filament from tray 1, so a PLA
  3957. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3958. # schedules smart-plug auto-off. dry_status comes from the same info
  3959. # hex parsed above; when it is absent we let the edge through, so a
  3960. # firmware that never reports one still ends its cycles.
  3961. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3962. # Leave the remembered value alone, exactly as the absent-
  3963. # dry_time skip above does: whichever push ends the cycle for
  3964. # real must still see a non-zero previous.
  3965. logger.debug(
  3966. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3967. self.serial_number,
  3968. ams_id,
  3969. ams_unit.get("dry_status"),
  3970. )
  3971. continue
  3972. seen_before = ams_id in self._previous_dry_times
  3973. previous = self._previous_dry_times.get(ams_id, 0)
  3974. self._previous_dry_times[ams_id] = current
  3975. if current > 0:
  3976. cycle = self._dry_cycles.get(ams_id)
  3977. if cycle is None or previous == 0:
  3978. cycle = {
  3979. "peak": current,
  3980. # A rise from an observed 0 is the cycle's first minute.
  3981. # A first sighting already counting down is not.
  3982. "start_seen": seen_before,
  3983. "target": self._drying_targets.get(ams_id),
  3984. }
  3985. self._dry_cycles[ams_id] = cycle
  3986. elif current > int(cycle["peak"]):
  3987. cycle["peak"] = current
  3988. # Stall detection: stamp value CHANGES only — a live countdown
  3989. # decrements once a minute, so repeats of the same value within
  3990. # the minute must not refresh the stamp, and a frame without a
  3991. # dry_time never reaches here (the absent-value skip above).
  3992. now_mono = time.monotonic()
  3993. if current != previous or ams_id not in self._dry_time_changed_at:
  3994. self._dry_time_changed_at[ams_id] = now_mono
  3995. ams_unit["dry_countdown_stalled"] = bool(
  3996. current > 0
  3997. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  3998. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  3999. )
  4000. if previous > 0 and current == 0:
  4001. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  4002. if self.on_drying_complete:
  4003. self.on_drying_complete(ams_id)
  4004. cycle = self._dry_cycles.pop(ams_id, None) or {"peak": previous, "start_seen": False, "target": None}
  4005. if self.on_drying_cycle_end:
  4006. self.on_drying_cycle_end(self._drying_cycle_end(ams_id, previous, cycle))
  4007. # Create a hash of relevant AMS data to detect changes.
  4008. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  4009. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  4010. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  4011. # above but leaves the raw payload's tracked fields untouched — so a
  4012. # raw-based hash never flips and on_ams_change never fires, leaving the
  4013. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  4014. # always spans every unit, so a partial single-unit update can't produce a
  4015. # spuriously different hash from a full pushall.
  4016. ams_hash_data = []
  4017. for ams_unit in merged_ams:
  4018. for tray in ams_unit.get("tray", []):
  4019. # Include fields that matter for filament tracking
  4020. ams_hash_data.append(
  4021. f"{ams_unit.get('id')}:{tray.get('id')}:"
  4022. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  4023. )
  4024. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  4025. # Only trigger callback if AMS data actually changed
  4026. if ams_hash != self._previous_ams_hash:
  4027. self._previous_ams_hash = ams_hash
  4028. if self.on_ams_change:
  4029. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  4030. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  4031. # may lack fields like 'remain' that the merged state preserves
  4032. self.on_ams_change(merged_ams)
  4033. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  4034. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  4035. # or cali_idx — so an assignment that only swaps the filament id on an
  4036. # already-loaded slot would not flip the hash, and gating the check on
  4037. # it would miss exactly the confirmation we are after.
  4038. if self._pending_assignments:
  4039. self._check_assignment_verifications()
  4040. @staticmethod
  4041. def _drying_cycle_end(ams_id: int, remaining: int, cycle: dict[str, object]) -> DryingCycleEnd:
  4042. """Build the cycle-end report from the record kept while it ran."""
  4043. target = cycle.get("target")
  4044. target_temp: int | None = None
  4045. target_hours: int | None = None
  4046. if isinstance(target, dict):
  4047. try:
  4048. target_temp = int(target.get("temp") or 0) or None
  4049. target_hours = int(target.get("duration_hours") or 0) or None
  4050. except (TypeError, ValueError):
  4051. target_temp = target_hours = None
  4052. return DryingCycleEnd(
  4053. ams_id=ams_id,
  4054. remaining_minutes=remaining,
  4055. peak_minutes=max(int(cycle.get("peak") or 0), remaining),
  4056. start_seen=bool(cycle.get("start_seen")),
  4057. target_temp=target_temp,
  4058. target_hours=target_hours,
  4059. )
  4060. def _log_drying_cycle_end(
  4061. self,
  4062. ams_id: int,
  4063. remaining: int,
  4064. ams_unit: dict,
  4065. target: dict[str, object] | None,
  4066. ) -> None:
  4067. """Report a finished drying cycle, with the firmware's reason when it was
  4068. cut short (#2770).
  4069. A cycle that reaches its configured duration needs no explanation and
  4070. keeps the one-line "drying complete" it has always had. One that ends
  4071. with most of its countdown left was ended by somebody, and there are
  4072. only two candidates: a stop Bambuddy sent — the print-takes-priority
  4073. stop, or the user's Stop button — which is named as such, or the
  4074. firmware.
  4075. For the firmware case the only account of why lives in fields we already
  4076. parse but have never written down: the ``dry_status`` /
  4077. ``dry_sub_status`` phase from the info hex, the per-unit
  4078. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  4079. that moment. Logging them at INFO puts them in every support bundle by
  4080. default, which is what a report like #2770 needs before its cause can be
  4081. argued about at all.
  4082. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  4083. logged for every cycle, early or not, because they are what decides
  4084. whether auto-drying re-arms. Reconstructing them for #2770 meant
  4085. cross-referencing hourly alarm lines against 30-second scheduler debug
  4086. that was switched off at the time; one line here says it outright — a
  4087. cycle ending at 63 degC with the reading still above the threshold is
  4088. the whole shape of the re-arm loop.
  4089. """
  4090. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  4091. if ams_id in self._drying_stops_sent:
  4092. self._drying_stops_sent.discard(ams_id)
  4093. logger.info(
  4094. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  4095. self.serial_number,
  4096. ams_id,
  4097. remaining,
  4098. box,
  4099. )
  4100. return
  4101. if remaining <= _EARLY_DRY_END_MINUTES:
  4102. logger.info(
  4103. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  4104. self.serial_number,
  4105. ams_id,
  4106. remaining,
  4107. box,
  4108. )
  4109. return
  4110. requested_minutes: int | None = None
  4111. if target is not None:
  4112. try:
  4113. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  4114. except (TypeError, ValueError):
  4115. requested_minutes = None
  4116. logger.info(
  4117. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  4118. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  4119. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  4120. self.serial_number,
  4121. ams_id,
  4122. remaining,
  4123. requested_minutes if requested_minutes is not None else "?",
  4124. ams_unit.get("dry_status"),
  4125. ams_unit.get("dry_sub_status"),
  4126. ams_unit.get("dry_sf_reason") or [],
  4127. [e.full_code for e in self.state.hms_errors] or "none",
  4128. box,
  4129. )
  4130. def register_assignment_verification(
  4131. self,
  4132. ams_id: int,
  4133. tray_id: int,
  4134. tray_info_idx: str,
  4135. tray_color: str,
  4136. cali_idx: int | None,
  4137. ) -> None:
  4138. """Record an assignment we just pushed so subsequent AMS telemetry can
  4139. confirm the tray actually accepted it (#2582).
  4140. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  4141. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  4142. accepted filament id back in the per-tray push, so a match means the
  4143. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  4144. signal so we can specifically flag "filament loaded but K-profile not
  4145. applied", which is the exact symptom the reporter chased via flow-cal.
  4146. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  4147. there is nothing to verify and no record is stored.
  4148. """
  4149. want_idx = (tray_info_idx or "").strip().upper()
  4150. if not want_idx:
  4151. return
  4152. self._pending_assignments[(ams_id, tray_id)] = {
  4153. "tray_info_idx": want_idx,
  4154. "tray_color": (tray_color or "").strip().upper(),
  4155. "cali_idx": cali_idx,
  4156. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  4157. "last_seen_idx": None,
  4158. }
  4159. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  4160. """Locate the live tray dict for a pending verification.
  4161. External spools (ams_id 255) live in ``vt_tray`` under global ids
  4162. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  4163. report a single tray whose id may not equal the logical tray_id, so fall
  4164. back to the sole tray when an id match fails.
  4165. """
  4166. raw = self.state.raw_data or {}
  4167. if ams_id == 255:
  4168. want_ext = external_tray_id(tray_id)
  4169. for vt in raw.get("vt_tray", []) or []:
  4170. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  4171. return vt
  4172. return None
  4173. for unit in raw.get("ams", []) or []:
  4174. if str(unit.get("id")) != str(ams_id):
  4175. continue
  4176. trays = unit.get("tray", []) or []
  4177. for tray in trays:
  4178. if str(tray.get("id")) == str(tray_id):
  4179. return tray
  4180. if ams_id >= 128 and len(trays) == 1:
  4181. return trays[0]
  4182. return None
  4183. return None
  4184. def _check_assignment_verifications(self) -> None:
  4185. """Compare each pending assignment against live tray telemetry and fire
  4186. ``on_assignment_verified`` on a match or once the deadline passes.
  4187. Runs on every AMS push. Non-matching-but-still-within-window entries are
  4188. left in place for the next push. The timeout branch only fires when a
  4189. later push arrives after the deadline; if the printer goes silent we
  4190. simply never confirm, which is preferable to inventing a failure.
  4191. """
  4192. now = time.monotonic()
  4193. for key, want in list(self._pending_assignments.items()):
  4194. ams_id, tray_id = key
  4195. tray = self._find_verify_tray(ams_id, tray_id)
  4196. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  4197. if tray is not None and actual_idx:
  4198. want["last_seen_idx"] = actual_idx
  4199. if actual_idx and actual_idx == want["tray_info_idx"]:
  4200. self._pending_assignments.pop(key, None)
  4201. kprofile_applied = True
  4202. want_cali = want.get("cali_idx")
  4203. if want_cali is not None and want_cali >= 0:
  4204. actual_cali = tray.get("cali_idx")
  4205. kprofile_applied = actual_cali == want_cali
  4206. self._fire_assignment_verified(
  4207. ams_id,
  4208. tray_id,
  4209. True,
  4210. {
  4211. "tray_info_idx": actual_idx,
  4212. "kprofile_applied": kprofile_applied,
  4213. },
  4214. )
  4215. elif now >= want["deadline"]:
  4216. self._pending_assignments.pop(key, None)
  4217. self._fire_assignment_verified(
  4218. ams_id,
  4219. tray_id,
  4220. False,
  4221. {
  4222. "expected_tray_info_idx": want["tray_info_idx"],
  4223. "actual_tray_info_idx": want.get("last_seen_idx"),
  4224. # True when we saw the tray at least once (so the push
  4225. # channel is alive and the printer really stored a
  4226. # different/blank id) vs never observing it at all.
  4227. "saw_tray": want.get("last_seen_idx") is not None,
  4228. },
  4229. )
  4230. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  4231. if verified:
  4232. logger.info(
  4233. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  4234. self.serial_number,
  4235. ams_id,
  4236. tray_id,
  4237. detail.get("tray_info_idx"),
  4238. detail.get("kprofile_applied"),
  4239. )
  4240. else:
  4241. logger.warning(
  4242. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  4243. self.serial_number,
  4244. ams_id,
  4245. tray_id,
  4246. detail.get("expected_tray_info_idx"),
  4247. detail.get("actual_tray_info_idx"),
  4248. detail.get("saw_tray"),
  4249. )
  4250. if self.on_assignment_verified:
  4251. try:
  4252. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  4253. except Exception:
  4254. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  4255. @staticmethod
  4256. def _probe_number(value, fallback: float | None = None) -> float | None:
  4257. """Coerce a telemetry field to a number, or return `fallback`.
  4258. Firmware is inconsistent about whether these arrive as ints or as
  4259. numeric strings, and the probe must never raise on a surprise type.
  4260. """
  4261. try:
  4262. return float(value)
  4263. except (TypeError, ValueError):
  4264. return fallback
  4265. def _probe_end_of_print(self, data: dict) -> None:
  4266. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  4267. Opens on the first frame that looks like end-of-print (last object
  4268. layer reached, progress at 99+, or no remaining time), then logs each
  4269. frame in which any probed field changed, and closes on the transition
  4270. out of RUNNING. Armed once per print — see the module-level comment on
  4271. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  4272. currently see into.
  4273. Read-only with respect to printer state: this is instrumentation, and
  4274. nothing downstream may come to depend on it.
  4275. """
  4276. if not logger.isEnabledFor(logging.DEBUG):
  4277. return
  4278. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  4279. return
  4280. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  4281. if not present:
  4282. return
  4283. if not self._eop_probe_open:
  4284. # Open on any end-of-print signal. Read from the raw frame first so
  4285. # the frame that *carries* the signal is itself captured — state
  4286. # fields are only updated further down this same call.
  4287. frame_layer = data.get("layer_num")
  4288. if self._is_stale_layer(frame_layer):
  4289. frame_layer = None
  4290. layer = self._probe_number(frame_layer, self.state.layer_num) or 0
  4291. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  4292. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  4293. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  4294. at_last_layer = total > 0 and layer >= total
  4295. # `remaining <= 0` is only meaningful once the print has actually
  4296. # progressed — it reads 0 during the pre-print calibration too.
  4297. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  4298. if not (at_last_layer or percent >= 99 or out_of_time):
  4299. return
  4300. self._eop_probe_open = True
  4301. self._eop_probe_frames = 0
  4302. self._eop_probe_last = {}
  4303. logger.debug(
  4304. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  4305. self.serial_number,
  4306. layer,
  4307. total,
  4308. percent,
  4309. remaining,
  4310. )
  4311. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  4312. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  4313. self._eop_probe_last.update(present)
  4314. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  4315. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  4316. self._eop_probe_frames += 1
  4317. logger.debug(
  4318. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  4319. self.serial_number,
  4320. _END_OF_PRINT_PROBE_MAX_FRAMES,
  4321. )
  4322. return
  4323. if changed or closing:
  4324. self._eop_probe_frames += 1
  4325. logger.debug(
  4326. "[%s] EOP-PROBE %s%s: %s",
  4327. self.serial_number,
  4328. self._eop_probe_frames,
  4329. " CLOSE" if closing else "",
  4330. # `changed` on a closing frame can be empty; fall back to the
  4331. # full picture so the last line is always self-contained.
  4332. changed if changed else present,
  4333. )
  4334. if closing:
  4335. self._eop_probe_open = False
  4336. self._eop_probe_armed = False
  4337. self._eop_probe_last = {}
  4338. @property
  4339. def layer_before_new_print(self) -> int:
  4340. """The layer the printer was on when a print start was detected, until
  4341. it reports another (#3317); 0 when none.
  4342. For a print that is resumed rather than new, which a restart while it
  4343. was paused makes look new, that is the layer it is still on (#2984).
  4344. """
  4345. return self._stale_layer_num
  4346. def _is_stale_layer(self, value) -> bool:
  4347. """Whether a frame's `layer_num` is the previous print's last layer (#3317)."""
  4348. if not self._stale_layer_num:
  4349. return False
  4350. try:
  4351. return int(value) == self._stale_layer_num
  4352. except (TypeError, ValueError):
  4353. return False
  4354. def _apply_nozzle_temp(self, temps: dict, temp_val) -> None:
  4355. """Set ``nozzle`` / ``nozzle_target`` / ``nozzle_heating`` from an extruder's ``temp``.
  4356. H2D protocol: temp field encoding depends on value
  4357. - When > 500: encoded as (target * 65536 + current) - heater is ON
  4358. - When < 500: direct Celsius current temp only - heater is OFF
  4359. """
  4360. # Check if we recently set the target locally (within 5 seconds)
  4361. # If so, don't let MQTT data overwrite it
  4362. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4363. respect_local_target = (time.time() - local_set_time) < 5.0
  4364. if temp_val > 500:
  4365. # Encoded format: temp = target * 65536 + current
  4366. target = temp_val // 65536
  4367. current = temp_val % 65536
  4368. if 0 < target < 500 and not respect_local_target:
  4369. temps["nozzle_target"] = float(target)
  4370. if -50 < current < 500:
  4371. temps["nozzle"] = float(current)
  4372. # Heating = encoded AND we're using the MQTT target (not local override)
  4373. # If local target is being respected, use local target to determine heating
  4374. if respect_local_target:
  4375. local_target = self.state.temperatures.get("nozzle_target", 0)
  4376. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4377. else:
  4378. temps["nozzle_heating"] = target > 0 and current < target
  4379. elif -50 < temp_val < 500:
  4380. # Direct Celsius = heater is OFF (or at target with heater off)
  4381. temps["nozzle"] = float(temp_val)
  4382. if not respect_local_target:
  4383. temps["nozzle_target"] = 0.0
  4384. temps["nozzle_heating"] = False # Direct = not heating
  4385. def _update_state(self, data: dict):
  4386. """Update printer state from message data."""
  4387. _previous_state = self.state.state
  4388. # #2547: instrumentation only — runs before any state mutation so the
  4389. # frame carrying an end-of-print signal is logged as it arrived.
  4390. try:
  4391. self._probe_end_of_print(data)
  4392. except Exception: # pragma: no cover - a probe must never break ingest
  4393. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  4394. # Update state fields
  4395. if "gcode_state" in data:
  4396. self.state.state = data["gcode_state"]
  4397. if "gcode_file" in data:
  4398. self.state.gcode_file = data["gcode_file"]
  4399. self.state.current_print = data["gcode_file"]
  4400. # The answer to a print start the printer refused names the job it
  4401. # refused, not one it runs: read as status, its job id told the start
  4402. # watchdog the file had landed.
  4403. refused_start = (
  4404. data.get("command") == "project_file"
  4405. and data.get("result") is not None
  4406. and str(data["result"]).upper() != "SUCCESS"
  4407. )
  4408. if "subtask_name" in data and not refused_start:
  4409. self.state.subtask_name = data["subtask_name"]
  4410. # Prefer subtask_name as current_print if available
  4411. if data["subtask_name"]:
  4412. self.state.current_print = data["subtask_name"]
  4413. if "subtask_id" in data and not refused_start:
  4414. self.state.subtask_id = data["subtask_id"]
  4415. if "mc_percent" in data:
  4416. # Billing: retain this frame's latest positive value immediately.
  4417. # A display-side abort may be the very next frame (and may omit
  4418. # mc_percent entirely), so retaining only the previous frame can
  4419. # lose the only usable estimate for proportional charging.
  4420. previous_progress = self.state.progress
  4421. new_progress = float(data["mc_percent"])
  4422. if new_progress > 0:
  4423. self._last_valid_progress = new_progress
  4424. self.state.progress = new_progress
  4425. # #2547: strictly-increasing only. The firmware resets progress to 0
  4426. # on cancel and re-reports the same percent on most frames; neither
  4427. # is the print advancing, and both would make the frame bank grab a
  4428. # camera frame for nothing.
  4429. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  4430. self.on_print_progress(int(self.state.progress))
  4431. if "mc_remaining_time" in data:
  4432. self.state.remaining_time = int(data["mc_remaining_time"])
  4433. if "mc_print_sub_stage" in data:
  4434. new_sub_stage = int(data["mc_print_sub_stage"])
  4435. if new_sub_stage != self.state.mc_print_sub_stage:
  4436. logger.debug(
  4437. f"[{self.serial_number}] mc_print_sub_stage changed: "
  4438. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  4439. )
  4440. self.state.mc_print_sub_stage = new_sub_stage
  4441. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  4442. # front because three places below consult it and they run in an order
  4443. # that is not the order they read most naturally in: the layer-advance
  4444. # refresh (#2702) must not fire on a frame that already answers it, the
  4445. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  4446. # reset must not discard a total that belongs to the starting print.
  4447. total_from_this_frame = 0
  4448. if "total_layer_num" in data:
  4449. try:
  4450. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  4451. except (TypeError, ValueError):
  4452. # Must not escape. `_on_message` catches only JSONDecodeError
  4453. # and paho is left at `suppress_exceptions = False`, so an
  4454. # exception raised here is re-raised on the network thread and
  4455. # takes the printer connection down over one unusable field.
  4456. # Treat it as "not reported": the refresh below then recovers
  4457. # the real total from a pushall.
  4458. logger.debug(
  4459. "[%s] ignoring unusable total_layer_num: %r",
  4460. self.serial_number,
  4461. data["total_layer_num"],
  4462. )
  4463. if "layer_num" in data:
  4464. try:
  4465. new_layer = int(data["layer_num"])
  4466. except (TypeError, ValueError):
  4467. # Contained for the same reason as `total_layer_num` above: an
  4468. # exception raised here escapes `_update_state` and paho
  4469. # re-raises it on the network thread. Losing this frame would
  4470. # also lose the print-start and completion detection further
  4471. # down, which is worse than losing a layer number.
  4472. #
  4473. # Held at the last known layer rather than substituted with 0:
  4474. # a fabricated 0 reads as the firmware's cancel reset, which
  4475. # would move `_last_valid_layer_num` and show layer 0 in the UI
  4476. # until the next good frame.
  4477. logger.debug(
  4478. "[%s] ignoring unusable layer_num: %r",
  4479. self.serial_number,
  4480. data["layer_num"],
  4481. )
  4482. new_layer = self.state.layer_num
  4483. if self._is_stale_layer(new_layer):
  4484. logger.debug(
  4485. "[%s] ignoring layer_num %s: last layer of the previous print",
  4486. self.serial_number,
  4487. new_layer,
  4488. )
  4489. new_layer = self.state.layer_num
  4490. elif new_layer > 0:
  4491. # The new print reports a layer of its own; from here on the
  4492. # previous print's value is a layer this print can reach.
  4493. self._stale_layer_num = 0
  4494. old_layer = self.state.layer_num
  4495. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  4496. if old_layer > 0:
  4497. self._last_valid_layer_num = old_layer
  4498. self.state.layer_num = new_layer
  4499. # Trigger layer change callback if layer increased
  4500. if new_layer > old_layer and self.on_layer_change:
  4501. self.on_layer_change(new_layer)
  4502. # #2702: the print is demonstrably laying down layers but we still
  4503. # have no denominator, so the pushall requested at print start
  4504. # either went unanswered or raced the printer learning the total.
  4505. # Ask once more — by layer 1 the printer definitely knows it.
  4506. # One-shot: an unanswered pushall must not turn into a per-layer
  4507. # retry loop for the rest of the print.
  4508. if (
  4509. new_layer > old_layer
  4510. and self._total_layers_refresh_armed
  4511. and not self.state.total_layers
  4512. and not total_from_this_frame
  4513. ):
  4514. self._total_layers_refresh_armed = False
  4515. logger.debug(
  4516. "[%s] layer %s with no total_layer_num — re-requesting full status",
  4517. self.serial_number,
  4518. new_layer,
  4519. )
  4520. self._request_push_all()
  4521. # #2547: there is deliberately NO finish-photo trigger on the
  4522. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  4523. # moment the printer *starts* the final layer, not the moment it
  4524. # finishes it — on the H2C capture that closed #2547 the edge
  4525. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  4526. # filament change before the print actually ended, so the photo
  4527. # showed the toolhead mid-print over the part. Worse, the trigger
  4528. # latched `_finish_photo_captured`, locking out both the stage-22
  4529. # and FINISH triggers below for the rest of the print.
  4530. #
  4531. # #1867 (End G-code ejects the plate before FINISH) is handled
  4532. # where it belongs instead: `on_finish_photo_moment` prefers the
  4533. # in-print frame bank when the dispatcher recorded that it injected
  4534. # End G-code into this print. See services/print_dispatch_context.
  4535. if total_from_this_frame:
  4536. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  4537. # end — same shape as the `layer_num` reset guarded above. Applying
  4538. # only positive values preserves the last known good denominator so
  4539. # the usage-tracker split path (#1771) survives the reset frame.
  4540. self.state.total_layers = total_from_this_frame
  4541. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  4542. # Convert to 0-100 percentage for display
  4543. def parse_fan_speed(value: str | int | None) -> int | None:
  4544. if value is None:
  4545. return None
  4546. try:
  4547. speed = int(value)
  4548. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  4549. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  4550. if speed <= 15:
  4551. return round(speed * 100 / 15)
  4552. # If already a percentage (0-255 scale from some printers), convert
  4553. elif speed <= 255:
  4554. return round(speed * 100 / 255)
  4555. return speed
  4556. except (ValueError, TypeError):
  4557. return None
  4558. # Log fan fields once for debugging
  4559. if not hasattr(self, "_fan_fields_logged"):
  4560. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  4561. if fan_fields:
  4562. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  4563. self._fan_fields_logged = True
  4564. if "cooling_fan_speed" in data:
  4565. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  4566. if "big_fan1_speed" in data:
  4567. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  4568. if "big_fan2_speed" in data:
  4569. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  4570. if "heatbreak_fan_speed" in data:
  4571. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  4572. # Calibration stage tracking
  4573. if "stg_cur" in data:
  4574. new_stg = data["stg_cur"]
  4575. prev_stg = self.state.stg_cur
  4576. # Always log ANY stg_cur change for debugging filament operations
  4577. if new_stg != prev_stg:
  4578. logger.debug(
  4579. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  4580. )
  4581. # A stage we cannot name is the one worth seeing at the default
  4582. # log level: the DEBUG line above is off in normal running, so
  4583. # an unnamed stage otherwise reaches the user as "Unknown stage
  4584. # (72)" on a card with nothing behind it to say when it
  4585. # happened or what the printer was doing. Recorded once per
  4586. # stage number per session, with the stage it came from and the
  4587. # print state, which is what naming it later needs. Guarded on
  4588. # the int type because the field is whatever the firmware sent.
  4589. if (
  4590. isinstance(new_stg, int)
  4591. and not isinstance(new_stg, bool)
  4592. # -1 is Bambuddy's own "not in a stage" sentinel and the
  4593. # initial value of the field, not something the firmware
  4594. # reports; every print would otherwise report it on the way
  4595. # out of its last real stage.
  4596. and new_stg != -1
  4597. and new_stg not in STAGE_NAMES
  4598. and new_stg not in self._unnamed_stages_seen
  4599. ):
  4600. self._unnamed_stages_seen.add(new_stg)
  4601. logger.info(
  4602. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  4603. "state=%s progress=%s%% layer=%s/%s",
  4604. self.serial_number,
  4605. new_stg,
  4606. self.model,
  4607. prev_stg,
  4608. get_stage_name(prev_stg),
  4609. self.state.state,
  4610. self.state.progress,
  4611. self.state.layer_num,
  4612. self.state.total_layers,
  4613. )
  4614. self.state.stg_cur = new_stg
  4615. # #1721 end-of-print finish photo trigger.
  4616. # Stage 22 = "Filament unloading" fires at end-of-print AND
  4617. # during mid-print color swaps. The end-of-print gate
  4618. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  4619. # — those signals only line up at the real end. Edge-only
  4620. # (prev != 22) so the trigger fires once per stage entry.
  4621. if (
  4622. new_stg == 22
  4623. and prev_stg != 22
  4624. and self._was_running
  4625. and not self._finish_photo_captured
  4626. and self.on_finish_photo_moment
  4627. ):
  4628. progress = self.state.progress or 0.0
  4629. layer_num = self.state.layer_num or 0
  4630. total_layers = self.state.total_layers or 0
  4631. remaining = self.state.remaining_time or 0
  4632. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  4633. if is_end_of_print:
  4634. self._finish_photo_captured = True
  4635. logger.info(
  4636. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  4637. f"progress={progress}, layer={layer_num}/{total_layers}, "
  4638. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  4639. )
  4640. self.on_finish_photo_moment(
  4641. {
  4642. "trigger": "stage_22",
  4643. "filename": self._previous_gcode_file or self.state.gcode_file,
  4644. "subtask_name": self.state.subtask_name,
  4645. "timelapse_was_active": self._timelapse_during_print,
  4646. }
  4647. )
  4648. if "stg" in data:
  4649. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  4650. # Temperature data
  4651. temps = {}
  4652. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  4653. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  4654. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  4655. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  4656. # Log ALL keys in print data for H2D temperature discovery
  4657. all_keys = sorted(data.keys())
  4658. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  4659. self._temp_fields_logged = True
  4660. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  4661. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  4662. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  4663. self._vir_slot_logged = True
  4664. # Log nozzle hardware info fields (once)
  4665. nozzle_fields = {
  4666. k: v
  4667. for k, v in data.items()
  4668. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  4669. }
  4670. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  4671. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  4672. self._nozzle_fields_logged = True
  4673. # Parse active extruder from device.extruder.state bit 8
  4674. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  4675. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  4676. if "device" in data and isinstance(data.get("device"), dict):
  4677. device = data["device"]
  4678. # One-shot identification probe: surface whatever the firmware uses to
  4679. # name itself so an unknown model in a support bundle becomes self-
  4680. # diagnosing. INFO level so it shows up without debug logging. Falls
  4681. # back to dumping device.keys() if none of the known fields are present
  4682. # (so a future Bambu rename like `model_name` is still observable).
  4683. if not getattr(self, "_device_id_logged", False):
  4684. id_fields = {
  4685. k: device.get(k)
  4686. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  4687. if k in device
  4688. }
  4689. if id_fields:
  4690. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  4691. else:
  4692. logger.info(
  4693. "[%s] Device identification: no known id fields; device.keys=%s",
  4694. self.serial_number,
  4695. sorted(device.keys()),
  4696. )
  4697. self._device_id_logged = True
  4698. self._parse_extruder_position(data)
  4699. # Log device.extruder structure for active extruder
  4700. if "device" in data and isinstance(data.get("device"), dict):
  4701. device = data["device"]
  4702. if "extruder" in device:
  4703. ext_data = device["extruder"]
  4704. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4705. if "state" in ext_data:
  4706. state_val = ext_data["state"]
  4707. # Extract bits 12-14 (3 bits) for switch state
  4708. switch_state = (state_val >> 12) & 0x7
  4709. self._debug_on_change(
  4710. "extruder_state",
  4711. state_val,
  4712. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4713. self.serial_number,
  4714. state_val,
  4715. switch_state,
  4716. )
  4717. # Log 'cur' field if present (might indicate current/active extruder)
  4718. if "cur" in ext_data:
  4719. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4720. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4721. # it first. Repeated here so _update_state stays a complete "absorb this
  4722. # payload" step for any other caller; re-parsing the same block is free.
  4723. self._parse_fila_switch(data)
  4724. self._parse_extruder_slots(data)
  4725. if "bed_temper" in data:
  4726. temps["bed"] = float(data["bed_temper"])
  4727. if "bed_target_temper" in data:
  4728. temps["bed_target"] = float(data["bed_target_temper"])
  4729. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4730. has_h2d_extruder_info = (
  4731. "device" in data
  4732. and isinstance(data.get("device"), dict)
  4733. and "extruder" in data["device"]
  4734. and isinstance(data["device"]["extruder"].get("info"), list)
  4735. and len(data["device"]["extruder"]["info"]) >= 2
  4736. )
  4737. # A rack printer (H3C, #3442) swaps hotends on its one extruder, and
  4738. # nozzle_temper keeps reporting the one just put back in the rack. The
  4739. # mounted one's temperature is in device.extruder.info, which Bambu
  4740. # Studio reads over nozzle_temper too (DevExtruderSystem ParseV2_0).
  4741. # The layout knows an H3C by its model before any AMS data came.
  4742. mounted_tool_temp = self.tray_layout.rack
  4743. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4744. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4745. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4746. if "nozzle_temper" in data and not mounted_tool_temp:
  4747. if has_h2d_extruder_info:
  4748. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4749. else:
  4750. temps["nozzle"] = float(data["nozzle_temper"])
  4751. if "nozzle_target_temper" in data and not mounted_tool_temp:
  4752. if has_h2d_extruder_info:
  4753. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4754. else:
  4755. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4756. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4757. if not has_h2d_extruder_info:
  4758. # Try multiple possible field names used by different firmware versions
  4759. if "nozzle_temper_2" in data:
  4760. val = float(data["nozzle_temper_2"])
  4761. if -50 < val < 500: # Valid temp range
  4762. temps["nozzle_2"] = val
  4763. else:
  4764. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4765. elif "right_nozzle_temper" in data:
  4766. val = float(data["right_nozzle_temper"])
  4767. if -50 < val < 500: # Valid temp range
  4768. temps["nozzle_2"] = val
  4769. else:
  4770. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4771. if "nozzle_target_temper_2" in data:
  4772. val = float(data["nozzle_target_temper_2"])
  4773. if 0 <= val < 500: # Valid temp range
  4774. temps["nozzle_2_target"] = val
  4775. else:
  4776. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4777. elif "right_nozzle_target_temper" in data:
  4778. val = float(data["right_nozzle_target_temper"])
  4779. if 0 <= val < 500: # Valid temp range
  4780. temps["nozzle_2_target"] = val
  4781. else:
  4782. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4783. # Also check for left nozzle as primary (some H2 models)
  4784. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4785. temps["nozzle"] = float(data["left_nozzle_temper"])
  4786. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4787. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4788. if "chamber_temper" in data:
  4789. chamber_val = float(data["chamber_temper"])
  4790. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4791. # Check if we recently set the target locally (within 5 seconds)
  4792. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4793. respect_local = (time.time() - local_set_time) < 5.0
  4794. # H2D protocol: chamber_temper encoding indicates heater state
  4795. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4796. # - When < 500: direct Celsius current temp only - heater is OFF
  4797. if -50 < chamber_val < 100:
  4798. # Direct value = heater is OFF
  4799. temps["chamber"] = chamber_val
  4800. if not respect_local:
  4801. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4802. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4803. else:
  4804. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4805. # Try to decode if it looks like an encoded value
  4806. if chamber_val > 500:
  4807. mqtt_target = int(chamber_val) // 65536
  4808. current = int(chamber_val) % 65536
  4809. logger.debug(
  4810. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4811. )
  4812. if -50 < current < 100:
  4813. temps["chamber"] = float(current)
  4814. # Store decoded target for later use, but DON'T set chamber_heating here!
  4815. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4816. # which is the authoritative source the slicer uses.
  4817. if not respect_local:
  4818. if 0 <= mqtt_target <= 60:
  4819. # Store as "decoded" target - may be overridden by explicit target fields
  4820. temps["_chamber_decoded_target"] = float(mqtt_target)
  4821. # Chamber target temperature (set by print file or display)
  4822. if "mc_target_cham" in data:
  4823. mc_target = float(data["mc_target_cham"])
  4824. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4825. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4826. if 0 <= mc_target <= 60:
  4827. temps["chamber_target"] = mc_target
  4828. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4829. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4830. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4831. try:
  4832. if "info" in data and isinstance(data["info"], dict):
  4833. info_temp = data["info"].get("temp")
  4834. if info_temp is not None and "chamber" not in temps:
  4835. # Check for encoded value (target * 65536 + current)
  4836. if info_temp > 500:
  4837. # Decode: extract current temperature and target
  4838. target = info_temp // 65536
  4839. current = info_temp % 65536
  4840. temps["chamber"] = float(current)
  4841. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4842. if "_chamber_decoded_target" not in temps:
  4843. temps["_chamber_decoded_target"] = float(target)
  4844. logger.debug(
  4845. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4846. )
  4847. elif -50 < info_temp < 100:
  4848. # Valid direct temperature - heater is OFF
  4849. temps["chamber"] = float(info_temp)
  4850. temps["chamber_target"] = 0.0 # Direct value means heater off
  4851. self._debug_on_change(
  4852. "info_temp_direct",
  4853. info_temp,
  4854. "[%s] info.temp direct: %s°C (heater OFF)",
  4855. self.serial_number,
  4856. info_temp,
  4857. )
  4858. # H2D series: Dual extruder temps are in device.extruder.info array
  4859. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4860. if "device" in data and isinstance(data["device"], dict):
  4861. device = data["device"]
  4862. # Parse dual extruder temperatures
  4863. extruder_data = device.get("extruder", {})
  4864. extruder_info = extruder_data.get("info", [])
  4865. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4866. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4867. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4868. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4869. if has_h2d_extruder_info:
  4870. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4871. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4872. if "temp" in extruder_info[0]:
  4873. temp_val = extruder_info[0]["temp"]
  4874. if temp_val > 500:
  4875. # Encoded format: temp = target * 65536 + current
  4876. target = temp_val // 65536
  4877. current = temp_val % 65536
  4878. if -50 < current < 500:
  4879. temps["nozzle_2"] = float(current)
  4880. if 0 < target < 500:
  4881. temps["nozzle_2_target"] = float(target)
  4882. temps["nozzle_2_heating"] = target > 0 and current < target
  4883. elif -50 < temp_val < 500:
  4884. # Direct Celsius value = heater is OFF
  4885. temps["nozzle_2"] = float(temp_val)
  4886. temps["nozzle_2_target"] = 0.0
  4887. temps["nozzle_2_heating"] = False
  4888. # Left nozzle (extruder 1) - only for dual nozzle printers
  4889. # H2D protocol: temp field encoding depends on value
  4890. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4891. # - When < 500: direct Celsius current temp only - heater is OFF
  4892. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4893. self._apply_nozzle_temp(temps, extruder_info[1]["temp"])
  4894. # The H3C's one extruder: the hotend mounted on it (#3442).
  4895. elif mounted_tool_temp and "temp" in extruder_info[0]:
  4896. self._apply_nozzle_temp(temps, extruder_info[0]["temp"])
  4897. # The extruder snow is read by _parse_extruder_position, before the
  4898. # AMS block of the same frame (tray_now resolution needs it first).
  4899. # Parse bed heating state from device.bed.info.temp encoding
  4900. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4901. bed_data = device.get("bed", {})
  4902. bed_info = bed_data.get("info", {})
  4903. if "temp" in bed_info:
  4904. temp_val = bed_info["temp"]
  4905. if temp_val > 500:
  4906. target = temp_val // 65536
  4907. current = temp_val % 65536
  4908. temps["bed_heating"] = target > 0 and current < target
  4909. else:
  4910. temps["bed_heating"] = False
  4911. # Parse chamber temp from device.ctc.info.temp if not already set
  4912. ctc_data = device.get("ctc", {})
  4913. ctc_info = ctc_data.get("info", {})
  4914. # Parse airduct mode (0=cooling, 1=heating)
  4915. airduct_data = device.get("airduct", {})
  4916. if "modeCur" in airduct_data:
  4917. new_mode = airduct_data["modeCur"]
  4918. if new_mode != self.state.airduct_mode:
  4919. logger.debug(
  4920. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4921. )
  4922. self.state.airduct_mode = new_mode
  4923. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4924. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4925. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4926. # AIR_FUN enum: 1=part cooling, 2=aux, 3=chamber/exhaust,
  4927. # 10=second aux (FAN_REMOTE_COOLING_1). Aux 2 is the right fan and
  4928. # 10 the left on the P2S, the other way round on the X2D (#3373;
  4929. # Bambu Studio's N7.json / N6.json). The airduct `parts` list only
  4930. # contains the fans that physically exist, so it doubles as a
  4931. # presence signal for the two P2S/X2D add-on kits:
  4932. # - id 10 (second auxiliary part cooling fan) — reported ONLY here,
  4933. # never mirrored into a flat big_fanX_speed field.
  4934. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4935. # big_fan2_speed, but the part is only listed when the External
  4936. # Exhaust Fan kit (get_version module "eef") is installed.
  4937. # `state` is already a 0-100 percentage.
  4938. parts = airduct_data.get("parts")
  4939. if isinstance(parts, list):
  4940. speeds: dict[int, int] = {}
  4941. for part in parts:
  4942. if not isinstance(part, dict):
  4943. continue
  4944. try:
  4945. # Studio reads the id with get_flag_bits(id, 4, 8),
  4946. # so mask after shifting for the same reason `state`
  4947. # is masked below. Every id seen in the wild
  4948. # (16/32/48/160) decodes identically either way —
  4949. # this is consistency, not a live bug.
  4950. part_id = (int(part["id"]) >> 4) & 0xFF
  4951. # `state` is bit-packed like its sibling `range`
  4952. # (end << 16 | start), so take only the low 8 bits —
  4953. # the same decode Bambu Studio does with
  4954. # get_flag_bits(state, 0, 8). Without the mask a
  4955. # packed value would clamp to 100 instead of
  4956. # decoding to the real percentage.
  4957. part_state = int(part["state"]) & 0xFF
  4958. except (KeyError, ValueError, TypeError):
  4959. continue
  4960. # Ids seen across the support-package archive:
  4961. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4962. # 6 (H2 series, unmapped), 10 second aux.
  4963. speeds[part_id] = max(0, min(100, part_state))
  4964. # Absence in this list is what tells us a kit is NOT fitted,
  4965. # so it may only be trusted when the list is a full
  4966. # inventory rather than a diff frame. `device.airduct` is
  4967. # pushed field by field — the `modeCur` handler above exists
  4968. # for exactly that reason — and a truncated `parts` read as
  4969. # gospel would retract both accessory badges mid-print and
  4970. # start rejecting `aux2` on a printer that has the fan.
  4971. #
  4972. # Every airduct layout in the support-package archive
  4973. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4974. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4975. # part cooling fan and the aux fan, neither of which is
  4976. # optional on any machine that reports an airduct at all.
  4977. # A list carrying both is therefore a complete inventory; a
  4978. # list missing either is a partial frame, and we take its
  4979. # speeds without touching presence.
  4980. is_full_inventory = 1 in speeds and 2 in speeds
  4981. left_aux_speed = speeds.get(10)
  4982. if left_aux_speed is None and not is_full_inventory:
  4983. # Partial frame that didn't mention the second aux fan —
  4984. # keep whatever we already knew about it.
  4985. left_aux_speed = self.state.left_aux_fan_speed
  4986. if left_aux_speed != self.state.left_aux_fan_speed:
  4987. logger.debug(
  4988. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4989. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4990. )
  4991. # A FULL parts list without id 10 means the second aux fan is
  4992. # not installed — report None so the UI can hide the widget.
  4993. self.state.left_aux_fan_speed = left_aux_speed
  4994. # id 3 present == chamber exhaust fan installed (base P2S
  4995. # omits it). Only ever retracted on a full inventory.
  4996. if 3 in speeds:
  4997. self.state.exhaust_fan_present = True
  4998. elif is_full_inventory:
  4999. self.state.exhaust_fan_present = False
  5000. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  5001. # Check if we recently set the target locally (within 5 seconds)
  5002. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  5003. respect_local_target = (time.time() - local_set_time) < 5.0
  5004. # Log ctc_info contents for debugging
  5005. if ctc_info:
  5006. self._debug_on_change(
  5007. "ctc_info_keys",
  5008. tuple(ctc_info.keys()),
  5009. "[%s] ctc_info keys: %s",
  5010. self.serial_number,
  5011. list(ctc_info.keys()),
  5012. )
  5013. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  5014. # (what the slicer shows). This OVERRIDES any previously decoded target.
  5015. explicit_target = None
  5016. if "target" in ctc_info:
  5017. target_val = ctc_info["target"]
  5018. logger.debug(
  5019. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  5020. )
  5021. # Filter out invalid values (valid chamber target is 0-60°C)
  5022. if 0 <= target_val <= 60 and not respect_local_target:
  5023. explicit_target = float(target_val)
  5024. temps["chamber_target"] = explicit_target # Override any previous value
  5025. logger.debug(
  5026. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  5027. )
  5028. # Parse chamber temp from ctc.info.temp - may be encoded
  5029. if "temp" in ctc_info and "chamber" not in temps:
  5030. temp_val = ctc_info["temp"]
  5031. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  5032. if temp_val > 500:
  5033. # Encoded value: decode target and current
  5034. decoded_target = temp_val // 65536
  5035. current = temp_val % 65536
  5036. temps["chamber"] = float(current)
  5037. logger.debug(
  5038. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  5039. )
  5040. # Determine which target to use for heating state:
  5041. # Priority: local target > explicit target > decoded target
  5042. if respect_local_target:
  5043. local_target = self.state.temperatures.get("chamber_target", 0)
  5044. temps["chamber_heating"] = local_target > 0 and current < local_target
  5045. elif explicit_target is not None:
  5046. # Use explicit ctc.info.target - this is what slicer sees
  5047. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  5048. else:
  5049. # Fallback to decoded target only if no explicit target available
  5050. if not respect_local_target and "chamber_target" not in temps:
  5051. temps["chamber_target"] = float(decoded_target)
  5052. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  5053. else:
  5054. # Direct value (not encoded) - heater is OFF
  5055. temps["chamber"] = float(temp_val)
  5056. temps["chamber_heating"] = False
  5057. except Exception as e:
  5058. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  5059. if temps:
  5060. # Handle chamber_target: prefer explicit over decoded
  5061. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  5062. # No explicit target available, use decoded target from chamber_temper
  5063. temps["chamber_target"] = temps["_chamber_decoded_target"]
  5064. # Remove internal temp key before merging
  5065. temps.pop("_chamber_decoded_target", None)
  5066. # Merge new temps into existing, preserving valid values when new ones are filtered out
  5067. for key, value in temps.items():
  5068. self.state.temperatures[key] = value
  5069. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  5070. if "bed" in temps and self.on_bed_temp_update:
  5071. self.on_bed_temp_update(temps["bed"])
  5072. # Calculate chamber_heating after all targets are known
  5073. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  5074. if "chamber" in temps and "chamber_heating" not in temps:
  5075. current = self.state.temperatures.get("chamber", 0)
  5076. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  5077. respect_local = (time.time() - local_set_time) < 5.0
  5078. if respect_local:
  5079. # Use locally-set target
  5080. target = self.state.temperatures.get("chamber_target", 0)
  5081. else:
  5082. # Use explicit/decoded target from MQTT
  5083. target = self.state.temperatures.get("chamber_target", 0)
  5084. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  5085. self._debug_on_change(
  5086. "chamber_heating",
  5087. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  5088. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  5089. self.serial_number,
  5090. target,
  5091. current,
  5092. self.state.temperatures["chamber_heating"],
  5093. respect_local,
  5094. )
  5095. # Debug: log chamber value if it was updated
  5096. if "chamber" in temps:
  5097. self._debug_on_change(
  5098. "chamber_temp",
  5099. (
  5100. self.state.temperatures.get("chamber"),
  5101. self.state.temperatures.get("chamber_target"),
  5102. self.state.temperatures.get("chamber_heating"),
  5103. ),
  5104. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  5105. self.serial_number,
  5106. self.state.temperatures.get("chamber"),
  5107. self.state.temperatures.get("chamber_target"),
  5108. self.state.temperatures.get("chamber_heating"),
  5109. )
  5110. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  5111. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  5112. if "nozzle" in temps and "nozzle_heating" not in temps:
  5113. current = self.state.temperatures.get("nozzle", 0)
  5114. target = self.state.temperatures.get("nozzle_target", 0)
  5115. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  5116. # Parse HMS (Health Management System) errors
  5117. if "hms" in data:
  5118. hms_list = data["hms"]
  5119. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  5120. # A `print_error` fault is not in `hms[]` and its field only comes
  5121. # when it changes, so a list rebuilt from `hms[]` keeps it (#3487).
  5122. print_error_entries = [e for e in self.state.hms_errors if _is_print_error_entry(e)]
  5123. self.state.hms_errors = []
  5124. verify_failed = False
  5125. if isinstance(hms_list, list):
  5126. for hms in hms_list:
  5127. if isinstance(hms, dict):
  5128. # HMS format: {"attr": attribute_code, "code": error_code}
  5129. # attr contains module/severity info, code contains error number
  5130. # Both are needed to construct the wiki URL
  5131. attr = hms.get("attr", 0)
  5132. code = hms.get("code", 0)
  5133. if isinstance(attr, str):
  5134. attr = int(attr.replace("0x", ""), 16) if attr else 0
  5135. if isinstance(code, str):
  5136. code = int(code.replace("0x", ""), 16) if code else 0
  5137. # attr is module, module no., part, part no. (a byte each);
  5138. # code is the alert level (high 16 bits) then the error
  5139. # (low 16). The level is 1 error (task stopped), 2 warning
  5140. # (task paused), 3 notification; 0 is invalid. This is how
  5141. # Bambu Studio decodes it (DevHMSItem::parse_hms_info). It
  5142. # used to be read from attr bits 8-15, which is the part
  5143. # byte (#2728).
  5144. severity = (code >> 16) & 0xFFFF
  5145. # Module is in attr byte 3 (bits 24-31)
  5146. module = (attr >> 24) & 0xFF
  5147. # Skip non-error status codes. A real fault has a level of
  5148. # at least 1 in the high half, so its code is >= 0x10000
  5149. # and clears this; lower values are status/phase
  5150. # indicators some firmware sends during normal printing.
  5151. if code < 0x4000:
  5152. continue
  5153. # Skip user-action echoes — the printer firmware emits these
  5154. # as part of normal user-cancel sequences. They're not faults
  5155. # and shouldn't count toward "X problem" badges or surface as
  5156. # red pips on the printer card. Backend's notification path
  5157. # already suppresses 0500_400E for the same reason.
  5158. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  5159. if short_code in _HMS_USER_ACTION_CODES:
  5160. continue
  5161. # The full 16-char identifier is the firmware's matching key
  5162. # and the HMS catalogue's key for this kind of fault; the
  5163. # short code discards the part and alert-level groups. The
  5164. # action table still has some short-form entries, so that
  5165. # lookup falls back to it.
  5166. full_code = f"{attr:08X}{code:08X}"
  5167. if full_code == HMS_MQTT_VERIFY_FAILED:
  5168. verify_failed = True
  5169. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  5170. if not actions:
  5171. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5172. self.state.hms_errors.append(
  5173. HMSError(
  5174. code=f"0x{code:x}" if code else "0x0",
  5175. attr=attr,
  5176. module=module,
  5177. # No fallback: 0 is Bambu's "invalid" level, and
  5178. # promoting it would render it as a fault.
  5179. severity=severity,
  5180. actions=actions,
  5181. job_id=self.state.subtask_id,
  5182. full_code=full_code,
  5183. description=describe_fault(full_code, self.serial_number[:3]),
  5184. )
  5185. )
  5186. hms_short_codes = _hms_short_codes(self.state.hms_errors)
  5187. self.state.hms_errors.extend(e for e in print_error_entries if _hms_short_code(e) not in hms_short_codes)
  5188. self._apply_mqtt_verify_state(verify_failed)
  5189. # Parse print_error - this is a different error format than HMS
  5190. # print_error is a 32-bit integer where:
  5191. # - High 16 bits contain module info (e.g., 0x0500)
  5192. # - Low 16 bits contain error code (e.g., 0x8061)
  5193. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  5194. if "print_error" in data:
  5195. print_error = data["print_error"]
  5196. # The field holds the one current fault, and 0 once it is resolved,
  5197. # for example when the filament-load prompt is answered on the
  5198. # printer. The entry of a code that is no longer reported goes
  5199. # (#3487); the entry of the same code is kept as it is.
  5200. self.state.hms_errors = [
  5201. e for e in self.state.hms_errors if not _is_print_error_entry(e) or e.attr == print_error
  5202. ]
  5203. if print_error and print_error != 0:
  5204. # Extract components: MMMMEEEE -> MMMM_EEEE
  5205. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  5206. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  5207. # Values below 0x4000 are status/phase indicators, not real errors.
  5208. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  5209. # Some firmware sends low values like 0x0002 during normal printing.
  5210. if error < 0x4000:
  5211. pass # Skip — not a real error
  5212. else:
  5213. # Store in a format that matches the community error database
  5214. # attr stores the full 32-bit value for reconstruction
  5215. # code stores the short format string for lookup
  5216. short_code = f"{module:04X}_{error:04X}"
  5217. logger.debug(
  5218. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  5219. )
  5220. # Same user-action filter as the hms[] branch above — print_error
  5221. # carries the same cancel echoes (e.g. 0500_400E) and they must
  5222. # not surface as faults on the printer card.
  5223. if short_code in _HMS_USER_ACTION_CODES:
  5224. pass # cancel echo — silently drop
  5225. else:
  5226. # Only add if not already in HMS errors (avoid duplicates)
  5227. if short_code not in _hms_short_codes(self.state.hms_errors):
  5228. # Bambu's HMS catalog keys by 3-letter device code (the SN
  5229. # prefix) and a 16-char short error code without the
  5230. # underscore separator we store internally.
  5231. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5232. # Bambu pushes the current job as `subtask_id` on the
  5233. # state stream; the HMS-action commands echo it back as
  5234. # `job_id`. The error payload itself doesn't carry the
  5235. # id, so snapshot it from the live state at parse time
  5236. # and freeze it on the HMSError so subsequent
  5237. # job changes don't invalidate the action.
  5238. job_id = self.state.subtask_id
  5239. logger.debug(
  5240. "[%s, %s] HMS available actions: %s (job_id=%s)",
  5241. self.serial_number[:3],
  5242. short_code.replace("_", ""),
  5243. actions,
  5244. job_id,
  5245. )
  5246. self.state.hms_errors.append(
  5247. HMSError(
  5248. code=f"0x{error:x}",
  5249. attr=print_error, # Store full value for display
  5250. module=module >> 8, # High byte of module (e.g., 0x05)
  5251. # print_error has no level field; its error
  5252. # number's first digit carries it instead.
  5253. severity=alert_level_from_print_error(error),
  5254. actions=actions,
  5255. job_id=job_id,
  5256. # print_error is already 32-bit — `f"{print_error:08X}"`
  5257. # is the firmware's matching key with no truncation.
  5258. full_code=f"{print_error:08X}",
  5259. description=describe_fault(f"{print_error:08X}", self.serial_number[:3]),
  5260. )
  5261. )
  5262. # Parse home_flag first so SD-card detection below can prefer it.
  5263. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  5264. # bit 23 = door-open (X1 family only).
  5265. home_flag = None
  5266. if "home_flag" in data:
  5267. home_flag = data["home_flag"]
  5268. if home_flag < 0:
  5269. home_flag = home_flag & 0xFFFFFFFF
  5270. # SD card presence: the only remaining consumer is the firmware-update
  5271. # precondition check (firmware_update.py). Use the top-level `sdcard`
  5272. # field when present with a permissive truthy check covering the
  5273. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  5274. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  5275. # when a card is inserted, which caused the badge to flap before the
  5276. # badge was removed entirely.
  5277. if "sdcard" in data:
  5278. raw_sdcard = data["sdcard"]
  5279. if isinstance(raw_sdcard, str):
  5280. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  5281. else:
  5282. self.state.sdcard = bool(raw_sdcard)
  5283. self.state.sdcard_reported = True
  5284. if home_flag is not None:
  5285. store_to_sdcard = bool((home_flag >> 11) & 1)
  5286. if store_to_sdcard != self.state.store_to_sdcard:
  5287. logger.debug(
  5288. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  5289. )
  5290. self.state.store_to_sdcard = store_to_sdcard
  5291. # Door open detection — source depends on printer family:
  5292. # X1 series (X1, X1C, X1E): home_flag bit 23
  5293. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  5294. # Both share the same bitmask (0x00800000) but live in different fields.
  5295. model_upper = (self.model or "").upper().strip()
  5296. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  5297. if is_x1_family and home_flag is not None:
  5298. door_open = (home_flag & 0x00800000) != 0
  5299. if door_open != self.state.door_open:
  5300. logger.debug(
  5301. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  5302. self.serial_number,
  5303. self.state.door_open,
  5304. door_open,
  5305. home_flag,
  5306. )
  5307. self.state.door_open = door_open
  5308. elif not is_x1_family and "stat" in data:
  5309. try:
  5310. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  5311. door_open = (stat_value & 0x00800000) != 0
  5312. if door_open != self.state.door_open:
  5313. logger.debug(
  5314. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  5315. self.serial_number,
  5316. self.state.door_open,
  5317. door_open,
  5318. stat_value,
  5319. )
  5320. self.state.door_open = door_open
  5321. except (ValueError, TypeError):
  5322. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  5323. # Parse timelapse status (recording active during print). Status frames
  5324. # only — the project_file ack echoes back the per-job timelapse flag we
  5325. # asked for, which is a request, not the recorder's state (#3040).
  5326. if "timelapse" in data and is_printer_status_frame(data):
  5327. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  5328. self.state.timelapse = data["timelapse"] is True
  5329. # Track if timelapse was ever active during this print
  5330. if self.state.timelapse and self._was_running:
  5331. self._timelapse_during_print = True
  5332. # Parse ipcam/live view status
  5333. if "ipcam" in data:
  5334. ipcam_data = data["ipcam"]
  5335. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  5336. if isinstance(ipcam_data, dict):
  5337. # Check ipcam_record field for live view status
  5338. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  5339. # Check timelapse field (H2D sends it here, not in xcam)
  5340. if "timelapse" in ipcam_data:
  5341. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  5342. if timelapse_enabled != self.state.timelapse:
  5343. logger.debug(
  5344. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  5345. )
  5346. self.state.timelapse = timelapse_enabled
  5347. # Track if timelapse was ever active during this print
  5348. if self.state.timelapse and self._was_running:
  5349. self._timelapse_during_print = True
  5350. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  5351. else:
  5352. self.state.ipcam = ipcam_data is True
  5353. # Parse WiFi signal strength (dBm)
  5354. if "wifi_signal" in data:
  5355. wifi_signal = data["wifi_signal"]
  5356. self._debug_on_change(
  5357. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  5358. )
  5359. if isinstance(wifi_signal, (int, float)):
  5360. self.state.wifi_signal = int(wifi_signal)
  5361. elif isinstance(wifi_signal, str):
  5362. # Handle string format like "-52dBm"
  5363. try:
  5364. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  5365. except ValueError:
  5366. pass # Ignore unparseable wifi_signal strings; field is non-critical
  5367. # Detect ethernet connection: printers on ethernet with WiFi disabled
  5368. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  5369. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  5370. from backend.app.utils.printer_models import has_ethernet
  5371. if has_ethernet(self.model):
  5372. self.state.wired_network = self.state.wifi_signal == -90
  5373. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5374. if "spd_lvl" in data:
  5375. new_speed = data["spd_lvl"]
  5376. if new_speed != self.state.speed_level:
  5377. logger.debug(
  5378. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  5379. )
  5380. self.state.speed_level = new_speed
  5381. # Parse skipped objects from printer status (s_obj field)
  5382. # This allows us to restore skipped objects state after reconnection
  5383. if "s_obj" in data:
  5384. s_obj = data["s_obj"]
  5385. if isinstance(s_obj, list):
  5386. # Update skipped objects from printer's list
  5387. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  5388. if new_skipped != self.state.skipped_objects:
  5389. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  5390. self.state.skipped_objects = new_skipped
  5391. for oid in new_skipped:
  5392. self._unconfirmed_skips.pop(oid, None)
  5393. self._check_unconfirmed_skips()
  5394. # Parse chamber light status from lights_report
  5395. if "lights_report" in data:
  5396. lights = data["lights_report"]
  5397. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  5398. if isinstance(lights, list):
  5399. for light in lights:
  5400. if isinstance(light, dict) and light.get("node") == "chamber_light":
  5401. new_light_state = light.get("mode") == "on"
  5402. if new_light_state != self.state.chamber_light:
  5403. logger.debug(
  5404. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  5405. )
  5406. self.state.chamber_light = new_light_state
  5407. break
  5408. # Parse nozzle hardware info (single nozzle printers)
  5409. if "nozzle_type" in data:
  5410. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  5411. if "nozzle_diameter" in data:
  5412. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  5413. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  5414. # Left nozzle
  5415. if "left_nozzle_type" in data:
  5416. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  5417. if "left_nozzle_diameter" in data:
  5418. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  5419. # Right nozzle
  5420. if "right_nozzle_type" in data:
  5421. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  5422. if "right_nozzle_diameter" in data:
  5423. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  5424. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  5425. if "nozzle_type_2" in data:
  5426. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  5427. if "nozzle_diameter_2" in data:
  5428. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  5429. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  5430. if "device" in data and isinstance(data["device"], dict):
  5431. device = data["device"]
  5432. nozzle_data = device.get("nozzle", {})
  5433. # H2C rack position (#2800). `tar_id` is where the carriage is
  5434. # headed, `src_id` where it came from; mid-swap they differ, so
  5435. # dispatch prefers tar_id and falls back to src_id. Both are
  5436. # sticky — the field is only pushed when it changes, so an
  5437. # absent key must leave the last known value alone rather than
  5438. # reset it to None.
  5439. if isinstance(nozzle_data, dict):
  5440. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  5441. if key not in nozzle_data:
  5442. continue
  5443. try:
  5444. parsed_id = int(nozzle_data[key])
  5445. except (TypeError, ValueError):
  5446. continue
  5447. if getattr(self.state, attr) != parsed_id:
  5448. setattr(self.state, attr, parsed_id)
  5449. # DEBUG, not INFO: these move on every tool change, so
  5450. # a long multi-material print would otherwise write
  5451. # thousands of lines. The dispatch log records both
  5452. # values once per print, which is where triage needs
  5453. # them. Same reasoning as the one-shot `nozzle_info`
  5454. # log below.
  5455. logger.debug(
  5456. "[%s] Nozzle rack %s -> %s",
  5457. self.serial_number,
  5458. key,
  5459. parsed_id,
  5460. )
  5461. nozzle_info = nozzle_data.get("info", [])
  5462. if isinstance(nozzle_info, list):
  5463. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  5464. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  5465. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  5466. # for hover cards on both the L/R indicator and the nozzle rack card.
  5467. if nozzle_info:
  5468. self.state.nozzle_rack = sorted(
  5469. [
  5470. {
  5471. "id": n.get("id", i),
  5472. "type": str(n.get("type", "")),
  5473. "diameter": str(n.get("diameter", "")),
  5474. "wear": n.get("wear"),
  5475. "stat": n.get("stat"),
  5476. # H2C uses "tm", H2D uses "max_temp"
  5477. "max_temp": n.get("max_temp") or n.get("tm", 0),
  5478. # H2C uses "sn", H2D uses "serial_number"
  5479. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  5480. # H2C uses "color_m", H2D uses "filament_colour"
  5481. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  5482. # H2C uses "fila_id", H2D uses "filament_id"
  5483. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  5484. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  5485. # H3C: home rack position 0-8 (the mounted hotend reports id 0)
  5486. "addr_id": n.get("addr_id") if isinstance(n.get("addr_id"), int) else None,
  5487. }
  5488. for i, n in enumerate(nozzle_info)
  5489. ],
  5490. key=lambda x: x["id"],
  5491. )
  5492. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  5493. self._nozzle_rack_logged = True
  5494. logger.debug(
  5495. "[%s] Nozzle info: %d entries, IDs: %s",
  5496. self.serial_number,
  5497. len(nozzle_info),
  5498. [n.get("id") for n in nozzle_info],
  5499. )
  5500. for nozzle in nozzle_info:
  5501. idx = nozzle.get("id", 0)
  5502. if idx < len(self.state.nozzles):
  5503. if "type" in nozzle and nozzle["type"]:
  5504. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  5505. if "diameter" in nozzle:
  5506. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  5507. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  5508. # (these fields aren't sent in every MQTT push, only when changed)
  5509. ams_data = self.state.raw_data.get("ams")
  5510. vt_tray_data = self.state.raw_data.get("vt_tray")
  5511. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  5512. mapping_data = self.state.raw_data.get("mapping")
  5513. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  5514. # as a dict but consumers expect a list. Without this, the dev mode probe
  5515. # below can release the GIL (via publish), letting the event-loop thread
  5516. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  5517. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  5518. data["vt_tray"] = [data["vt_tray"]]
  5519. self.state.raw_data = data
  5520. # Restore preserved fields BEFORE any work that may release the GIL
  5521. # (e.g. _probe_developer_mode publishes an MQTT message).
  5522. if ams_data is not None:
  5523. self.state.raw_data["ams"] = ams_data
  5524. elif not isinstance(self.state.raw_data.get("ams"), list):
  5525. # #3499: no unit list yet (the AMS handling failed on this frame).
  5526. # The frame's AMS object is not one; readers iterate it as units.
  5527. self.state.raw_data.pop("ams", None)
  5528. if vt_tray_data is not None:
  5529. self.state.raw_data["vt_tray"] = vt_tray_data
  5530. if ams_extruder_map_data is not None:
  5531. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  5532. if mapping_data is not None and "mapping" not in data:
  5533. self.state.raw_data["mapping"] = mapping_data
  5534. # Parse developer LAN mode from "fun" field
  5535. if "fun" in data:
  5536. try:
  5537. fun_val = data["fun"]
  5538. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  5539. self.state.developer_mode = (fun_int & 0x20000000) == 0
  5540. except (ValueError, TypeError):
  5541. pass
  5542. elif self.state.developer_mode is None and not self._dev_mode_probed:
  5543. # No "fun" field — A1/P1 series never send it, so we need to probe.
  5544. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  5545. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  5546. # after connect to let the MQTT session stabilize — probing too early
  5547. # can destabilize some firmware MQTT brokers (#887).
  5548. if not self._dev_mode_needs_probe and len(data) > 30:
  5549. # First full status without "fun" — mark that probe is needed
  5550. self._dev_mode_needs_probe = True
  5551. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  5552. self._probe_developer_mode()
  5553. elif self._dev_mode_needs_probe:
  5554. logger.debug(
  5555. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  5556. self.serial_number,
  5557. time.monotonic() - self._connect_time,
  5558. )
  5559. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  5560. # Probe was sent but no response yet — check for timeout.
  5561. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  5562. # may deliver status pushes but silently drop commands (#887).
  5563. elapsed = time.monotonic() - self._dev_mode_probe_time
  5564. if elapsed > 10.0:
  5565. self._dev_mode_probe_failures += 1
  5566. logger.warning(
  5567. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  5568. self.serial_number,
  5569. elapsed,
  5570. self._dev_mode_probe_failures,
  5571. )
  5572. self._dev_mode_probe_seq = None
  5573. if self._dev_mode_probe_failures >= 2:
  5574. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  5575. else:
  5576. # Allow retry on next full status message
  5577. self._dev_mode_probed = False
  5578. # Zombie session detection: if an ams_filament_setting command has been
  5579. # pending for >10s with no response, the publish path is likely dead (#887).
  5580. if self._last_ams_cmd_time > 0:
  5581. elapsed = time.monotonic() - self._last_ams_cmd_time
  5582. if elapsed > 10.0:
  5583. self._ams_cmd_unanswered += 1
  5584. logger.warning(
  5585. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  5586. self.serial_number,
  5587. elapsed,
  5588. self._ams_cmd_unanswered,
  5589. )
  5590. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  5591. if self._ams_cmd_unanswered >= 2:
  5592. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  5593. self._ams_cmd_unanswered = 0
  5594. # Log mapping data when received (for usage tracking debugging)
  5595. if "mapping" in data:
  5596. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  5597. # Log state transitions for debugging
  5598. if "gcode_state" in data:
  5599. logger.debug(
  5600. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  5601. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  5602. )
  5603. # Detect print start (state changes TO RUNNING with a file)
  5604. current_file = self.state.gcode_file or self.state.current_print
  5605. if self._previous_gcode_state is None and self.state.state == "PAUSE" and current_file:
  5606. self._paused_at_startup = True
  5607. is_new_print = (
  5608. self.state.state == "RUNNING"
  5609. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  5610. and self._previous_gcode_state != "RUNNING"
  5611. and current_file
  5612. and not self._was_running # Prevent duplicates when resuming from PAUSE
  5613. # #3485: a print paused when Bambuddy started resumes like one it
  5614. # found running (#1304): restart recovery below, not a new print.
  5615. and not (self._paused_at_startup and self._previous_gcode_state == "PAUSE")
  5616. )
  5617. if self.state.state != "PAUSE":
  5618. self._paused_at_startup = False
  5619. # Also detect if file changed while running (new print started)
  5620. is_file_change = (
  5621. self.state.state == "RUNNING"
  5622. and current_file
  5623. and current_file != self._previous_gcode_file
  5624. and self._previous_gcode_file is not None
  5625. )
  5626. # Track RUNNING state for more robust completion detection
  5627. running_first_observed = False
  5628. if self.state.state == "RUNNING" and current_file:
  5629. if not self._was_running:
  5630. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  5631. # Check if timelapse was enabled in the same message (xcam parsed before this)
  5632. if self.state.timelapse:
  5633. self._timelapse_during_print = True
  5634. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  5635. # Mark this as the first RUNNING observation of the session.
  5636. # If is_new_print also fires below, on_print_start handles
  5637. # baseline capture and we suppress on_print_running_observed
  5638. # to avoid double-capture. If is_new_print does NOT fire
  5639. # (Bambuddy started mid-print — the #1304 guard suppressed
  5640. # it), main.py needs this hook to catch the restart-recovery
  5641. # case (#1485 follow-up).
  5642. running_first_observed = True
  5643. self._was_running = True
  5644. self._completion_triggered = False
  5645. if is_new_print or is_file_change:
  5646. # Clear any old HMS errors when a new print starts
  5647. self.state.hms_errors = []
  5648. # The last print's pauses; this one's come from its 3MF (#2984).
  5649. self.state.pause_points = []
  5650. self.state.pause_warned_layers = set()
  5651. # Reset layer tracking for new print (needed for layer-based timelapse)
  5652. # #3317: only above 1. Every print reports layer 1 first, which
  5653. # clears a higher value; a previous print that ended on layer 1
  5654. # would make this print's own first layer look stale.
  5655. self._stale_layer_num = self.state.layer_num if self.state.layer_num > 1 else 0
  5656. self.state.layer_num = 0
  5657. # Reset total_layers so the previous print's value can't bleed into
  5658. # this print's usage-tracker split (#1771 follow-on to the
  5659. # preservation guard at the `total_layer_num` parse above — that
  5660. # guard ignores firmware-reset 0s, so the explicit reset has to
  5661. # happen here instead).
  5662. #
  5663. # #2702: reset to *this frame's* total, not to 0. The frame that
  5664. # trips the new-print detection can carry the new print's
  5665. # `total_layer_num` as well — the parse above has already applied
  5666. # it, and zeroing unconditionally threw it away. That looked
  5667. # harmless but is not recoverable: Bambu firmware sends only
  5668. # changed fields, so the printer never offers the total again, and
  5669. # the print runs to completion at `n/0` in the UI, in
  5670. # `{total_layers}` notifications, and as the usage-split
  5671. # denominator. The value only reappears on the next full pushall
  5672. # (reconnect / Force Refresh), which is why the symptom looked
  5673. # random and why a *stable* connection made it worse.
  5674. self.state.total_layers = total_from_this_frame
  5675. # If the starting frame brought no total, ask for one. Costs one
  5676. # MQTT message per print and covers the ordering where the printer
  5677. # published the total a frame or two before the state flip.
  5678. self._total_layers_refresh_armed = not total_from_this_frame
  5679. if self._total_layers_refresh_armed:
  5680. self._request_push_all()
  5681. # Reset completion tracking for new print
  5682. self._was_running = True
  5683. self._completion_triggered = False
  5684. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5685. self._finish_photo_captured = False
  5686. # #2547: rearm the end-of-print telemetry probe for the new print
  5687. self._eop_probe_armed = True
  5688. self._eop_probe_open = False
  5689. self._eop_probe_frames = 0
  5690. self._eop_probe_last = {}
  5691. # Reset last valid progress/layer for usage tracking
  5692. self._last_valid_progress = 0.0
  5693. self._last_valid_layer_num = 0
  5694. # Clear and seed tray change log for mid-print usage splitting
  5695. self.state.tray_change_log.clear()
  5696. # Seeded with the assigned spools by usage_tracker.on_print_start.
  5697. self.state.spool_change_log = []
  5698. tn = self.state.tray_now
  5699. if self.tray_layout.is_loaded_tray(tn):
  5700. self.state.tray_change_log.append((tn, 0))
  5701. # Initialize timelapse tracking based on current state
  5702. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5703. # so self.state.timelapse may already be set from this message.
  5704. # We preserve that value instead of blindly resetting to False.
  5705. if self.state.timelapse:
  5706. self._timelapse_during_print = True
  5707. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5708. else:
  5709. self._timelapse_during_print = False
  5710. if (is_new_print or is_file_change) and self.on_print_start:
  5711. logger.info(
  5712. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5713. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5714. )
  5715. self.on_print_start(
  5716. {
  5717. "filename": current_file,
  5718. "subtask_name": self.state.subtask_name,
  5719. "remaining_time": self.state.remaining_time * 60
  5720. if self.state.remaining_time > 0
  5721. else None, # Convert minutes to seconds
  5722. "raw_data": data,
  5723. "ams_mapping": self._captured_ams_mapping,
  5724. }
  5725. )
  5726. elif running_first_observed and self.on_print_running_observed:
  5727. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5728. # print, so the #1304 first-push guard suppressed on_print_start,
  5729. # but we still need main.py to capture a fresh timelapse baseline
  5730. # before the printer uploads the in-flight MP4. Same payload
  5731. # shape as on_print_start so the consumer can reuse fields.
  5732. logger.info(
  5733. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5734. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5735. )
  5736. self.on_print_running_observed(
  5737. {
  5738. "filename": current_file,
  5739. "subtask_name": self.state.subtask_name,
  5740. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5741. "raw_data": data,
  5742. "ams_mapping": self._captured_ams_mapping,
  5743. }
  5744. )
  5745. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5746. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5747. # This handles cases where server restarts during a print
  5748. should_trigger_completion = (
  5749. self.state.state in ("FINISH", "FAILED")
  5750. and not self._completion_triggered
  5751. and self.on_print_complete
  5752. and (
  5753. self._previous_gcode_state == "RUNNING" # Normal transition
  5754. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5755. # Pre-print failure (#1111): printer rejected the job during setup
  5756. # — wrong nozzle size, AMS error, etc. The print never reaches
  5757. # RUNNING, so without this branch neither the RUNNING check nor
  5758. # _was_running match and the queue item stays stuck at "printing".
  5759. # Restricted to FAILED from pre-print states so a stale FAILED on
  5760. # first connection (prev=None) still can't accidentally fire.
  5761. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5762. )
  5763. )
  5764. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5765. if (
  5766. self.state.state == "IDLE"
  5767. and self._previous_gcode_state == "RUNNING"
  5768. and not self._completion_triggered
  5769. and self.on_print_complete
  5770. ):
  5771. should_trigger_completion = True
  5772. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5773. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5774. if (
  5775. not should_trigger_completion
  5776. and self.state.state in ("FINISH", "FAILED")
  5777. and self._previous_gcode_state != self.state.state
  5778. ):
  5779. logger.info(
  5780. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5781. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5782. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5783. )
  5784. # Mark as triggered so state is clean for the next print cycle
  5785. self._completion_triggered = True
  5786. if should_trigger_completion:
  5787. if self.state.state == "FINISH":
  5788. status = "completed"
  5789. elif self.state.state == "FAILED":
  5790. status = "failed"
  5791. else:
  5792. status = "aborted"
  5793. logger.info(
  5794. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5795. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5796. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5797. f"timelapse_during_print: {self._timelapse_during_print}"
  5798. )
  5799. timelapse_was_active = self._timelapse_during_print
  5800. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5801. # external-spool-only, HMS halt, or firmware variant that skips
  5802. # the unload phase) fire the finish-photo moment now. Bed has
  5803. # already dropped, framing is worse, but we still capture.
  5804. # Only on successful completion — aborted/failed prints don't
  5805. # produce a meaningful finish photo.
  5806. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5807. self._finish_photo_captured = True
  5808. logger.info(
  5809. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5810. f"stage-22 never fired; capturing at FINISH-state transition"
  5811. )
  5812. self.on_finish_photo_moment(
  5813. {
  5814. "trigger": "finish_state",
  5815. "filename": self._previous_gcode_file or current_file,
  5816. "subtask_name": self.state.subtask_name,
  5817. "timelapse_was_active": timelapse_was_active,
  5818. }
  5819. )
  5820. self._completion_triggered = True
  5821. self._was_running = False
  5822. self._timelapse_during_print = False # Reset for next print
  5823. # Include HMS errors for failure reason detection
  5824. hms_errors_data = [e.completion_payload() for e in self.state.hms_errors or []]
  5825. from backend.app.utils.printer_models import usage_progress
  5826. last_progress = usage_progress(
  5827. self.model, self._last_valid_progress, self._last_valid_layer_num, self.state.total_layers
  5828. )
  5829. self.on_print_complete(
  5830. {
  5831. "status": status,
  5832. "subtask_id": self.state.subtask_id,
  5833. "filename": self._previous_gcode_file or current_file,
  5834. "subtask_name": self.state.subtask_name,
  5835. "raw_data": data,
  5836. "timelapse_was_active": timelapse_was_active,
  5837. "hms_errors": hms_errors_data,
  5838. "ams_mapping": self._captured_ams_mapping,
  5839. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5840. "last_progress": last_progress,
  5841. "last_layer_num": self._last_valid_layer_num,
  5842. }
  5843. )
  5844. self._captured_ams_mapping = None
  5845. # Same lifecycle as the mapping above: it described *this* print.
  5846. # Leaving it set would hand the next print an answer about where a
  5847. # different file went, and a stale "internal storage" reading costs
  5848. # an archive that the FTPS sweep would have found (#2780).
  5849. self.state.current_project_url = None
  5850. self._previous_gcode_state = self.state.state
  5851. if current_file:
  5852. self._previous_gcode_file = current_file
  5853. if self.on_state_change:
  5854. self.on_state_change(self.state)
  5855. def _request_push_all(self):
  5856. """Request full status update from printer."""
  5857. if self._client:
  5858. message = {"pushing": {"command": "pushall"}}
  5859. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5860. def _probe_developer_mode(self):
  5861. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5862. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5863. For these, we detect developer mode by sending a harmless command and
  5864. checking whether the printer accepts or rejects it:
  5865. - result="success" → developer mode ON (commands accepted)
  5866. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5867. The probe re-sends the current external slot configuration so it's a no-op
  5868. when the command succeeds. If there's no external slot data yet, we send a
  5869. reset (empty filament) which is also safe.
  5870. """
  5871. if not self._client or not self.state.connected:
  5872. return
  5873. self._dev_mode_probed = True
  5874. self._dev_mode_probe_time = time.monotonic()
  5875. self._sequence_id += 1
  5876. seq = str(self._sequence_id)
  5877. self._dev_mode_probe_seq = seq
  5878. # Build probe command: re-send current external slot config (no-op on success)
  5879. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5880. current = vt_tray[0] if vt_tray else {}
  5881. command = {
  5882. "print": {
  5883. "command": "ams_filament_setting",
  5884. "ams_id": 255,
  5885. "tray_id": 0,
  5886. "slot_id": 0,
  5887. "tray_info_idx": current.get("tray_info_idx", ""),
  5888. "tray_type": current.get("tray_type", ""),
  5889. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5890. "tray_color": current.get("tray_color", "00000000"),
  5891. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5892. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5893. "sequence_id": seq,
  5894. }
  5895. }
  5896. setting_id = current.get("setting_id")
  5897. if setting_id:
  5898. command["print"]["setting_id"] = setting_id
  5899. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5900. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5901. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5902. """Reconcile developer_mode with the printer's own command-verification verdict.
  5903. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5904. control commands are being refused, so it outranks the probe in both
  5905. directions:
  5906. * present → developer_mode is definitively False, whatever the probe
  5907. concluded. The probe can only read the response to its own
  5908. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5909. instead, so the probe answers ENABLED while every print silently dies
  5910. (#2732).
  5911. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5912. probe, so a user who enables Developer Mode and restarts the printer
  5913. isn't stuck behind a verdict nothing would ever revisit.
  5914. A False that came from the probe or the ``fun`` bit is left alone — this
  5915. only ever unwinds its own latch.
  5916. """
  5917. if verify_failed:
  5918. if not self._dev_mode_from_hms:
  5919. logger.warning(
  5920. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5921. "rejecting control commands, so prints, temperature changes and filament "
  5922. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5923. self.serial_number,
  5924. HMS_MQTT_VERIFY_FAILED,
  5925. )
  5926. self._dev_mode_from_hms = True
  5927. self.state.developer_mode = False
  5928. return
  5929. if not self._dev_mode_from_hms:
  5930. return
  5931. logger.info(
  5932. "[%s] HMS %s cleared — re-probing developer mode",
  5933. self.serial_number,
  5934. HMS_MQTT_VERIFY_FAILED,
  5935. )
  5936. self._dev_mode_from_hms = False
  5937. self.state.developer_mode = None
  5938. self._dev_mode_probed = False
  5939. self._dev_mode_needs_probe = False
  5940. def _handle_dev_mode_probe_response(self, data: dict):
  5941. """Handle response to the developer mode probe command.
  5942. Sets developer_mode based on whether the printer accepted or rejected the command.
  5943. Three outcomes, not two. An explicit ``success`` proves commands are
  5944. accepted and an explicit verify-failure proves they are not, but anything
  5945. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5946. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5947. ``result`` at all, while refusing every control command and reporting
  5948. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5949. is what put ``developer_mode: pass`` in the support bundle of a printer
  5950. that had not accepted a command all day (#2732). Leaving it unknown makes
  5951. the connection diagnostic report ``skip``, which is the honest answer.
  5952. """
  5953. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5954. self._dev_mode_probe_failures = 0 # Reset on any response
  5955. result = data.get("result", "")
  5956. reason = data.get("reason", "")
  5957. if result == "failed" and "verify failed" in reason:
  5958. self.state.developer_mode = False
  5959. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5960. elif str(result).lower() == "success":
  5961. self.state.developer_mode = True
  5962. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5963. else:
  5964. # An HMS verdict already recorded here is real evidence; don't let an
  5965. # inconclusive probe response wipe it back to unknown.
  5966. if not self._dev_mode_from_hms:
  5967. self.state.developer_mode = None
  5968. logger.info(
  5969. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5970. "the printer neither confirmed nor refused the command",
  5971. self.serial_number,
  5972. result,
  5973. reason,
  5974. )
  5975. if self.on_state_change:
  5976. self.on_state_change(self.state)
  5977. def _request_version(self):
  5978. """Request firmware version info from printer."""
  5979. if self._client:
  5980. self._sequence_id += 1
  5981. message = {
  5982. "info": {
  5983. "sequence_id": str(self._sequence_id),
  5984. "command": "get_version",
  5985. }
  5986. }
  5987. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5988. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5989. def request_status_update(self) -> bool:
  5990. """Request a full status update from the printer (public API).
  5991. Sends both pushall and get_accessories commands to refresh all data
  5992. including nozzle hardware info.
  5993. Returns:
  5994. True if the request was sent, False if not connected.
  5995. """
  5996. if not self._client or not self.state.connected:
  5997. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5998. return False
  5999. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  6000. self._request_push_all()
  6001. # Note: get_accessories returns stale nozzle data on H2D.
  6002. # The correct nozzle data comes from push_status response.
  6003. return True
  6004. def _prime_kprofile_request(self):
  6005. """Send a priming K-profile request on connect.
  6006. Bambu printers often ignore the first K-profile request after connection,
  6007. so we send a dummy request on connect to 'prime' the system.
  6008. """
  6009. if self._client:
  6010. self._sequence_id += 1
  6011. command = {
  6012. "print": {
  6013. "command": "extrusion_cali_get",
  6014. "filament_id": "",
  6015. "nozzle_diameter": "0.4",
  6016. "sequence_id": str(self._sequence_id),
  6017. }
  6018. }
  6019. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  6020. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6021. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  6022. """Connect to the printer MQTT broker.
  6023. Args:
  6024. loop: The asyncio event loop to use for thread-safe callbacks.
  6025. If not provided, will try to get the running loop.
  6026. """
  6027. self._loop = loop
  6028. BambuMQTTClient._client_instance_counter += 1
  6029. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  6030. self._client = mqtt.Client(
  6031. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  6032. client_id=client_id,
  6033. protocol=mqtt.MQTTv311,
  6034. )
  6035. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  6036. # tracking (#1164). The default ceiling of 20 wedges sessions after
  6037. # ~16-20 cumulative commands; lifting it well above any realistic
  6038. # session count keeps QoS=1 working without changing wire-protocol
  6039. # behaviour across printer models.
  6040. self._client.max_inflight_messages_set(1000)
  6041. self._client.username_pw_set("bblp", self.access_code)
  6042. self._client.on_connect = self._on_connect
  6043. self._client.on_disconnect = self._on_disconnect
  6044. self._client.on_subscribe = self._on_subscribe
  6045. self._client.on_message = self._on_message
  6046. # TLS setup - Bambu uses self-signed certs
  6047. ssl_context = ssl.create_default_context()
  6048. ssl_context.check_hostname = False
  6049. ssl_context.verify_mode = ssl.CERT_NONE
  6050. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  6051. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  6052. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  6053. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  6054. # bare-metal installs whose build allows TLS 1.0.
  6055. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  6056. self._client.tls_set_context(ssl_context)
  6057. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  6058. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  6059. # Keepalive: paho sends PINGREQs at this interval, broker considers
  6060. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  6061. # real network loss (45s), not so aggressive that transient hiccups
  6062. # trigger false disconnects. Stale detection (60s no messages) handles
  6063. # the P1S/P1P firmware bug where the broker stops publishing but the
  6064. # TCP connection stays alive.
  6065. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  6066. self._client.loop_start()
  6067. def start_print(
  6068. self,
  6069. filename: str,
  6070. plate_id: int = 1,
  6071. ams_mapping: list[int] | None = None,
  6072. bed_levelling: str = "auto",
  6073. flow_cali: str = "auto",
  6074. vibration_cali: bool = True,
  6075. layer_inspect: bool = False,
  6076. timelapse: bool = False,
  6077. use_ams: bool = True,
  6078. nozzle_offset_cali: str = "auto",
  6079. nozzle_mapping: str | None = None,
  6080. nozzle_slot_extruders: str | None = None,
  6081. plate_uses_only_external: bool = False,
  6082. ):
  6083. """Start a print job on the printer.
  6084. The file should already be uploaded to the printer's root directory via FTP.
  6085. Args:
  6086. filename: Name of the uploaded file
  6087. plate_id: Plate number to print (default 1)
  6088. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  6089. Global tray ID = (ams_id * 4) + slot_id, external = 254
  6090. timelapse: Record timelapse video
  6091. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  6092. if the bed was levelled recently, matching BambuStudio).
  6093. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  6094. vibration_cali: Vibration compensation calibration
  6095. layer_inspect: First layer AI inspection
  6096. use_ams: Use AMS for automatic filament changes
  6097. plate_uses_only_external: The caller determined from the plate's
  6098. own filament list that it prints only from the spool holder;
  6099. use_ams=False then stands even if the mapping names a real
  6100. tray (one another plate of the file uses, #3087)
  6101. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  6102. (dual-nozzle printers only — silently ignored on single-nozzle).
  6103. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  6104. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  6105. AND the printer is dual-nozzle, parsed and injected as the
  6106. `nozzle_mapping` array on the dispatched project_file so the
  6107. firmware honours the user's slicer pick instead of falling
  6108. back to "last matching nozzle" auto-pick. Silently ignored
  6109. on single-nozzle printers.
  6110. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  6111. MQTT extruder indices, derived from the 3MF when no
  6112. BambuStudio capture exists (#2800). Consulted only on
  6113. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  6114. not already supply one; resolved here into physical rack
  6115. positions using the live `device.nozzle` state. When it
  6116. cannot be resolved the field is omitted and the firmware
  6117. picks, as it did before this existed.
  6118. Returns True when the start command was published, False otherwise
  6119. (not connected, or the printer is already busy — see the run-state
  6120. guard below).
  6121. """
  6122. # Never dispatch project_file to a printer that is not idle (#2598).
  6123. # This is the single publish choke point for every dispatch path — the
  6124. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  6125. # forwarded job all funnel through here — so one guard covers them all.
  6126. # The firmware rejects a start while busy with 0500_4004 ("Device is
  6127. # busy and cannot start a new task"), and on an A1 mini that error
  6128. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  6129. # start targets; only the active-print states are refused. (A
  6130. # transport-level QoS-1 replay on reconnect would bypass this guard;
  6131. # _on_connect empties paho's outbox before it can re-send (#3454).)
  6132. if self.state.state in _ACTIVE_PRINT_STATES:
  6133. logger.warning(
  6134. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  6135. self.serial_number,
  6136. self.state.state,
  6137. filename,
  6138. )
  6139. return False
  6140. if self._client and self.state.connected:
  6141. # Bambu print command format — matches Bambu Studio's format.
  6142. # The calibration/leveling fields (timelapse, bed_leveling,
  6143. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  6144. # every model. An earlier revision integer-encoded them for the H2
  6145. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  6146. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  6147. # sends plain booleans, and the integer encoding made the H2S
  6148. # silently skip flow-dynamics calibration (#1478). use_ams is the
  6149. # one field that genuinely must stay boolean: H2D Pro firmware
  6150. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  6151. # what actually caused the wrong-extruder routing behind #1386.
  6152. # Dual-nozzle routing for external spool (254 = deputy/left,
  6153. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  6154. # H2 firmware family but is single-nozzle, despite sharing serial
  6155. # prefix "094" with H2D. Prefer runtime detection from
  6156. # device.extruder.info (set in _handle_push_status); fall back to
  6157. # model name for the brief window after connect before push data
  6158. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  6159. # as the primary signal.
  6160. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  6161. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6162. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  6163. ams_mapping2 = []
  6164. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  6165. # ams_mapping and relies on ams_mapping2 for external spool details.
  6166. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  6167. # with 0700_8012 "Failed to get AMS mapping table".
  6168. flat_ams_mapping = []
  6169. layout = self.tray_layout
  6170. if ams_mapping is not None:
  6171. for tray_id in ams_mapping:
  6172. # Ensure tray_id is an integer (may be string from JSON)
  6173. tray_id = int(tray_id) if tray_id is not None else -1
  6174. rack_slot = layout.rack_slot(tray_id) if tray_id >= 0 else None
  6175. if tray_id == -1:
  6176. # Unmapped filament slot
  6177. flat_ams_mapping.append(-1)
  6178. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  6179. elif layout.rack and layout.is_external(tray_id):
  6180. # A rack printer's per-hotend input 247-255, as Studio
  6181. # sends it: -1 flat, its own id in ams_mapping2.
  6182. flat_ams_mapping.append(-1)
  6183. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6184. elif rack_slot is not None:
  6185. # Rack AMS slot, as Studio sends it: 28 + k flat,
  6186. # {ams_id: 32, slot_id: k} in ams_mapping2.
  6187. flat_ams_mapping.append(tray_id)
  6188. ams_mapping2.append({"ams_id": rack_slot[0], "slot_id": rack_slot[1]})
  6189. elif tray_id >= 254:
  6190. # External/virtual spool. BambuStudio convention:
  6191. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  6192. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  6193. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  6194. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  6195. # for external spool, but BambuStudio always sends ams_id=255
  6196. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  6197. # firmware to target AMS tray 0 instead of external spool, leading
  6198. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  6199. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  6200. flat_ams_mapping.append(-1)
  6201. ext_ams_id = tray_id if is_dual_nozzle else 255
  6202. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  6203. elif tray_id >= 128:
  6204. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  6205. flat_ams_mapping.append(tray_id)
  6206. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6207. elif (_a2l := a2l_lite_wire_ids(layout.slot_key(tray_id)[0], tray_id)) is not None:
  6208. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  6209. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  6210. # — both CONFIRMED against the firmware's own mapping
  6211. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  6212. _wire_ams, _wire_slot, _ = _a2l
  6213. flat_ams_mapping.append(_wire_slot)
  6214. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  6215. else:
  6216. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  6217. ams_id, slot_id = layout.slot_key(tray_id)
  6218. flat_ams_mapping.append(tray_id)
  6219. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  6220. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  6221. # printers — the mapping is authoritative about whether this print
  6222. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  6223. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  6224. # H2S falls through here now (#1386): it is single-nozzle and was
  6225. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  6226. # without an AMS attached.
  6227. #
  6228. # Two symmetric corrections:
  6229. #
  6230. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  6231. # use_ams=True even if it arrived False. A print sent to a Virtual
  6232. # Printer is sliced against the VP, which advertises no AMS, so the
  6233. # slicer sends use_ams=false and that gets stamped on the queue item
  6234. # — but at dispatch the scheduler colour-matches a real printer and
  6235. # resolves a real AMS slot. Without this, the stale False reaches the
  6236. # printer, which ignores the mapped slot and aborts at layer 0 on the
  6237. # empty external spool ("not enough filament"). Diagnosed by
  6238. # @Sawtaytoes (#2595, PR #2596).
  6239. #
  6240. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  6241. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  6242. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  6243. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  6244. # status-load race that persisted [-1] (#2589) — and treating it as
  6245. # external silently started the print against an empty feed. A genuine
  6246. # external selection is >=254; unresolved is -1; a loaded tray is
  6247. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  6248. # (or is recomputed upstream) instead of silently going external, and
  6249. # never gets force-enabled by (a) either.
  6250. if ams_mapping and not is_dual_nozzle:
  6251. has_real_tray = any(
  6252. t is not None and 0 <= int(t) <= 253 and not layout.is_external(int(t)) for t in ams_mapping
  6253. )
  6254. all_external = all(t is None or int(t) >= 254 or layout.is_external(int(t)) for t in ams_mapping)
  6255. # (Not when the scheduler worked out from the plate's own
  6256. # filament list that it prints only from the spool holder: a
  6257. # real tray here is then one another plate of the file uses.)
  6258. if has_real_tray and not use_ams and not plate_uses_only_external:
  6259. use_ams = True
  6260. logger.info(
  6261. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  6262. self.serial_number,
  6263. )
  6264. elif use_ams and all_external:
  6265. use_ams = False
  6266. logger.info(
  6267. "[%s] All filament slots use external spool — setting use_ams=False",
  6268. self.serial_number,
  6269. )
  6270. # (c) A single-nozzle printer that reported no AMS at all can only
  6271. # print from the spool holder, whatever the mapping says. With
  6272. # nothing set on the holder the matcher resolves no mapping, so
  6273. # neither (a) nor (b) ran and the print went out as use_ams=True,
  6274. # which the firmware refuses with 07FF_8012 "Failed to get AMS
  6275. # mapping table" (#3356). An empty raw_data["ams"] is the
  6276. # printer's own report of no AMS; a missing key means no AMS
  6277. # push has been handled yet (a reconnect), which changes nothing.
  6278. if use_ams and not is_dual_nozzle and self.state.raw_data.get("ams") == []:
  6279. use_ams = False
  6280. logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
  6281. # Unique per-submission identity fields. Hardcoded "0" values caused
  6282. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  6283. # continuations of the same job: the printer reuses gcode_start_time
  6284. # from the prior print with task_id=0, so observers latch onto a stale
  6285. # timestamp and report compounding durations on repeat replays (#1011).
  6286. # BambuStudio mints fresh IDs per submission; matching that behavior
  6287. # makes the printer emit a clean state-transition for each job.
  6288. # md5 is left empty — firmware historically accepts "" as "skip
  6289. # validation" (unlike Studio, we don't have the file's real md5 here
  6290. # without re-reading the upload, and sending a synthetic wrong digest
  6291. # risks activation of md5 verification on some firmwares).
  6292. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  6293. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  6294. # overflows and every submission ends up with the same task_id from
  6295. # the printer's perspective — the printer then treats a fresh dispatch
  6296. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  6297. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  6298. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  6299. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  6300. # Remember it so on_print_start can persist a restart-stable id on
  6301. # the archive even before the printer echoes subtask_id back (#1485).
  6302. self.last_dispatch_subtask_id = submission_id
  6303. self.last_start_refusal = None
  6304. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  6305. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  6306. # only if it wasn't done recently). The paired bool field is true
  6307. # only for the explicit "on" state — for "auto" the bool is false and
  6308. # the int carries the intent, exactly as BambuStudio's SelectMachine
  6309. # sends it. Unknown values fall back to auto.
  6310. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  6311. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  6312. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  6313. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  6314. command = {
  6315. "print": {
  6316. "sequence_id": "20000",
  6317. "command": "project_file",
  6318. "param": f"Metadata/plate_{plate_id}.gcode",
  6319. "url": f"ftp://{filename}",
  6320. "file": filename,
  6321. "md5": "",
  6322. "bed_type": "auto",
  6323. "timelapse": timelapse,
  6324. # bed_leveling stays a JSON bool (true only for "on") and
  6325. # auto_bed_leveling carries the tri-state int — the exact
  6326. # two-field shape BambuStudio sends. The int must stay a plain
  6327. # number, never quoted (#1478 boolean-family concern applies to
  6328. # the *_cali bools, not these companion ints).
  6329. "bed_leveling": bed_levelling == "on",
  6330. "auto_bed_leveling": bed_level_int,
  6331. "flow_cali": flow_cali == "on",
  6332. "vibration_cali": vibration_cali,
  6333. "layer_inspect": layer_inspect,
  6334. "use_ams": use_ams,
  6335. # No "cfg": it is the printer's device-config bitmask
  6336. # (auto-refill, detect-on-insert, chamber light, ...), not a
  6337. # per-job field — BambuStudio's PrintParams has no such
  6338. # member. We used to send "0"; firmware ignores it, but it
  6339. # comes straight back in the project_file ack (#3040).
  6340. # extrude_cali_flag gates flow-dynamics calibration:
  6341. # 0 = never, 1 = force every print, 2 = auto (run only if the
  6342. # filament wasn't calibrated recently). #1721 saw stage 8
  6343. # ("Calibrating dynamic flow") still queued when we send 2 —
  6344. # that is exactly the auto contract (the printer queues the
  6345. # stage and skips it at runtime if recent), not a bug, so 2 is
  6346. # the right wire value for "auto". off/on remain 0/1.
  6347. "extrude_cali_flag": flow_cali_int,
  6348. "extrude_cali_manual_mode": 0,
  6349. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  6350. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  6351. # again the auto contract, not a failure to suppress.
  6352. # BambuStudio exposes the toggle only for dual-nozzle
  6353. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  6354. # firmware never runs a calibration the head doesn't support.
  6355. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  6356. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  6357. "profile_id": "0",
  6358. "project_id": submission_id,
  6359. "subtask_id": submission_id,
  6360. "task_id": submission_id,
  6361. }
  6362. }
  6363. # P2S-specific parameter adjustments
  6364. # P2S printer doesn't support vibration calibration like X1/P1 series
  6365. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  6366. command["print"]["vibration_cali"] = False
  6367. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  6368. # Add AMS mapping if provided
  6369. if ams_mapping is not None:
  6370. command["print"]["ams_mapping"] = flat_ams_mapping
  6371. command["print"]["ams_mapping2"] = ams_mapping2
  6372. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  6373. # `nozzle_mapping` carries per-filament physical nozzle position
  6374. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  6375. # item; parse here so the wire ships an array, matching
  6376. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  6377. # defensively — single-nozzle firmwares would ignore the field
  6378. # but we err on the side of not emitting unrecognised fields. A
  6379. # parse failure is logged but never blocks the dispatch — the
  6380. # firmware will fall back to its auto-pick path, which is the
  6381. # pre-fix behaviour.
  6382. if is_dual_nozzle and nozzle_mapping:
  6383. try:
  6384. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  6385. except json.JSONDecodeError:
  6386. logger.warning(
  6387. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  6388. "project_file (firmware will auto-pick): %r",
  6389. self.serial_number,
  6390. nozzle_mapping,
  6391. )
  6392. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  6393. # never saw the job, so it can never override a real capture. The
  6394. # queue stores extruder indices per filament slot; the physical
  6395. # rack position they resolve to is only knowable here, because the
  6396. # mounted hotend can change between queueing and dispatch.
  6397. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  6398. try:
  6399. slot_extruders = json.loads(nozzle_slot_extruders)
  6400. except (json.JSONDecodeError, TypeError):
  6401. # TypeError covers a caller handing us the list itself
  6402. # rather than its JSON — the field is opaque by contract,
  6403. # and a print must not die over the difference.
  6404. slot_extruders = None
  6405. logger.warning(
  6406. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  6407. "omitting nozzle_mapping (firmware will auto-pick): %r",
  6408. self.serial_number,
  6409. nozzle_slot_extruders,
  6410. )
  6411. if isinstance(slot_extruders, list):
  6412. rack_nozzle_id = (
  6413. self.state.nozzle_rack_tar_id
  6414. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  6415. else self.state.nozzle_rack_src_id
  6416. )
  6417. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  6418. if resolved is None:
  6419. logger.info(
  6420. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  6421. "omitting nozzle_mapping so the firmware picks",
  6422. self.serial_number,
  6423. slot_extruders,
  6424. self.state.nozzle_rack_tar_id,
  6425. self.state.nozzle_rack_src_id,
  6426. )
  6427. else:
  6428. logger.info(
  6429. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  6430. self.serial_number,
  6431. slot_extruders,
  6432. rack_nozzle_id,
  6433. resolved,
  6434. )
  6435. command["print"]["nozzle_mapping"] = resolved
  6436. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  6437. # Remember this dispatch so its echo on the topic is recognised as
  6438. # ours rather than logged as a slicer's.
  6439. self._own_project_file_key = self._project_file_key(command["print"])
  6440. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6441. # Record what we dispatched so /cover can pick the right plate
  6442. # thumbnail even when the printer's gcode_file echo is just the
  6443. # 3MF filename without a plate path (#1166). Match the same
  6444. # subtask_name shape we send so the comparison in the cover route
  6445. # works against state.subtask_name reflected back via MQTT.
  6446. self.state.dispatched_plate_id = plate_id
  6447. self.state.dispatched_subtask = command["print"]["subtask_name"]
  6448. return True
  6449. else:
  6450. # Log why we couldn't send the command
  6451. if not self._client:
  6452. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  6453. elif not self.state.connected:
  6454. logger.error(
  6455. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  6456. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  6457. )
  6458. return False
  6459. def stop_print(self) -> bool:
  6460. """Stop the current print job."""
  6461. if self._client and self.state.connected:
  6462. command = {"print": {"command": "stop", "sequence_id": "0"}}
  6463. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6464. logger.info("[%s] Sent stop print command", self.serial_number)
  6465. return True
  6466. return False
  6467. def set_xcam_option(
  6468. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  6469. ) -> bool:
  6470. """Set an xcam (AI detection) option on the printer.
  6471. Args:
  6472. module_name: The xcam module to control (e.g., "spaghetti_detector",
  6473. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  6474. enabled: Whether to enable or disable the feature
  6475. print_halt: Whether to halt print on detection (only applies to some detectors)
  6476. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  6477. Returns:
  6478. True if command was sent, False if not connected
  6479. """
  6480. if not self._client or not self.state.connected:
  6481. return False
  6482. # auto_recovery_step_loss uses a different command format (print.print_option)
  6483. if module_name == "auto_recovery_step_loss":
  6484. return self._set_print_option("auto_recovery", enabled)
  6485. self._sequence_id += 1
  6486. # Build the xcam control command (exact OrcaSlicer format)
  6487. # Key findings from OrcaSlicer source:
  6488. # - Uses "xcam" wrapper (not "print")
  6489. # - print_halt is ALWAYS true (legacy protocol requirement)
  6490. # - Both "control" and "enable" are set to the same value
  6491. # - halt_print_sensitivity controls actual halt behavior
  6492. command = {
  6493. "xcam": {
  6494. "command": "xcam_control_set",
  6495. "sequence_id": str(self._sequence_id),
  6496. "module_name": module_name,
  6497. "control": enabled,
  6498. "enable": enabled, # old protocol compatibility
  6499. "print_halt": True, # ALWAYS true per OrcaSlicer
  6500. }
  6501. }
  6502. # Only add sensitivity if not "never_halt"
  6503. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  6504. # The module_name field determines which detector's sensitivity is being set
  6505. if sensitivity and sensitivity != "never_halt":
  6506. command["xcam"]["halt_print_sensitivity"] = sensitivity
  6507. command_json = json.dumps(command)
  6508. self._client.publish(self.topic_publish, command_json, qos=1)
  6509. logger.debug(
  6510. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  6511. )
  6512. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  6513. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  6514. # This prevents stale MQTT data from immediately overwriting our change
  6515. self._xcam_hold_start[module_name] = time.time()
  6516. # Update local state immediately for responsive UI
  6517. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  6518. # When spaghetti_detector sensitivity is changed, pileup also changes
  6519. if module_name == "spaghetti_detector":
  6520. self.state.print_options.spaghetti_detector = enabled
  6521. self.state.print_options.print_halt = print_halt
  6522. if sensitivity and sensitivity != "never_halt":
  6523. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  6524. self.state.print_options.halt_print_sensitivity = sensitivity
  6525. self.state.print_options.pileup_sensitivity = sensitivity
  6526. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  6527. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  6528. elif module_name == "first_layer_inspector":
  6529. self.state.print_options.first_layer_inspector = enabled
  6530. elif module_name == "printing_monitor":
  6531. self.state.print_options.printing_monitor = enabled
  6532. elif module_name == "buildplate_marker_detector":
  6533. self.state.print_options.buildplate_marker_detector = enabled
  6534. elif module_name == "allow_skip_parts":
  6535. self.state.print_options.allow_skip_parts = enabled
  6536. elif module_name == "pileup_detector":
  6537. self.state.print_options.pileup_detector = enabled
  6538. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  6539. elif module_name == "clump_detector":
  6540. self.state.print_options.nozzle_clumping_detector = enabled
  6541. if sensitivity and sensitivity != "never_halt":
  6542. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  6543. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  6544. elif module_name == "airprint_detector":
  6545. self.state.print_options.airprint_detector = enabled
  6546. if sensitivity and sensitivity != "never_halt":
  6547. self.state.print_options.airprint_sensitivity = sensitivity
  6548. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  6549. elif module_name == "auto_recovery_step_loss":
  6550. self.state.print_options.auto_recovery_step_loss = enabled
  6551. return True
  6552. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  6553. """Set a print option using the print.print_option command.
  6554. This is different from xcam_control_set and is used for options like:
  6555. - auto_recovery
  6556. - air_print_detect
  6557. - filament_tangle_detect
  6558. - nozzle_blob_detect
  6559. - sound_enable
  6560. Args:
  6561. option_name: The option to control (e.g., "auto_recovery")
  6562. enabled: Whether to enable or disable the option
  6563. Returns:
  6564. True if command was sent, False if not connected
  6565. """
  6566. if not self._client or not self.state.connected:
  6567. return False
  6568. self._sequence_id += 1
  6569. command = {
  6570. "print": {
  6571. "command": "print_option",
  6572. "sequence_id": str(self._sequence_id),
  6573. option_name: enabled,
  6574. }
  6575. }
  6576. command_json = json.dumps(command)
  6577. self._client.publish(self.topic_publish, command_json, qos=1)
  6578. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  6579. # Set hold timer
  6580. hold_key = f"print_option_{option_name}"
  6581. self._xcam_hold_start[hold_key] = time.time()
  6582. # Update local state immediately
  6583. if option_name == "auto_recovery":
  6584. self.state.print_options.auto_recovery_step_loss = enabled
  6585. elif option_name == "auto_switch_filament":
  6586. self.state.ams_filament_backup = enabled
  6587. return True
  6588. def set_ams_filament_backup(self, enabled: bool) -> bool:
  6589. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  6590. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  6591. shape from H2D capture 2026-06-20.
  6592. """
  6593. return self._set_print_option("auto_switch_filament", enabled)
  6594. def start_calibration(
  6595. self,
  6596. bed_leveling: bool = False,
  6597. vibration: bool = False,
  6598. motor_noise: bool = False,
  6599. nozzle_offset: bool = False,
  6600. high_temp_heatbed: bool = False,
  6601. ) -> bool:
  6602. """Start printer calibration with selected options.
  6603. Args:
  6604. bed_leveling: Run bed leveling calibration
  6605. vibration: Run vibration compensation calibration
  6606. motor_noise: Run motor noise cancellation calibration
  6607. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  6608. high_temp_heatbed: Run high-temperature heatbed calibration
  6609. Returns:
  6610. True if command was sent, False if not connected
  6611. """
  6612. if not self._client or not self.state.connected:
  6613. return False
  6614. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  6615. # Bit 0: xcam_cali (not exposed in UI)
  6616. # Bit 1: bed_leveling
  6617. # Bit 2: vibration
  6618. # Bit 3: motor_noise
  6619. # Bit 4: nozzle_cali
  6620. # Bit 5: bed_cali (high-temp heatbed)
  6621. # Bit 6: clumppos_cali (not exposed in UI)
  6622. option = 0
  6623. if bed_leveling:
  6624. option |= 1 << 1
  6625. if vibration:
  6626. option |= 1 << 2
  6627. if motor_noise:
  6628. option |= 1 << 3
  6629. if nozzle_offset:
  6630. option |= 1 << 4
  6631. if high_temp_heatbed:
  6632. option |= 1 << 5
  6633. if option == 0:
  6634. logger.warning("[%s] No calibration options selected", self.serial_number)
  6635. return False
  6636. self._sequence_id += 1
  6637. command = {
  6638. "print": {
  6639. "command": "calibration",
  6640. "sequence_id": str(self._sequence_id),
  6641. "option": option,
  6642. }
  6643. }
  6644. command_json = json.dumps(command)
  6645. self._client.publish(self.topic_publish, command_json, qos=1)
  6646. logger.info(
  6647. f"[{self.serial_number}] Starting calibration: "
  6648. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  6649. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  6650. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  6651. )
  6652. return True
  6653. def disconnect(self, timeout: float = 0):
  6654. """Disconnect from the printer.
  6655. Waits up to *timeout* for paho to report the disconnect, then lets the
  6656. client go without joining its network thread — the callers are route
  6657. handlers (printer edited, deleted, disconnected by hand) running on the
  6658. asyncio thread, and that join has no bound (#3068)."""
  6659. if self._client:
  6660. old_client = self._client
  6661. self._disconnection_event = threading.Event()
  6662. old_client.disconnect()
  6663. # The callback that sets this fires on paho's thread, so it has to
  6664. # be given its window before retire_paho_client detaches it.
  6665. self._disconnection_event.wait(timeout=timeout)
  6666. self._client = None
  6667. retire_paho_client(old_client, self.serial_number)
  6668. self.state.connected = False
  6669. # Deliberately no on_state_change here. paho's disconnect callback
  6670. # used to land during the join, but `_on_disconnect` suppresses
  6671. # itself for a clean disconnect of a printer that reported within
  6672. # the last 10s -- which is every healthy printer -- so a
  6673. # hand-disconnected printer never broadcast one. Announcing it now
  6674. # would fire the connected→disconnected edge in
  6675. # `on_printer_status_change` and notify the user their printer went
  6676. # offline a minute after they disconnected it on purpose (#1752).
  6677. # The callers drop the client from the manager anyway, so the next
  6678. # status read already shows it gone.
  6679. def enable_logging(self, enabled: bool = True):
  6680. """Enable or disable MQTT message logging."""
  6681. self._logging_enabled = enabled
  6682. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6683. def get_logs(self) -> list[MQTTLogEntry]:
  6684. """Get all logged MQTT messages."""
  6685. return list(self._message_log)
  6686. def clear_logs(self):
  6687. """Clear the message log."""
  6688. self._message_log.clear()
  6689. @property
  6690. def logging_enabled(self) -> bool:
  6691. """Check if logging is enabled."""
  6692. return self._logging_enabled
  6693. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6694. """Register a handler invoked for every incoming MQTT message.
  6695. Used by the VP MQTT bridge to republish the printer's report pushes to
  6696. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6697. on paho's network thread and must not block; exceptions are caught.
  6698. """
  6699. if handler not in self._raw_message_handlers:
  6700. self._raw_message_handlers.append(handler)
  6701. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6702. """Unregister a previously-registered raw-message handler."""
  6703. try:
  6704. self._raw_message_handlers.remove(handler)
  6705. except ValueError:
  6706. pass
  6707. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6708. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6709. Used by the VP MQTT bridge to forward slicer-originated commands without
  6710. giving it one of our own sequence ids. Returns False if the
  6711. underlying paho client isn't ready.
  6712. """
  6713. if self._client is None:
  6714. return False
  6715. try:
  6716. info = self._client.publish(topic, payload, qos=qos)
  6717. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6718. except Exception:
  6719. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6720. return False
  6721. def _ams3h_drying_zone_id(self, ams_id: int) -> int:
  6722. """The drying zone id of AMS 3H unit ``ams_id`` from the last status, else 0."""
  6723. unit = self._ams_unit(ams_id)
  6724. return _mqtt_int((unit or {}).get("dry_zone_id")) or 0
  6725. def send_drying_command(
  6726. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6727. ):
  6728. """Send AMS drying start/stop command.
  6729. Args:
  6730. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6731. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6732. duration: Drying duration in hours
  6733. mode: 1=start, 0=stop
  6734. filament: Filament type string (e.g. "PLA", "PETG")
  6735. rotate_tray: Whether to rotate the spool during drying for even heat
  6736. """
  6737. if not self._client:
  6738. return False
  6739. self._sequence_id += 1
  6740. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6741. # not actually support drying, but keep the translation consistent). The
  6742. # _drying_targets dict below stays keyed by the normalised id so the
  6743. # on_drying_complete callback matches the telemetry.
  6744. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6745. ams3h = self._rack_ams_type(ams_id) == AmsType.ZMULTI_A
  6746. command = {
  6747. "print": {
  6748. "sequence_id": str(self._sequence_id),
  6749. "command": "ams_filament_drying",
  6750. "ams_id": wire_ams_id,
  6751. "temp": temp,
  6752. "cooling_temp": 20 if mode == 1 else 0,
  6753. "duration": duration,
  6754. "humidity": 0,
  6755. "mode": mode,
  6756. "rotate_tray": rotate_tray,
  6757. "filament": filament,
  6758. "close_power_conflict": False,
  6759. }
  6760. }
  6761. if ams3h:
  6762. # As Studio 02.09 sends it (DevFilaSystemCtrl.cpp): a start names
  6763. # the drying zone and cooling_temp; a stop names no zone. The AMS 3H
  6764. # can't turn spools.
  6765. command["print"]["rotate_tray"] = False
  6766. if mode == 1:
  6767. command["print"]["zone_id"] = self._ams3h_drying_zone_id(ams_id)
  6768. command["print"]["cooling_temp"] = ams3h_drying_cooling_temp(filament)
  6769. # Log the full wire JSON at INFO so support bundles capture exactly
  6770. # what we sent — needed to diagnose silent rejections (#1447) where
  6771. # the printer ACKs the command but never starts/stops drying.
  6772. # Paired with the ams_filament_drying response-payload INFO log so
  6773. # both halves of the conversation land in the bundle by default.
  6774. wire_json = json.dumps(command)
  6775. self._client.publish(self.topic_publish, wire_json, qos=1)
  6776. logger.info(
  6777. "[%s] Sent ams_filament_drying: %s",
  6778. self.serial_number,
  6779. wire_json,
  6780. )
  6781. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6782. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6783. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6784. # say how much of the requested time the firmware actually ran (#2770).
  6785. if mode == 1:
  6786. self._drying_targets[ams_id] = {
  6787. "filament": filament or "",
  6788. "temp": int(temp),
  6789. "duration_hours": int(duration),
  6790. }
  6791. self._drying_stops_sent.discard(ams_id)
  6792. # A start sent while a cycle is still counting down replaces it
  6793. # without dry_time passing through 0; begin a fresh record so the
  6794. # new target and length are the ones reported (#2863).
  6795. self._dry_cycles.pop(ams_id, None)
  6796. else:
  6797. self._drying_targets.pop(ams_id, None)
  6798. # Remember that this cycle's end is ours, so the cycle-end log
  6799. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6800. # stop always ends the cycle far short of its duration, which is
  6801. # otherwise indistinguishable from the firmware abandoning it.
  6802. self._drying_stops_sent.add(ams_id)
  6803. return True
  6804. @staticmethod
  6805. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6806. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6807. The printer reports ``nozzle_diameter`` **only on the response
  6808. envelope** — the per-filament entries carry just setting_id,
  6809. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6810. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6811. single-nozzle printers regardless of the installed nozzle (#1748),
  6812. which broke the K-Profiles display and, worse, the cali_idx cascade
  6813. in the inventory/Spoolman assign paths that matches on
  6814. nozzle_diameter. Fall back to the envelope value instead, and only
  6815. to "0.4" when the envelope has none either.
  6816. ``or`` rather than a dict default on purpose: it also covers an entry
  6817. that carries the key with an empty value, and stops ``str()`` turning
  6818. a missing envelope value into the literal "None".
  6819. """
  6820. profiles: list[KProfile] = []
  6821. for i, f in enumerate(filaments):
  6822. if not isinstance(f, dict):
  6823. continue
  6824. try:
  6825. profiles.append(
  6826. KProfile(
  6827. # cali_idx is the actual slot/calibration index from the printer
  6828. slot_id=f.get("cali_idx", i),
  6829. extruder_id=int(f.get("extruder_id", 0)),
  6830. nozzle_id=str(f.get("nozzle_id", "")),
  6831. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6832. filament_id=str(f.get("filament_id", "")),
  6833. name=str(f.get("name", "")),
  6834. k_value=str(f.get("k_value", "0.000000")),
  6835. n_coef=str(f.get("n_coef", "0.000000")),
  6836. ams_id=int(f.get("ams_id", 0)),
  6837. tray_id=int(f.get("tray_id", -1)),
  6838. setting_id=f.get("setting_id"),
  6839. )
  6840. )
  6841. except (ValueError, TypeError) as e:
  6842. # Skip malformed entries; the remaining profiles stay usable.
  6843. # Unsolicited broadcasts arrive constantly, so only a response
  6844. # someone is actually waiting on is worth a warning.
  6845. if log_errors:
  6846. logger.warning("Failed to parse K-profile: %s", e)
  6847. else:
  6848. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6849. return profiles
  6850. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6851. """File one calibration-table response under its nozzle diameter.
  6852. ``response_nozzle`` names the table the printer just sent, so that
  6853. bucket is replaced wholesale and every other one is left alone. When
  6854. the envelope carries no diameter, fall back to the diameters the parsed
  6855. profiles claim for themselves — and if there are none of those either,
  6856. keep what we have rather than dropping a table we cannot attribute.
  6857. ``state.kprofiles`` stays a flat list because that is what its readers
  6858. expect; the three assign paths already filter it by ``nozzle_diameter``
  6859. and were quietly finding nothing whenever the last response happened to
  6860. be for a different nozzle.
  6861. """
  6862. buckets: dict[str, list] = {}
  6863. if response_nozzle:
  6864. buckets[str(response_nozzle)] = list(profiles)
  6865. else:
  6866. for profile in profiles:
  6867. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6868. if not buckets:
  6869. return
  6870. self._kprofiles_by_nozzle.update(buckets)
  6871. self.state.kprofiles = [
  6872. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6873. ]
  6874. def _handle_kprofile_response(self, data: dict):
  6875. """Handle K-profile response from printer."""
  6876. response_nozzle = data.get("nozzle_diameter")
  6877. response_seq_id = str(data.get("sequence_id", ""))
  6878. filaments = data.get("filaments", [])
  6879. # Snapshot the map: the asyncio thread adds and removes entries while
  6880. # this MQTT callback thread walks it.
  6881. pending = dict(self._pending_kprofile_requests)
  6882. request = pending.get(response_seq_id)
  6883. if request is None and pending:
  6884. # Firmware that doesn't echo our sequence_id still has to be
  6885. # served, so fall back to the pre-#1748 rule of matching on the
  6886. # nozzle size. Only requests still waiting are eligible, and the
  6887. # sequence_id lookup above has already claimed any response that
  6888. # identifies itself, so this can no longer hand request A's
  6889. # answer to request B when both are in flight.
  6890. request = next(
  6891. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6892. None,
  6893. )
  6894. if pending:
  6895. logger.info(
  6896. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6897. self.serial_number,
  6898. response_nozzle,
  6899. response_seq_id or "?",
  6900. len(filaments),
  6901. request is not None,
  6902. )
  6903. if request is None and pending:
  6904. # A request is outstanding and this isn't its answer. The printer
  6905. # broadcasts extrusion_cali_get unsolicited, so letting this
  6906. # through would replace state.kprofiles with another nozzle's
  6907. # profiles while the caller is still waiting.
  6908. logger.debug(
  6909. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6910. self.serial_number,
  6911. response_nozzle,
  6912. response_seq_id or "?",
  6913. )
  6914. return
  6915. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6916. self._store_kprofiles(profiles, response_nozzle)
  6917. if request is None:
  6918. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6919. # nobody to wake. Worth a line — this is the printer answering
  6920. # somebody else (BambuStudio queries the same report topic), and
  6921. # until it was bucketed by nozzle it was also the quietest way for
  6922. # the AMS card's K values to change underneath us.
  6923. logger.debug(
  6924. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6925. self.serial_number,
  6926. response_nozzle or "?",
  6927. len(profiles),
  6928. )
  6929. return
  6930. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6931. request["profiles"] = profiles
  6932. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6933. # in a different thread than the event loop.
  6934. event = request["event"]
  6935. if self._loop and self._loop.is_running():
  6936. self._loop.call_soon_threadsafe(event.set)
  6937. else:
  6938. # Fallback for when loop is not available
  6939. event.set()
  6940. async def get_kprofiles(
  6941. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6942. ) -> list[KProfile]:
  6943. """Request K-profiles from the printer with retry logic.
  6944. Bambu printers sometimes ignore the first K-profile request, so we
  6945. implement retry logic to ensure reliable retrieval.
  6946. Args:
  6947. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6948. timeout: Timeout in seconds to wait for each response attempt
  6949. max_retries: Maximum number of retry attempts
  6950. Returns:
  6951. List of KProfile objects; empty when the printer has none for
  6952. the nozzle.
  6953. Raises:
  6954. KProfileReadError: not connected, or no answer to any attempt.
  6955. Returning an empty list made that a printer without profiles
  6956. (#3404).
  6957. """
  6958. if not self._client or not self.state.connected:
  6959. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6960. raise KProfileReadError("Printer not connected")
  6961. # Capture current event loop for thread-safe callback
  6962. try:
  6963. self._loop = asyncio.get_running_loop()
  6964. except RuntimeError:
  6965. logger.warning("[%s] No running event loop", self.serial_number)
  6966. raise KProfileReadError("No running event loop") from None
  6967. for attempt in range(max_retries):
  6968. # Register this attempt under its own sequence_id so a concurrent
  6969. # request for a different nozzle size can't consume its response
  6970. # (#1748) — the pending map is keyed by exactly the id we send.
  6971. self._sequence_id += 1
  6972. seq_id = str(self._sequence_id)
  6973. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6974. self._pending_kprofile_requests[seq_id] = request
  6975. # Send the command with nozzle_diameter filter
  6976. command = {
  6977. "print": {
  6978. "command": "extrusion_cali_get",
  6979. "filament_id": "",
  6980. "nozzle_diameter": nozzle_diameter,
  6981. "sequence_id": seq_id,
  6982. }
  6983. }
  6984. logger.info(
  6985. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6986. )
  6987. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6988. # Wait for the response (the handler matches it back to this entry)
  6989. try:
  6990. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6991. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6992. profiles = request["profiles"] or []
  6993. logger.info(
  6994. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6995. )
  6996. return profiles
  6997. except TimeoutError:
  6998. logger.warning(
  6999. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  7000. )
  7001. if attempt < max_retries - 1:
  7002. # Brief delay before retry
  7003. await asyncio.sleep(0.5)
  7004. finally:
  7005. self._pending_kprofile_requests.pop(seq_id, None)
  7006. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  7007. raise KProfileReadError("The printer did not answer the K-profile request")
  7008. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  7009. """Publish a K-profile write and arm its ack slot.
  7010. Registration happens before the publish because the printer answers in
  7011. well under a second — measured at 70-150ms — which is comfortably
  7012. before an async caller gets back to awaiting.
  7013. """
  7014. self._pending_cali_acks[seq_id] = None
  7015. try:
  7016. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7017. except Exception:
  7018. self._pending_cali_acks.pop(seq_id, None)
  7019. raise
  7020. return True
  7021. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  7022. """Wait for the printer's verdict on a K-profile write.
  7023. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  7024. explicitly said ``result: "fail"`` — a timeout returns True with a
  7025. detail string, because "no answer" is not evidence of rejection and
  7026. older firmware may not answer at all. Callers that need certainty read
  7027. the calibration table back.
  7028. Polled rather than event-driven on purpose: the ack is filled in by the
  7029. MQTT callback thread, and polling a dict costs one lookup every 50ms
  7030. for at most a few hundred milliseconds, against the cross-thread
  7031. event plumbing it would otherwise take.
  7032. """
  7033. deadline = time.monotonic() + timeout
  7034. try:
  7035. while time.monotonic() < deadline:
  7036. ack = self._pending_cali_acks.get(seq_id)
  7037. if ack is not None:
  7038. result = str(ack.get("result", "")).lower()
  7039. reason = str(ack.get("reason", "") or "")
  7040. if result == "fail":
  7041. return (False, reason or "printer reported failure")
  7042. return (True, reason)
  7043. await asyncio.sleep(0.05)
  7044. finally:
  7045. self._pending_cali_acks.pop(seq_id, None)
  7046. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  7047. return (True, CALI_ACK_UNCONFIRMED)
  7048. def set_kprofile(
  7049. self,
  7050. filament_id: str,
  7051. name: str,
  7052. k_value: str,
  7053. nozzle_diameter: str = "0.4",
  7054. nozzle_id: str = "HS00-0.4",
  7055. extruder_id: int = 0,
  7056. setting_id: str | None = None,
  7057. slot_id: int = 0,
  7058. cali_idx: int | None = None,
  7059. ) -> str | None:
  7060. """Set/update a K-profile on the printer.
  7061. Args:
  7062. filament_id: Bambu filament identifier
  7063. name: Profile name
  7064. k_value: Pressure advance value (e.g., "0.020000")
  7065. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7066. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  7067. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7068. setting_id: Existing setting ID for updates, None for new
  7069. slot_id: Calibration index (cali_idx) for the profile
  7070. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  7071. Returns:
  7072. The sequence_id the command was sent under, so the caller can
  7073. await the printer's verdict via await_cali_ack. None if the
  7074. command could not be sent.
  7075. """
  7076. if not self._client or not self.state.connected:
  7077. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  7078. return None
  7079. self._sequence_id += 1
  7080. seq_id = str(self._sequence_id)
  7081. # Build the filament entry - printer uses cali_idx for profile identification
  7082. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  7083. # For edits, use the provided cali_idx or slot_id
  7084. if cali_idx is not None:
  7085. effective_cali_idx = cali_idx
  7086. else:
  7087. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7088. # Generate a setting_id for new profiles (required by printer)
  7089. # Format: "PF" + 17 random digits
  7090. import random
  7091. if not setting_id and slot_id == 0:
  7092. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7093. filament_entry = {
  7094. "ams_id": 0,
  7095. "cali_idx": effective_cali_idx,
  7096. "extruder_id": extruder_id,
  7097. "filament_id": filament_id,
  7098. "k_value": k_value,
  7099. "n_coef": "0.000000",
  7100. "name": name,
  7101. "nozzle_diameter": nozzle_diameter,
  7102. "nozzle_id": nozzle_id,
  7103. "setting_id": setting_id if setting_id else "",
  7104. # 0, not -1. Single-nozzle firmware validates this field and
  7105. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  7106. # applying the write anyway, so the rejection looked like noise.
  7107. # Measured on an X1C: flipping only this value turns the ack into
  7108. # `success` (#2718). BambuStudio always sends a real tray_id and
  7109. # defaults it to 0 for a manually entered profile.
  7110. "tray_id": 0,
  7111. }
  7112. command = {
  7113. "print": {
  7114. "command": "extrusion_cali_set",
  7115. "filaments": [filament_entry],
  7116. "nozzle_diameter": nozzle_diameter,
  7117. "sequence_id": seq_id,
  7118. }
  7119. }
  7120. command_json = json.dumps(command)
  7121. logger.info(
  7122. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  7123. )
  7124. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  7125. self._publish_cali_write(command, seq_id)
  7126. return seq_id
  7127. def set_kprofiles_batch(
  7128. self,
  7129. profiles: list[dict],
  7130. nozzle_diameter: str = "0.4",
  7131. ) -> str | None:
  7132. """Set multiple K-profiles in a single command (for dual-nozzle).
  7133. Args:
  7134. profiles: List of profile dicts, each with:
  7135. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  7136. nozzle_diameter: Common nozzle diameter for all profiles
  7137. Returns:
  7138. The sequence_id the command was sent under (see set_kprofile),
  7139. or None if it could not be sent.
  7140. """
  7141. if not self._client or not self.state.connected:
  7142. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  7143. return None
  7144. import random
  7145. self._sequence_id += 1
  7146. seq_id = str(self._sequence_id)
  7147. filament_entries = []
  7148. for p in profiles:
  7149. slot_id = p.get("slot_id", 0)
  7150. cali_idx = p.get("cali_idx")
  7151. if cali_idx is not None:
  7152. effective_cali_idx = cali_idx
  7153. else:
  7154. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7155. setting_id = p.get("setting_id")
  7156. if not setting_id and slot_id == 0:
  7157. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7158. filament_entries.append(
  7159. {
  7160. "ams_id": 0,
  7161. "cali_idx": effective_cali_idx,
  7162. "extruder_id": p.get("extruder_id", 0),
  7163. "filament_id": p.get("filament_id", ""),
  7164. "k_value": p.get("k_value", "0.020000"),
  7165. "n_coef": "0.000000",
  7166. "name": p.get("name", ""),
  7167. "nozzle_diameter": nozzle_diameter,
  7168. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  7169. "setting_id": setting_id if setting_id else "",
  7170. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  7171. # single-nozzle firmware even though the write lands (#2718).
  7172. "tray_id": 0,
  7173. }
  7174. )
  7175. command = {
  7176. "print": {
  7177. "command": "extrusion_cali_set",
  7178. "filaments": filament_entries,
  7179. "nozzle_diameter": nozzle_diameter,
  7180. "sequence_id": seq_id,
  7181. }
  7182. }
  7183. command_json = json.dumps(command)
  7184. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  7185. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  7186. self._publish_cali_write(command, seq_id)
  7187. return seq_id
  7188. def delete_kprofile(
  7189. self,
  7190. cali_idx: int,
  7191. filament_id: str,
  7192. nozzle_id: str,
  7193. nozzle_diameter: str = "0.4",
  7194. extruder_id: int = 0,
  7195. setting_id: str | None = None,
  7196. ) -> str | None:
  7197. """Delete a K-profile from the printer.
  7198. Args:
  7199. cali_idx: The calibration index (slot_id) of the profile to delete
  7200. filament_id: Bambu filament identifier
  7201. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  7202. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7203. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7204. setting_id: Unique setting identifier (for X1C series)
  7205. Returns:
  7206. The sequence_id the command was sent under (see set_kprofile),
  7207. or None if it could not be sent.
  7208. """
  7209. if not self._client or not self.state.connected:
  7210. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  7211. return None
  7212. self._sequence_id += 1
  7213. seq_id = str(self._sequence_id)
  7214. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  7215. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  7216. # Prefer runtime detection from device.extruder.info; fall back to
  7217. # model name. H2S is single-nozzle but shares serial prefix "094" with
  7218. # H2D, so a prefix-only check misclassified it (#1386).
  7219. from backend.app.utils.printer_models import is_dual_nozzle_model
  7220. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  7221. if is_dual_nozzle:
  7222. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  7223. command = {
  7224. "print": {
  7225. "command": "extrusion_cali_del",
  7226. "sequence_id": seq_id,
  7227. "extruder_id": extruder_id,
  7228. "nozzle_id": nozzle_id,
  7229. "filament_id": filament_id,
  7230. "cali_idx": cali_idx,
  7231. "nozzle_diameter": nozzle_diameter,
  7232. }
  7233. }
  7234. else:
  7235. # X1C/P1/A1 format: include all fields like the set command
  7236. # The delete command structure should match what set uses
  7237. command = {
  7238. "print": {
  7239. "command": "extrusion_cali_del",
  7240. "sequence_id": seq_id,
  7241. "filament_id": filament_id,
  7242. "cali_idx": cali_idx,
  7243. "setting_id": setting_id if setting_id else "",
  7244. "nozzle_diameter": nozzle_diameter,
  7245. "nozzle_id": nozzle_id,
  7246. "extruder_id": extruder_id,
  7247. }
  7248. }
  7249. command_json = json.dumps(command)
  7250. logger.info(
  7251. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  7252. )
  7253. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  7254. # QoS 1 for reliable delivery (at least once)
  7255. self._publish_cali_write(command, seq_id)
  7256. return seq_id
  7257. # =========================================================================
  7258. # Printer Control Commands
  7259. # =========================================================================
  7260. def pause_print(self) -> bool:
  7261. """Pause the current print job."""
  7262. if not self._client or not self.state.connected:
  7263. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  7264. return False
  7265. command = {"print": {"command": "pause", "sequence_id": "0"}}
  7266. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7267. logger.info("[%s] Sent pause print command", self.serial_number)
  7268. return True
  7269. def resume_print(self) -> bool:
  7270. """Resume a paused print job."""
  7271. if not self._client or not self.state.connected:
  7272. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  7273. return False
  7274. command = {"print": {"command": "resume", "sequence_id": "0"}}
  7275. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7276. logger.info("[%s] Sent resume print command", self.serial_number)
  7277. return True
  7278. def clear_hms_errors(self) -> bool:
  7279. """Clear HMS/print errors on the printer and locally."""
  7280. if not self._client or not self.state.connected:
  7281. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  7282. return False
  7283. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  7284. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7285. self.state.hms_errors = []
  7286. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  7287. return True
  7288. def _handle_skip_objects_answer(self, print_data: dict) -> None:
  7289. """The printer's answer to skip_objects: a refusal is logged and the
  7290. objects are no longer shown as skipped."""
  7291. obj_list = self._skip_commands.pop(str(print_data.get("sequence_id", "")), None)
  7292. result = str(print_data.get("result", "") or "").lower()
  7293. if obj_list is None or result in ("", "success"):
  7294. return
  7295. logger.error(
  7296. "[%s] Printer refused skipping objects %s: result=%s reason=%s",
  7297. self.serial_number,
  7298. obj_list,
  7299. print_data.get("result"),
  7300. print_data.get("reason", ""),
  7301. )
  7302. for oid in obj_list:
  7303. self._unconfirmed_skips.pop(oid, None)
  7304. self.state.skipped_objects = [oid for oid in self.state.skipped_objects if oid not in obj_list]
  7305. def _check_unconfirmed_skips(self) -> None:
  7306. """Log, once, a skip the printer's s_obj list never showed."""
  7307. if not self._unconfirmed_skips:
  7308. return
  7309. if self.state.state not in ("RUNNING", "PAUSE"):
  7310. # The print ended; its skips are moot.
  7311. self._unconfirmed_skips.clear()
  7312. self._skip_commands.clear()
  7313. return
  7314. now = time.monotonic()
  7315. # A copy: skip_objects adds to the dict from the event loop while this
  7316. # runs on the MQTT thread.
  7317. pending = list(self._unconfirmed_skips.items())
  7318. expired = [oid for oid, sent_at in pending if now - sent_at > SKIP_CONFIRM_TIMEOUT_S]
  7319. if not expired:
  7320. return
  7321. logger.error(
  7322. "[%s] Printer did not confirm skipping objects %s within %.0fs; they may still be printed",
  7323. self.serial_number,
  7324. sorted(expired),
  7325. SKIP_CONFIRM_TIMEOUT_S,
  7326. )
  7327. for oid in expired:
  7328. self._unconfirmed_skips.pop(oid, None)
  7329. def skip_objects(self, object_ids: list[int]) -> bool:
  7330. """Skip specific objects during a print.
  7331. This command tells the printer to skip printing the specified objects.
  7332. The object IDs come from the slice_info.config file in the 3MF.
  7333. Args:
  7334. object_ids: List of identify_id values from slice_info.config
  7335. Returns:
  7336. True if command was sent, False otherwise
  7337. """
  7338. if not self._client or not self.state.connected:
  7339. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  7340. return False
  7341. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  7342. logger.warning(
  7343. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  7344. )
  7345. return False
  7346. if not object_ids:
  7347. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  7348. return False
  7349. # Validate all IDs are integers
  7350. try:
  7351. obj_list = [int(oid) for oid in object_ids]
  7352. except (ValueError, TypeError) as e:
  7353. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  7354. return False
  7355. self._sequence_id += 1
  7356. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  7357. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7358. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  7359. sent_at = time.monotonic()
  7360. for oid in obj_list:
  7361. self._unconfirmed_skips.setdefault(oid, sent_at)
  7362. self._skip_commands[str(self._sequence_id)] = obj_list
  7363. # Track skipped objects in state
  7364. for oid in obj_list:
  7365. if oid not in self.state.skipped_objects:
  7366. self.state.skipped_objects.append(oid)
  7367. return True
  7368. def send_gcode(self, gcode: str) -> bool:
  7369. """Send G-code command(s) to the printer.
  7370. Multiple commands can be separated by newlines.
  7371. Args:
  7372. gcode: G-code command(s) to send
  7373. Returns:
  7374. True if command was sent, False otherwise
  7375. """
  7376. if not self._client or not self.state.connected:
  7377. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  7378. return False
  7379. self._sequence_id += 1
  7380. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  7381. # Use QoS 1 for reliable delivery (at least once)
  7382. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7383. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  7384. return True
  7385. def set_bed_temperature(self, target: int) -> bool:
  7386. """Set the bed target temperature.
  7387. Args:
  7388. target: Target temperature in Celsius (0 to turn off)
  7389. Returns:
  7390. True if command was sent, False otherwise
  7391. """
  7392. return self.send_gcode(f"M140 S{target}")
  7393. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  7394. """Set the nozzle target temperature.
  7395. Args:
  7396. target: Target temperature in Celsius (0 to turn off)
  7397. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  7398. Returns:
  7399. True if command was sent, False otherwise
  7400. """
  7401. # Use M104 for non-blocking
  7402. # Always use T parameter for H2D compatibility
  7403. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  7404. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  7405. # Track it locally so we can display it correctly
  7406. if result and nozzle == 1:
  7407. self.state.temperatures["nozzle_target"] = float(target)
  7408. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  7409. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  7410. return result
  7411. def set_chamber_temperature(self, target: int) -> bool:
  7412. """Set the chamber target temperature.
  7413. Args:
  7414. target: Target temperature in Celsius (0 to turn off heating)
  7415. Returns:
  7416. True if command was sent, False otherwise
  7417. """
  7418. # The H3C's heater only runs in the airduct's heating mode.
  7419. from backend.app.utils.printer_models import chamber_heater_needs_heating_mode
  7420. if target > 0 and self.state.airduct_mode != 1 and chamber_heater_needs_heating_mode(self.model):
  7421. logger.info(
  7422. "[%s] Chamber target %s°C: switching the airduct to heating mode first (H3C)",
  7423. self.serial_number,
  7424. target,
  7425. )
  7426. self.set_airduct_mode("heating")
  7427. # M141 sets chamber temperature
  7428. result = self.send_gcode(f"M141 S{target}")
  7429. # Track chamber target locally (MQTT reports encoded values that need filtering)
  7430. if result:
  7431. self.state.temperatures["chamber_target"] = float(target)
  7432. self.state.temperatures["_chamber_target_set_time"] = time.time()
  7433. # Update heating state immediately based on new target
  7434. current_temp = self.state.temperatures.get("chamber", 0)
  7435. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  7436. logger.info(
  7437. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  7438. )
  7439. return result
  7440. def set_print_speed(self, mode: int) -> bool:
  7441. """Set the print speed mode.
  7442. Args:
  7443. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  7444. Returns:
  7445. True if command was sent, False otherwise
  7446. """
  7447. if not self._client or not self.state.connected:
  7448. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  7449. return False
  7450. if mode not in (1, 2, 3, 4):
  7451. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  7452. return False
  7453. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  7454. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7455. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  7456. return True
  7457. def set_fan_speed(self, fan: int, speed: int) -> bool:
  7458. """Set fan speed.
  7459. Args:
  7460. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=second auxiliary).
  7461. Index 10 is the second auxiliary part cooling fan: left on the P2S
  7462. (an accessory kit), right on the X2D, where 2 is the left (#3373)
  7463. (airduct part id 10); Bambu's official machine profiles drive it with
  7464. "M106 P10" in start/layer-change gcode.
  7465. speed: Speed 0-255 (0=off, 255=full)
  7466. Returns:
  7467. True if command was sent, False otherwise
  7468. """
  7469. if fan not in (1, 2, 3, 10):
  7470. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  7471. return False
  7472. speed = max(0, min(255, speed)) # Clamp to 0-255
  7473. return self.send_gcode(f"M106 P{fan} S{speed}")
  7474. def set_airduct_mode(self, mode: str) -> bool:
  7475. """Set air conditioning mode (cooling or heating).
  7476. Args:
  7477. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  7478. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  7479. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  7480. closes top exhaust flap
  7481. Returns:
  7482. True if command was sent, False otherwise
  7483. """
  7484. if not self._client or not self.state.connected:
  7485. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  7486. return False
  7487. self._sequence_id += 1
  7488. mode_id = 0 if mode == "cooling" else 1
  7489. command = {
  7490. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  7491. }
  7492. # Use QoS 1 for reliable delivery
  7493. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7494. logger.info(
  7495. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  7496. )
  7497. return True
  7498. def set_chamber_light(self, on: bool) -> bool:
  7499. """Turn chamber light on or off.
  7500. Args:
  7501. on: True to turn on, False to turn off
  7502. Returns:
  7503. True if command was sent, False otherwise
  7504. """
  7505. if not self._client or not self.state.connected:
  7506. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  7507. return False
  7508. mode = "on" if on else "off"
  7509. # Control both chamber lights (some printers like H2D have two)
  7510. for led_node in ["chamber_light", "chamber_light2"]:
  7511. self._sequence_id += 1
  7512. command = {
  7513. "system": {
  7514. "command": "ledctrl",
  7515. "led_node": led_node,
  7516. "led_mode": mode,
  7517. "led_on_time": 500,
  7518. "led_off_time": 500,
  7519. "loop_times": 0,
  7520. "interval_time": 0,
  7521. "sequence_id": str(self._sequence_id),
  7522. }
  7523. }
  7524. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7525. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  7526. return True
  7527. def select_extruder(self, extruder: int) -> bool:
  7528. """Select the active extruder for dual-nozzle printers (H2D).
  7529. Args:
  7530. extruder: Extruder index (0=right, 1=left for H2D)
  7531. Returns:
  7532. True if command was sent, False otherwise
  7533. """
  7534. if extruder not in (0, 1):
  7535. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  7536. return False
  7537. if not self._client or not self.state.connected:
  7538. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  7539. return False
  7540. # H2D extruder switching via select_extruder command
  7541. # Command format captured from OrcaSlicer:
  7542. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  7543. # extruder_index: 0 = RIGHT, 1 = LEFT
  7544. self._sequence_id += 1
  7545. command = {
  7546. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  7547. }
  7548. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7549. logger.info(
  7550. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  7551. )
  7552. return True
  7553. def _ams_unit(self, ams_id: int) -> dict | None:
  7554. """AMS unit ``ams_id`` in the last status, or None."""
  7555. for unit in self.state.raw_data.get("ams") or []:
  7556. if isinstance(unit, dict) and _mqtt_int(unit.get("id")) == ams_id:
  7557. return unit
  7558. return None
  7559. def _rack_tray(self, tray_id: int | None) -> tuple[int, int, dict | None] | None:
  7560. """``(ams_id, slot, tray)`` of a rack AMS slot's global tray id (the AMS 3H's 28-36), else None."""
  7561. if not isinstance(tray_id, int):
  7562. return None
  7563. located = self.tray_layout.rack_slot(tray_id)
  7564. if located is None:
  7565. return None
  7566. ams_id, slot = located
  7567. unit = self._ams_unit(ams_id) or {}
  7568. tray = next(
  7569. (t for t in unit.get("tray") or [] if isinstance(t, dict) and _mqtt_int(t.get("id")) == slot),
  7570. None,
  7571. )
  7572. return ams_id, slot, tray
  7573. def rack_tray_has_filament(self, tray_id: int) -> bool:
  7574. """Whether rack AMS slot ``tray_id`` reports a filament type, which Studio requires before a Load.
  7575. The AMS 3H registers a spool only once it has pulled the filament in at the inlet.
  7576. """
  7577. rack = self._rack_tray(tray_id)
  7578. return bool(rack and rack[2] and rack[2].get("tray_type"))
  7579. @staticmethod
  7580. def _tray_mid_temp(tray: dict | None) -> int:
  7581. """Midpoint of a tray's nozzle_temp_min/max, or -1 (as Studio's ams_change_filament)."""
  7582. if tray is None:
  7583. return -1
  7584. low, high = _mqtt_int(tray.get("nozzle_temp_min")), _mqtt_int(tray.get("nozzle_temp_max"))
  7585. return (low + high) // 2 if low and high and low > 0 and high > 0 else -1
  7586. def _rack_change_filament(self, tray_id: int, load: bool) -> bool:
  7587. """Load AMS 3H slot ``tray_id`` into its own hotend, or unload that hotend.
  7588. As Studio 02.09 sends it for a direct-connected rack (PageFilament.cpp):
  7589. load targets 32 at slot k, unload 255 at slot 255 - k (the feeder to
  7590. retract). The AMS 3H can't rewind: an unload ends with a hand pull.
  7591. """
  7592. client = self._client
  7593. rack = self._rack_tray(tray_id)
  7594. if client is None or rack is None:
  7595. return False
  7596. ams_id, slot, tray = rack
  7597. on_head = self._rack_tray(self.state.tray_now)
  7598. self._sequence_id += 1
  7599. command = {
  7600. "print": {
  7601. "command": "ams_change_filament",
  7602. "sequence_id": str(self._sequence_id),
  7603. "ams_id": ams_id,
  7604. "target": ams_id if load else 255,
  7605. "slot_id": slot if load else 255 - slot,
  7606. "extruder_id": 0,
  7607. "curr_temp": self._tray_mid_temp(on_head[2] if on_head else None),
  7608. "tar_temp": self._tray_mid_temp(tray),
  7609. }
  7610. }
  7611. command_json = json.dumps(command)
  7612. logger.info(
  7613. "[%s] Publishing ams_change_filament (%s, AMS 3H slot %d): %s",
  7614. self.serial_number,
  7615. "load" if load else "unload",
  7616. slot + 1,
  7617. command_json,
  7618. )
  7619. client.publish(self.topic_publish, command_json, qos=1)
  7620. if load:
  7621. self.state.pending_tray_target = tray_id
  7622. self.state.pending_tray_target_at = time.monotonic()
  7623. else:
  7624. self.state.pending_tray_target = None
  7625. self.state.pending_tray_target_at = None
  7626. return True
  7627. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  7628. """Load filament from a specific AMS tray.
  7629. Args:
  7630. tray_id: Global tray ID — 0..15 for AMS slots, 24..27 for the A2L
  7631. AMS-Lite, 128..135 for an AMS-HT (its unit id), 254 for external spool
  7632. (single-external printers and Ext-L on dual-nozzle H2D),
  7633. 255 for Ext-R on dual-nozzle H2D.
  7634. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  7635. Sent only when given, matching BambuStudio: ``extruder_id`` is
  7636. an optional field on ``ams_change_filament``
  7637. (``DeviceManager::command_ams_change_filament``) and Studio
  7638. omits it unless a Filament Track Switch is installed. Without a
  7639. switch the firmware derives the hotend from the AMS's own
  7640. extruder binding and an explicit value is redundant; *with* one
  7641. every AMS reports 0xE and is bound to a switch inlet instead, so
  7642. the firmware has nothing to derive from and the load silently
  7643. does nothing until we name the hotend.
  7644. Returns:
  7645. True if command was sent, False otherwise
  7646. """
  7647. if not self._client or not self.state.connected:
  7648. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  7649. return False
  7650. if self.tray_layout.rack_units:
  7651. # Only an AMS 3H slot can be loaded: an external input or an AMS-B
  7652. # can't feed itself (Studio's CanAutoFeed).
  7653. rack = self._rack_tray(tray_id)
  7654. if rack is None or self.tray_layout.ams_type(rack[0]) != AmsType.ZMULTI_A:
  7655. logger.warning("[%s] Load: tray %s is not an AMS 3H slot", self.serial_number, tray_id)
  7656. return False
  7657. if not self.rack_tray_has_filament(tray_id):
  7658. logger.warning("[%s] Load: AMS 3H slot %d has no filament", self.serial_number, rack[1] + 1)
  7659. return False
  7660. return self._rack_change_filament(tray_id, load=True)
  7661. # Build the ams_change_filament command. Encoding differs by target type:
  7662. # - AMS slots (0..15, A2L 24..27, AMS-HT 128..135): see
  7663. # change_filament_wire_ids; curr/tar_temp = -1.
  7664. # - External spool (tray_id=254): legacy capture from a single-extruder
  7665. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  7666. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  7667. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  7668. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  7669. self._sequence_id += 1
  7670. wire_target = tray_id
  7671. if tray_id == 255:
  7672. ams_id = 255
  7673. slot_id = 0 # extruder index for the right nozzle
  7674. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  7675. if right_temp < 180:
  7676. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  7677. curr_temp = right_temp
  7678. tar_temp = right_temp
  7679. elif tray_id == 254:
  7680. ams_id = 255
  7681. slot_id = 254
  7682. curr_temp = -1
  7683. tar_temp = -1
  7684. else:
  7685. # A regular AMS, the A2L AMS-Lite (physical unit 16) or an AMS-HT
  7686. # (128-135), as BambuStudio addresses each.
  7687. ams_id, slot_id, wire_target = change_filament_wire_ids(tray_id, self.tray_layout)
  7688. curr_temp = -1
  7689. tar_temp = -1
  7690. command = {
  7691. "print": {
  7692. "command": "ams_change_filament",
  7693. "sequence_id": str(self._sequence_id),
  7694. "ams_id": ams_id,
  7695. "slot_id": slot_id,
  7696. "target": wire_target,
  7697. "curr_temp": curr_temp,
  7698. "tar_temp": tar_temp,
  7699. }
  7700. }
  7701. if extruder_id is not None:
  7702. command["print"]["extruder_id"] = int(extruder_id)
  7703. command_json = json.dumps(command)
  7704. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  7705. self._client.publish(self.topic_publish, command_json, qos=1)
  7706. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  7707. # Track this load request for H2D dual-nozzle disambiguation
  7708. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  7709. self.state.pending_tray_target = tray_id
  7710. self.state.pending_tray_target_at = time.monotonic()
  7711. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  7712. return True
  7713. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  7714. """Unload filament, optionally naming the slot to unload.
  7715. Args:
  7716. tray_id: Global tray ID of the slot being unloaded. When given, the
  7717. command is addressed to that slot's AMS and is only sent if an
  7718. extruder is actually fed from it — BambuStudio does the same
  7719. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  7720. nothing when none matches). When omitted, the pre-existing
  7721. behaviour is kept: unload whatever ``tray_now`` names.
  7722. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  7723. machine with both hotends loaded it names only one of them and an
  7724. unaddressed unload picks that one regardless of which slot the operator
  7725. clicked. Passing the slot is what makes the two hotends distinguishable.
  7726. Returns:
  7727. True if command was sent, False otherwise
  7728. """
  7729. if not self._client or not self.state.connected:
  7730. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  7731. return False
  7732. if self.tray_layout.rack_units:
  7733. # The hotend of the named AMS 3H slot, else of the one on the toolhead.
  7734. source = tray_id if tray_id is not None else self.state.tray_now
  7735. if self._rack_tray(source) is None:
  7736. logger.warning("[%s] Unload: no AMS 3H slot to unload (tray %s)", self.serial_number, source)
  7737. return False
  7738. return self._rack_change_filament(source, load=False)
  7739. # Get the currently loaded tray info
  7740. tray_now = self.state.tray_now
  7741. source_tray = tray_now if tray_id is None else tray_id
  7742. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  7743. # Determine source ams_id for the unload command
  7744. if source_tray == 255 or source_tray == 254:
  7745. ams_id = 255 # No filament or external spool
  7746. else:
  7747. # Source AMS: the A2L AMS-Lite as physical 16, an AMS-HT as its unit id.
  7748. ams_id = change_filament_wire_ids(source_tray, self.tray_layout)[0]
  7749. # Refuse an addressed unload of a slot no hotend is holding — but only on
  7750. # a printer that has more than one hotend, which is the only case the
  7751. # check exists for. With one hotend there is nothing to disambiguate:
  7752. # tray_now already names the loaded slot exactly, and running the check
  7753. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  7754. # very likely does, but single-nozzle machines do report the block —
  7755. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  7756. # an X1C on the maintainer's own network sends `device.extruder` — and
  7757. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  7758. # would 409 every unload on every X1C, P1S and A1.
  7759. #
  7760. # Gated on the runtime flag rather than on len(extruder_slots), which is
  7761. # rebuilt from each payload's array and would flip the check off for any
  7762. # frame that carried a short one; and deliberately not on
  7763. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  7764. # one single-nozzle machine as dual (#1386) — the false positive there is
  7765. # exactly the case this gate exists to keep out.
  7766. #
  7767. # The external spool is excluded for a different reason: 254/255 are not
  7768. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  7769. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  7770. local_slot = change_filament_wire_ids(tray_id, self.tray_layout)[1]
  7771. holder = next(
  7772. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  7773. None,
  7774. )
  7775. if holder is None:
  7776. logger.info(
  7777. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  7778. self.serial_number,
  7779. ams_id,
  7780. local_slot,
  7781. )
  7782. return False
  7783. logger.info(
  7784. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7785. )
  7786. # Command format from BambuStudio traffic capture:
  7787. # - No extruder_id field
  7788. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7789. # - slot_id=255 and target=255 for unload
  7790. # Get current nozzle temperature for the unload command
  7791. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7792. if nozzle_temp < 180:
  7793. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7794. self._sequence_id += 1
  7795. command = {
  7796. "print": {
  7797. "command": "ams_change_filament",
  7798. "sequence_id": str(self._sequence_id),
  7799. "ams_id": ams_id,
  7800. "slot_id": 255, # 255 = unload marker
  7801. "target": 255, # 255 = unload destination
  7802. "curr_temp": nozzle_temp,
  7803. "tar_temp": nozzle_temp,
  7804. }
  7805. }
  7806. command_json = json.dumps(command)
  7807. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7808. self._client.publish(self.topic_publish, command_json, qos=1)
  7809. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7810. # Clear tracked load request since we're unloading
  7811. self.state.pending_tray_target = None
  7812. self.state.pending_tray_target_at = None
  7813. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7814. return True
  7815. def ams_control(self, action: str) -> bool:
  7816. """Control AMS operations.
  7817. Args:
  7818. action: "resume", "reset", or "pause"
  7819. Returns:
  7820. True if command was sent, False otherwise
  7821. """
  7822. if not self._client or not self.state.connected:
  7823. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7824. return False
  7825. if action not in ("resume", "reset", "pause"):
  7826. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7827. return False
  7828. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7829. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7830. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7831. return True
  7832. async def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7833. """Trigger RFID re-read for a specific AMS tray.
  7834. Sends ``ams_get_rfid`` and waits for the printer's answer. Firmware
  7835. that refuses it (#3206: X1Plus on base 01.08.02.00 answers ``FAIL`` /
  7836. ``ERROR STATE``) gets the legacy ``M620 R<global tray>`` gcode instead,
  7837. which is what Bambu Studio sends to printers without the new protocol.
  7838. The fallback only follows an explicit refusal, so firmware that takes
  7839. ``ams_get_rfid`` never sees it.
  7840. Success means the printer accepted the request, not that the tag was
  7841. read: the slot updating in the next push is the only proof of that.
  7842. Args:
  7843. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7844. tray_id: Tray ID within the AMS (0-3)
  7845. Returns:
  7846. Tuple of (success, message)
  7847. """
  7848. if not self._client or not self.state.connected:
  7849. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7850. return False, "Printer not connected"
  7851. # Check if filament is currently loaded (tray_now != 255)
  7852. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7853. tray_now = self.state.tray_now
  7854. if tray_now != 255:
  7855. # Decode which tray is loaded for the message
  7856. layout = self.tray_layout
  7857. if tray_now == 254:
  7858. loaded_tray = "external spool"
  7859. elif (rack := layout.rack_slot(tray_now)) is not None:
  7860. loaded_tray = f"{unit_label(rack[0], layout.ams_type(rack[0]))} slot {rack[1] + 1}"
  7861. elif tray_now >= 0 and tray_now < 128:
  7862. loaded_ams, loaded_slot = layout.slot_key(tray_now)
  7863. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7864. else:
  7865. loaded_tray = f"tray {tray_now}"
  7866. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7867. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7868. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7869. wire_ams_id, wire_slot_id = ams_id, tray_id
  7870. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7871. wire_ams_id, wire_slot_id, _ = _a2l
  7872. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7873. refused = await self._send_rfid_command(
  7874. {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id}
  7875. )
  7876. if refused is None:
  7877. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7878. # M620 R only for what Bambu Studio sends it to: a model older than the
  7879. # newer protocol, on one of the four regular AMS units (the only ones
  7880. # with a legacy global tray index). Never during a job either: a
  7881. # gcode_line would be executed inside the running print.
  7882. from backend.app.utils.printer_models import uses_legacy_rfid_refresh
  7883. if (
  7884. not 0 <= wire_ams_id <= 3
  7885. or not uses_legacy_rfid_refresh(self.model)
  7886. or self.state.state in _ACTIVE_PRINT_STATES
  7887. ):
  7888. return False, f"Printer refused the RFID refresh: {refused}"
  7889. logger.info(
  7890. "[%s] ams_get_rfid refused (%s), falling back to M620 R%s",
  7891. self.serial_number,
  7892. refused,
  7893. legacy_tray_index(wire_ams_id, wire_slot_id),
  7894. )
  7895. legacy_refused = await self._send_rfid_command(
  7896. {"command": "gcode_line", "param": f"M620 R{legacy_tray_index(wire_ams_id, wire_slot_id)}\n"}
  7897. )
  7898. if legacy_refused is None:
  7899. return True, f"Refreshing AMS {ams_id} tray {tray_id} (legacy command)"
  7900. return False, f"Printer refused the RFID refresh: {legacy_refused}"
  7901. # The answer to ams_get_rfid was measured at 11ms in #3206's capture.
  7902. _rfid_ack_timeout: float = 3.0
  7903. async def _send_rfid_command(self, print_command: dict) -> str | None:
  7904. """Publish one RFID refresh command and wait for the printer's answer.
  7905. Returns the printer's reason when it answered ``FAIL``, else None.
  7906. No answer within ``_rfid_ack_timeout`` counts as accepted, because
  7907. silence is not evidence of refusal and older firmware may not answer
  7908. at all.
  7909. """
  7910. timeout = self._rfid_ack_timeout
  7911. self._sequence_id += 1
  7912. seq_id = str(self._sequence_id)
  7913. command = {"print": {**print_command, "sequence_id": seq_id}}
  7914. self._pending_rfid_acks[seq_id] = None
  7915. try:
  7916. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7917. deadline = time.monotonic() + timeout
  7918. while time.monotonic() < deadline:
  7919. ack = self._pending_rfid_acks.get(seq_id)
  7920. if ack is not None:
  7921. if str(ack.get("result", "")).lower() == "fail":
  7922. return str(ack.get("reason", "") or "") or "printer reported failure"
  7923. return None
  7924. await asyncio.sleep(0.05)
  7925. finally:
  7926. self._pending_rfid_acks.pop(seq_id, None)
  7927. logger.info(
  7928. "[%s] No answer to %s seq=%s within %.1fs", self.serial_number, print_command["command"], seq_id, timeout
  7929. )
  7930. return None
  7931. def ams_set_filament_setting(
  7932. self,
  7933. ams_id: int,
  7934. tray_id: int,
  7935. tray_info_idx: str,
  7936. tray_type: str,
  7937. tray_sub_brands: str,
  7938. tray_color: str,
  7939. nozzle_temp_min: int,
  7940. nozzle_temp_max: int,
  7941. setting_id: str = "",
  7942. ) -> bool:
  7943. """Set AMS tray filament settings (type, color, temperature).
  7944. Note: K value is set separately via extrusion_cali_sel command.
  7945. Args:
  7946. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7947. tray_id: Tray ID within the AMS (0-3)
  7948. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7949. tray_type: Filament type (e.g., "PLA", "PETG")
  7950. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  7951. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  7952. nozzle_temp_min: Minimum nozzle temperature
  7953. nozzle_temp_max: Maximum nozzle temperature
  7954. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  7955. Returns:
  7956. True if command was sent, False otherwise
  7957. """
  7958. if not self._client or not self.state.connected:
  7959. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  7960. return False
  7961. # Calculate mqtt IDs based on AMS type.
  7962. # External-spool convention verified against a BambuStudio→X1C packet capture
  7963. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  7964. # *global* tray index in `tray_id`, not a local position within the virtual
  7965. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  7966. # is what the original code was matching — but the request and response
  7967. # use different semantics for that field. Sending `tray_id: 0` is what
  7968. # the P1S in #1279 rejected with `result: "fail"`.
  7969. if ams_id == 255:
  7970. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7971. if len(vt_tray) > 1:
  7972. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7973. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7974. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7975. # captured Studio→H2D exchange confirms the correct value.
  7976. mqtt_ams_id = external_tray_id(tray_id)
  7977. mqtt_tray_id = 0
  7978. else:
  7979. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7980. mqtt_ams_id = 255
  7981. mqtt_tray_id = 254
  7982. slot_id = 0
  7983. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7984. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7985. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7986. mqtt_ams_id, slot_id, _ = _a2l
  7987. mqtt_tray_id = slot_id
  7988. elif self._rack_ams_type(ams_id) is not None:
  7989. # AMS 3H: unit 32 with its slot 0-8 in tray_id and slot_id (verified).
  7990. mqtt_ams_id = ams_id
  7991. mqtt_tray_id = slot_id = tray_id
  7992. elif ams_id <= 3:
  7993. mqtt_ams_id = ams_id
  7994. mqtt_tray_id = tray_id
  7995. slot_id = tray_id
  7996. else:
  7997. # AMS-HT: single tray per unit
  7998. mqtt_ams_id = ams_id
  7999. mqtt_tray_id = tray_id
  8000. slot_id = 0
  8001. command = {
  8002. "print": {
  8003. "command": "ams_filament_setting",
  8004. "ams_id": mqtt_ams_id,
  8005. "tray_id": mqtt_tray_id,
  8006. "slot_id": slot_id,
  8007. "tray_info_idx": tray_info_idx,
  8008. "tray_type": tray_type,
  8009. "tray_sub_brands": tray_sub_brands,
  8010. # UPPERCASE, always: lowercase hex is silently read as zeros by
  8011. # P1S firmware and acknowledged as a success (#2987).
  8012. "tray_color": wire_tray_color(tray_color),
  8013. "nozzle_temp_min": nozzle_temp_min,
  8014. "nozzle_temp_max": nozzle_temp_max,
  8015. "sequence_id": "0",
  8016. }
  8017. }
  8018. # Include setting_id if provided (helps slicer show correct profile)
  8019. if setting_id:
  8020. command["print"]["setting_id"] = setting_id
  8021. command_json = json.dumps(command)
  8022. logger.info(
  8023. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  8024. )
  8025. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  8026. self._client.publish(self.topic_publish, command_json, qos=1)
  8027. self._last_ams_cmd_time = time.monotonic()
  8028. return True
  8029. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  8030. """Reset an AMS slot to empty/unconfigured state.
  8031. Args:
  8032. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  8033. tray_id: Tray ID within the AMS (0-3)
  8034. Returns:
  8035. True if command was sent, False otherwise
  8036. """
  8037. if not self._client or not self.state.connected:
  8038. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  8039. return False
  8040. # Calculate mqtt IDs based on AMS type — same convention as
  8041. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  8042. if ams_id == 255:
  8043. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8044. if len(vt_tray) > 1:
  8045. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8046. mqtt_ams_id = external_tray_id(tray_id)
  8047. mqtt_tray_id = 0
  8048. else:
  8049. # Single external slot (X1C, P1S, A1): global tray_id=254.
  8050. mqtt_ams_id = 255
  8051. mqtt_tray_id = 254
  8052. slot_id = 0
  8053. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8054. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  8055. mqtt_ams_id, slot_id, _ = _a2l
  8056. mqtt_tray_id = slot_id
  8057. elif self._rack_ams_type(ams_id) is not None:
  8058. # AMS 3H: unit 32 with its slot 0-8 (see ams_set_filament_setting).
  8059. mqtt_ams_id = ams_id
  8060. mqtt_tray_id = slot_id = tray_id
  8061. elif ams_id <= 3:
  8062. mqtt_ams_id = ams_id
  8063. mqtt_tray_id = tray_id
  8064. slot_id = tray_id
  8065. else:
  8066. # AMS-HT: single tray per unit
  8067. mqtt_ams_id = ams_id
  8068. mqtt_tray_id = tray_id
  8069. slot_id = 0
  8070. command = {
  8071. "print": {
  8072. "command": "ams_filament_setting",
  8073. "ams_id": mqtt_ams_id,
  8074. "tray_id": mqtt_tray_id,
  8075. "slot_id": slot_id,
  8076. "tray_info_idx": "",
  8077. "tray_type": "",
  8078. "tray_sub_brands": "",
  8079. "tray_color": "00000000",
  8080. "nozzle_temp_min": 0,
  8081. "nozzle_temp_max": 0,
  8082. "sequence_id": "0",
  8083. }
  8084. }
  8085. command_json = json.dumps(command)
  8086. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  8087. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  8088. self._client.publish(self.topic_publish, command_json, qos=1)
  8089. self._last_ams_cmd_time = time.monotonic()
  8090. return True
  8091. def extrusion_cali_sel(
  8092. self,
  8093. ams_id: int,
  8094. tray_id: int,
  8095. cali_idx: int,
  8096. filament_id: str,
  8097. nozzle_diameter: str = "0.4",
  8098. ) -> bool:
  8099. """Set calibration profile (K value) for an AMS slot.
  8100. This command selects a K profile from the printer's calibration list.
  8101. Use cali_idx=-1 to use the default K value (0.020).
  8102. Note: Do NOT send setting_id in this command — BambuStudio never includes
  8103. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  8104. Args:
  8105. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  8106. tray_id: Tray ID within the AMS (0-3)
  8107. cali_idx: Calibration profile index (-1 for default)
  8108. filament_id: Filament preset ID (same as tray_info_idx)
  8109. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8110. Returns:
  8111. True if command was sent, False otherwise
  8112. """
  8113. if not self._client or not self.state.connected:
  8114. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  8115. return False
  8116. # Calculate mqtt IDs based on AMS type.
  8117. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  8118. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  8119. if ams_id == 255:
  8120. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  8121. # ams_filament_setting which uses LOCAL tray_id=0).
  8122. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8123. if len(vt_tray) > 1:
  8124. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8125. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  8126. mqtt_ams_id = external_tray_id(tray_id)
  8127. mqtt_tray_id = external_tray_id(tray_id)
  8128. else:
  8129. # Single external slot (X1C, P1S, A1): global tray_id=254
  8130. mqtt_ams_id = 254
  8131. mqtt_tray_id = 254
  8132. slot_id = 0
  8133. elif self._rack_ams_type(ams_id) is not None:
  8134. # AMS 3H: unit 32, slot k in tray_id and slot_id ({32, 8, 8} verified).
  8135. mqtt_ams_id = ams_id
  8136. mqtt_tray_id = slot_id = tray_id
  8137. elif ams_id <= 3:
  8138. mqtt_ams_id = ams_id
  8139. mqtt_tray_id = legacy_tray_index(ams_id, tray_id)
  8140. slot_id = tray_id
  8141. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8142. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  8143. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  8144. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  8145. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  8146. elif is_ams_ht_id(ams_id):
  8147. mqtt_ams_id = ams_id
  8148. mqtt_tray_id = tray_id
  8149. slot_id = 0
  8150. else:
  8151. mqtt_ams_id = ams_id
  8152. mqtt_tray_id = tray_id
  8153. slot_id = 0
  8154. command = {
  8155. "print": {
  8156. "command": "extrusion_cali_sel",
  8157. "cali_idx": cali_idx,
  8158. "filament_id": filament_id,
  8159. "nozzle_diameter": nozzle_diameter,
  8160. "ams_id": mqtt_ams_id,
  8161. "tray_id": mqtt_tray_id,
  8162. "slot_id": slot_id,
  8163. "sequence_id": "0",
  8164. }
  8165. }
  8166. command_json = json.dumps(command)
  8167. logger.info(
  8168. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  8169. )
  8170. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  8171. self._client.publish(self.topic_publish, command_json, qos=1)
  8172. return True
  8173. def extrusion_cali_set(
  8174. self,
  8175. tray_id: int,
  8176. k_value: float,
  8177. nozzle_diameter: str = "0.4",
  8178. nozzle_temp: int = 220,
  8179. filament_id: str = "",
  8180. setting_id: str = "",
  8181. name: str = "",
  8182. cali_idx: int = -1,
  8183. ) -> bool:
  8184. """Directly set K value (pressure advance) for a tray.
  8185. Uses the filaments array format required by current firmware.
  8186. Args:
  8187. tray_id: Global tray ID (ams_id * 4 + slot)
  8188. k_value: Pressure advance K value (e.g., 0.020)
  8189. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8190. nozzle_temp: Nozzle temperature for calibration reference
  8191. filament_id: Filament preset ID (e.g., "GFA02")
  8192. setting_id: Setting ID (e.g., "GFSA02_07")
  8193. name: Profile display name
  8194. cali_idx: Calibration index (-1 for new)
  8195. Returns:
  8196. True if command was sent, False otherwise
  8197. """
  8198. if not self._client or not self.state.connected:
  8199. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  8200. return False
  8201. # Was reusing the previous command's id — harmless while nothing
  8202. # correlated on it, but the printer echoes sequence_id back and the
  8203. # K-profile write path now matches acks by it (#2718).
  8204. self._sequence_id += 1
  8205. nozzle_id = f"HS00-{nozzle_diameter}"
  8206. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  8207. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  8208. # stays 0 (hardcoded, as for every other unit here).
  8209. wire_tray_id = tray_id
  8210. if (
  8211. 0 <= tray_id <= 253
  8212. and (_a2l := a2l_lite_wire_ids(self.tray_layout.slot_key(tray_id)[0], tray_id)) is not None
  8213. ):
  8214. wire_tray_id = _a2l[2]
  8215. filament_entry = {
  8216. "ams_id": 0,
  8217. "cali_idx": cali_idx,
  8218. "extruder_id": 0,
  8219. "filament_id": filament_id,
  8220. "k_value": f"{k_value:.6f}",
  8221. "n_coef": "1.400000",
  8222. "name": name,
  8223. "nozzle_diameter": nozzle_diameter,
  8224. "nozzle_id": nozzle_id,
  8225. "setting_id": setting_id,
  8226. "tray_id": wire_tray_id,
  8227. }
  8228. command = {
  8229. "print": {
  8230. "command": "extrusion_cali_set",
  8231. "filaments": [filament_entry],
  8232. "nozzle_diameter": nozzle_diameter,
  8233. "sequence_id": str(self._sequence_id),
  8234. }
  8235. }
  8236. command_json = json.dumps(command)
  8237. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  8238. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  8239. self._client.publish(self.topic_publish, command_json, qos=1)
  8240. return True
  8241. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  8242. """Dispatch the user's choice from the HMS-error modal as a printer command.
  8243. Args:
  8244. print_error: Canonical hex identifier for the fault — 8 chars for the
  8245. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  8246. (HMSError.full_code). Carried through unchanged from the route.
  8247. Converted to its DECIMAL string form for the `ignore` /
  8248. `idle_ignore` commands' `err` field, which is what the firmware
  8249. actually compares against the active fault. The pre-#1869
  8250. hex-string `err` was silently rejected because the firmware was
  8251. being asked to match `"05008051"` against int 0x05008051
  8252. (= 83918929 decimal) — see BambuStudio's
  8253. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  8254. `std::to_string(int m_error_code)`.
  8255. action: One of HMSAction's string values.
  8256. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  8257. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  8258. shapes; empty string is the no-job-id sentinel.
  8259. Returns False when the MQTT client is offline or when `action` is unknown
  8260. so the route surfaces it as a 4xx rather than a silent no-op.
  8261. """
  8262. if not self._client or not self.state.connected:
  8263. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  8264. return False
  8265. # Always re-push the full state after a command so the modal's underlying
  8266. # status query reflects the new error list (or absence) on the next tick.
  8267. def publish(payload: dict):
  8268. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  8269. self._client.publish(
  8270. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  8271. )
  8272. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  8273. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  8274. # every command_hms_* call). Our route hands us the hex string —
  8275. # convert. Falls back to the raw input if it's not parseable so the
  8276. # firmware can reject it and the route can surface 502 instead of us
  8277. # raising ValueError mid-dispatch.
  8278. try:
  8279. err_decimal = str(int(print_error, 16))
  8280. except ValueError:
  8281. err_decimal = print_error
  8282. def hms_resume():
  8283. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  8284. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  8285. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  8286. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  8287. # shape historically because it works, and changing it without a
  8288. # field test risks regressing a path that the user has confirmed.
  8289. publish(
  8290. {
  8291. "print": {
  8292. "command": "resume",
  8293. "param": "",
  8294. "sequence_id": "0",
  8295. }
  8296. }
  8297. )
  8298. def hms_stop():
  8299. # Same as hms_resume — plain shape, confirmed working by the user
  8300. # for "Stop Printing".
  8301. publish(
  8302. {
  8303. "print": {
  8304. "command": "stop",
  8305. "param": "",
  8306. "sequence_id": "0",
  8307. }
  8308. }
  8309. )
  8310. def hms_ignore_command():
  8311. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  8312. # what the "Ignore this and Resume" button actually publishes.
  8313. # Distinct from `idle_ignore`: this command has the firmware
  8314. # suppress the next re-check of the named fault AND resume the
  8315. # paused print in a single operation. The previous Bambuddy code
  8316. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  8317. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  8318. # the problem, re-check normally" so the firmware re-detected the
  8319. # wrong plate and re-paused with the same code (#1869).
  8320. #
  8321. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  8322. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  8323. # variant of "don't remind next time" lives on `idle_ignore`'s
  8324. # type=1, not as a separate ignore shape.
  8325. publish(
  8326. {
  8327. "print": {
  8328. "command": "ignore",
  8329. "err": err_decimal,
  8330. "param": "reserve",
  8331. "job_id": job_id or "",
  8332. "sequence_id": "0",
  8333. }
  8334. }
  8335. )
  8336. def hms_idle_ignore(persistent: bool = False):
  8337. # `idle_ignore` is BambuStudio's "dismiss this warning without
  8338. # resuming" command for non-pause warnings — what
  8339. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  8340. # type=0 dismisses once, type=1 suppresses the same warning
  8341. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  8342. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  8343. # NOT via the resume-bearing `ignore` command.
  8344. publish(
  8345. {
  8346. "print": {
  8347. "command": "idle_ignore",
  8348. "err": err_decimal,
  8349. "type": 1 if persistent else 0,
  8350. "sequence_id": "0",
  8351. }
  8352. }
  8353. )
  8354. def ams_control(param: str):
  8355. publish(
  8356. {
  8357. "print": {
  8358. "command": "ams_control",
  8359. "param": param,
  8360. "sequence_id": "0",
  8361. }
  8362. }
  8363. )
  8364. def clean_print_error():
  8365. # Matches the existing `clear_hms_errors` shape — Bambu does not
  8366. # expect `print_error` in the body; the command clears whatever
  8367. # error dialog is currently active on the printer.
  8368. publish(
  8369. {
  8370. "print": {
  8371. "command": "clean_print_error",
  8372. "sequence_id": "0",
  8373. }
  8374. }
  8375. )
  8376. def uiop_close():
  8377. # `err` is the 8-char hex short code (already a string from the
  8378. # frontend), uppercased for consistency with how BambuStudio sends it.
  8379. publish(
  8380. {
  8381. "system": {
  8382. "command": "uiop",
  8383. "name": "print_error",
  8384. "action": "close",
  8385. "source": 1,
  8386. "type": "dialog",
  8387. "err": print_error.upper(),
  8388. "sequence_id": "0",
  8389. }
  8390. }
  8391. )
  8392. match action:
  8393. case (
  8394. HMSAction.RESUME_PRINTING
  8395. | HMSAction.RESUME_PRINTING_DEFECTS
  8396. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  8397. | HMSAction.PROBLEM_SOLVED_RESUME
  8398. | HMSAction.FILAMENT_LOAD_RESUME
  8399. | HMSAction.PROCEED
  8400. ):
  8401. hms_resume()
  8402. case HMSAction.STOP_PRINTING:
  8403. hms_stop()
  8404. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  8405. # All three buttons map to BambuStudio's `command_hms_ignore`
  8406. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  8407. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  8408. # responsibility — the wire shape is identical.
  8409. hms_ignore_command()
  8410. case HMSAction.NO_REMINDER_NEXT_TIME:
  8411. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  8412. # `command_hms_idle_ignore` with type=0
  8413. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  8414. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  8415. # dismisses the dialog.
  8416. hms_idle_ignore(persistent=False)
  8417. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  8418. ams_control("done")
  8419. case (
  8420. HMSAction.RETRY_FILAMENT_EXTRUDED
  8421. | HMSAction.CONTINUE
  8422. | HMSAction.RETRY_PROBLEM_SOLVED
  8423. | HMSAction.DBL_CHECK_RETRY
  8424. ):
  8425. ams_control("resume")
  8426. case HMSAction.ABORT:
  8427. ams_control("abort")
  8428. case HMSAction.OK_BUTTON:
  8429. clean_print_error()
  8430. case HMSAction.DBL_CHECK_OK:
  8431. clean_print_error()
  8432. uiop_close()
  8433. case HMSAction.DBL_CHECK_RESUME:
  8434. # Plain resume — not HMS-aware, no err/job_id.
  8435. publish(
  8436. {
  8437. "print": {
  8438. "command": "resume",
  8439. "param": "",
  8440. "sequence_id": "0",
  8441. }
  8442. }
  8443. )
  8444. case HMSAction.REFRESH_NOZZLE:
  8445. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  8446. case HMSAction.TURN_OFF_FIRE_ALARM:
  8447. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  8448. case HMSAction.STOP_DRYING:
  8449. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  8450. case HMSAction.DISABLE_PURIFICATION:
  8451. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  8452. case (
  8453. HMSAction.CHECK_ASSISTANT
  8454. | HMSAction.JUMP_TO_LIVEVIEW
  8455. | HMSAction.OK_JUMP_RACK
  8456. | HMSAction.REMOVE_CLOSE_BTN
  8457. | HMSAction.LOAD_VIRTUAL_TRAY
  8458. | HMSAction.CANCLE
  8459. | HMSAction.DBL_CHECK_CANCEL
  8460. ):
  8461. # UI-only actions — the printer's own screen handles these; the
  8462. # modal still surfaces them so the user has parity with Studio.
  8463. pass
  8464. case _:
  8465. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  8466. return False
  8467. return True