bambu_mqtt.py 413 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225
  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 describe_fault
  22. from backend.app.utils.ams_drying import ACTIVE_DRY_STATUSES
  23. logger = logging.getLogger(__name__)
  24. # AMS module name prefixes used in get_version responses.
  25. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  26. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  27. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  28. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  29. _AMS_MODULE_PREFIXES = ("ams/", "n3f/", "n3s/")
  30. # gcode_state values that mean the printer is not idle and must not be handed a
  31. # new start-print (#2598). The firmware rejects a project_file while busy with
  32. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  33. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  34. # are valid start targets and are deliberately excluded. Mirrors
  35. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  36. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  37. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  38. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  39. # ended the cycle on schedule or aborted it. More than this many minutes still on
  40. # the clock means it was cut short, and the firmware's own reason codes are worth
  41. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  42. # left), and the log said only "drying complete", so the report carried no
  43. # evidence of why. The margin absorbs a stale last observation between AMS
  44. # pushes; it is not a judgement about how short "short" is.
  45. _EARLY_DRY_END_MINUTES = 5
  46. # CONNACK reason codes that mean the printer actively refused our credentials,
  47. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  48. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  49. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  50. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  51. # code (or, on some firmware, the serial used as the username) is wrong.
  52. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  53. # Short, stable slugs recorded on the client and surfaced to the connection
  54. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  55. # frontend picks a localized message key off these.
  56. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  57. CONNECT_ERROR_REFUSED = "refused"
  58. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  59. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  60. OrcaSlicer reads bit 18 of the hex string via
  61. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  62. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  63. that doesn't yield a clean integer so downstream consumers preserve today's
  64. behaviour rather than treating "absent" as "OFF".
  65. """
  66. if not isinstance(cfg_raw, str) or not cfg_raw:
  67. return None
  68. try:
  69. return bool((int(cfg_raw, 16) >> 18) & 1)
  70. except ValueError:
  71. return None
  72. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  73. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  74. # firmware is internally inconsistent about it:
  75. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  76. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  77. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  78. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  79. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  80. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  81. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  82. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  83. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  84. A2L_LITE_PHYSICAL_AMS_ID = 16
  85. A2L_LITE_NORMALIZED_AMS_ID = 6
  86. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  87. def normalize_am_unit_id(ams_id: int) -> int:
  88. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  89. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  90. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  91. through untouched.
  92. """
  93. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  94. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  95. """Translate a normalised A2L slot back to the physical wire form.
  96. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  97. (normalised id 6), else ``None`` for every other unit.
  98. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  99. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  100. confirmed by capture: the physical **global** tray value some commands put on
  101. the wire (load `target`, extrusion_cali `tray_id`) — we extrapolate it as
  102. 16*4+slot = 64-67 to stay consistent with the physical unit id. This is the
  103. single unverified encoding; a BambuStudio->A2L capture of a load or cali
  104. command would settle it, and it lives only here.
  105. """
  106. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  107. return None
  108. local_slot = tray_id % 4
  109. return (
  110. A2L_LITE_PHYSICAL_AMS_ID,
  111. local_slot,
  112. A2L_LITE_PHYSICAL_AMS_ID * 4 + local_slot,
  113. )
  114. def apply_tray_exist_bits(
  115. units: list,
  116. tray_exist_bits_str: str | int | None,
  117. *,
  118. power_on_flag: bool = True,
  119. log_label: str | None = None,
  120. annotate_exists: bool = False,
  121. ) -> int:
  122. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  123. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  124. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  125. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  126. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  127. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  128. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  129. instead of guessing from payload shape (#1322, #147).
  130. Two callers share this helper to keep their views consistent:
  131. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  132. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  133. facing push_status (#1726 — without this the VP would forward stale
  134. per-tray fields for empty slots, and BambuStudio's Sync would render
  135. phantom loaded slots).
  136. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  137. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  138. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  139. so spool removal is detected without requiring a manual reconnect.
  140. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  141. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  142. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  143. authoritative empty signal for the HT — the only working clear path, since
  144. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  145. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  146. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  147. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  148. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  149. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  150. the raw physical id 16 get the same bit base as callers holding the
  151. normalised 6 (#2697).
  152. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  153. way). Ints are tolerated for defensive symmetry but typically not seen
  154. on the wire. ``None`` / empty / unparseable → no-op.
  155. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  156. every processed slot. This is firmware's authoritative "spool physically
  157. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  158. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  159. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  160. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  161. leaves it False so the ``exists`` key never reaches the slicer wire format.
  162. Mutates ``units`` in place. Returns the number of slots cleared.
  163. """
  164. if not tray_exist_bits_str:
  165. return 0
  166. try:
  167. if isinstance(tray_exist_bits_str, int):
  168. tray_exist_bits = tray_exist_bits_str
  169. else:
  170. tray_exist_bits = int(tray_exist_bits_str, 16)
  171. except (ValueError, TypeError):
  172. return 0
  173. if tray_exist_bits == 0 and not power_on_flag:
  174. return 0
  175. if not isinstance(units, list):
  176. return 0
  177. cleared = 0
  178. for ams_unit in units:
  179. if not isinstance(ams_unit, dict):
  180. continue
  181. ams_id_raw = ams_unit.get("id")
  182. if ams_id_raw is None:
  183. continue
  184. try:
  185. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  186. except (ValueError, TypeError):
  187. continue
  188. if not isinstance(ams_id, int):
  189. continue
  190. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  191. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  192. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  193. # the physical 16. Both mean bit base 24, so fold them together here
  194. # rather than relying on every caller to normalise first — reading 16 as
  195. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  196. ams_id = normalize_am_unit_id(ams_id)
  197. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  198. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  199. # Anything outside those ranges has no known bit layout — don't guess it.
  200. is_ht = 128 <= ams_id <= 135
  201. if not is_ht and not (0 <= ams_id <= 15):
  202. continue
  203. for tray in ams_unit.get("tray", []):
  204. if not isinstance(tray, dict):
  205. continue
  206. tray_id_raw = tray.get("id")
  207. if tray_id_raw is None:
  208. continue
  209. try:
  210. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  211. except (ValueError, TypeError):
  212. continue
  213. if not isinstance(tray_id, int):
  214. continue
  215. global_bit = (16 + (ams_id - 128)) if is_ht else (ams_id * 4 + tray_id)
  216. slot_exists = (tray_exist_bits >> global_bit) & 1
  217. if annotate_exists:
  218. tray["exists"] = bool(slot_exists)
  219. if slot_exists:
  220. continue
  221. tray["state"] = 9
  222. if tray.get("tray_type"):
  223. if log_label:
  224. logger.debug(
  225. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  226. f"(tray_exist_bits bit {global_bit} = 0)"
  227. )
  228. tray["tray_type"] = ""
  229. tray["tray_sub_brands"] = ""
  230. tray["tray_color"] = ""
  231. tray["tray_id_name"] = ""
  232. tray["tag_uid"] = "0000000000000000"
  233. tray["tray_uuid"] = "00000000000000000000000000000000"
  234. tray["tray_info_idx"] = ""
  235. tray["remain"] = 0
  236. cleared += 1
  237. return cleared
  238. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  239. #
  240. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  241. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  242. # rack position is never mistakable for the nozzle on the other carriage.
  243. #
  244. # Extruder indices are a different namespace that happens to overlap these
  245. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  246. # Nothing below may pass a value from one namespace to the other untranslated;
  247. # doing exactly that is what #2800 was.
  248. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  249. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  250. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  251. #
  252. # Briefly changed to the plate's own slot count on the strength of a single
  253. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  254. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  255. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  256. # a calibration job, so the length varies with whatever Studio is doing rather
  257. # than with the filament count -- which makes it the wrong thing to derive.
  258. _RACK_WIRE_SLOTS = 32
  259. # The two carriages, as extruder indices in the form the queue stores (already
  260. # translated through the file's physical_extruder_map).
  261. #
  262. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  263. #
  264. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  265. # extruder 1, AMS 1 and 2 feed extruder 0;
  266. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  267. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  268. # and that print completed. So extruder 1 is the fixed hotend and extruder
  269. # 0 is the rack;
  270. # - our own constants were internally inconsistent about it: physical nozzle
  271. # id N sits on extruder N (see the L/R split in PrintersPage), and
  272. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  273. # extruder index of 0.
  274. #
  275. # These were the other way round until then, which is what dispatched a plate
  276. # to the carriage that had not been levelled and printed its first layer in
  277. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  278. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  279. # which *wire* worked, and the extruder indices were only inferred from it by
  280. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  281. # wire result stands; the inference from it did not.
  282. _FIXED_EXTRUDER_ID = 1
  283. _RACK_EXTRUDER_ID = 0
  284. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  285. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  286. # outright, which would not start the job at all. Native BambuStudio captures
  287. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  288. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  289. _FIXED_NOZZLE_ID = 1
  290. def resolve_rack_nozzle_mapping(
  291. slot_extruders: list[int],
  292. rack_nozzle_id: int | None,
  293. ) -> list[int] | None:
  294. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  295. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  296. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  297. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  298. reports as live.
  299. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  300. when the mapping cannot be resolved with confidence -- in which case the
  301. caller omits the field entirely and the firmware falls back to its own
  302. nozzle pick, exactly as it did before this translation existed. Omitting
  303. is deliberately the failure mode: a *wrong* physical ID makes the printer
  304. level with one nozzle and print with another several millimetres off the
  305. bed, which is far worse than letting the firmware choose.
  306. Returns None specifically when:
  307. - a slot needs the rack but the printer has not reported a live rack
  308. position (mid-swap, or a stale connection);
  309. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  310. for a plate sliced for the fixed hotend only (#2800 capture), so this
  311. matches it rather than naming a nozzle it does not have to name;
  312. - a slot names a carriage that is neither of the two an H2C has, which
  313. means the file was mapped for a machine this translation does not model;
  314. - the plate needs more slots than the wire format carries;
  315. - the input is not a list of whole numbers.
  316. Total by construction: it raises nothing, because the only caller is
  317. building an MQTT print command with no exception handler above it and the
  318. queue item has already been committed as `printing` by then. An
  319. unparseable input has to degrade to "let the firmware pick", not to a job
  320. wedged in a state no print will ever leave.
  321. """
  322. if not isinstance(slot_extruders, list) or not slot_extruders:
  323. return None
  324. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  325. return None
  326. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  327. return None
  328. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  329. return None
  330. # Normalise first so the checks below, and the values that reach the wire,
  331. # are known ints. bool is an int subclass and would otherwise serialise as
  332. # a JSON `true`; None means "slot not printed" and is folded into -1.
  333. normalised: list[int] = []
  334. for extruder in slot_extruders:
  335. if extruder is None:
  336. normalised.append(-1)
  337. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  338. normalised.append(extruder)
  339. else:
  340. return None
  341. if _RACK_EXTRUDER_ID not in normalised:
  342. return None
  343. wire = [-1] * _RACK_WIRE_SLOTS
  344. for index, extruder in enumerate(normalised):
  345. if extruder < 0:
  346. continue
  347. if extruder == _RACK_EXTRUDER_ID:
  348. wire[index] = rack_nozzle_id
  349. elif extruder == _FIXED_EXTRUDER_ID:
  350. wire[index] = _FIXED_NOZZLE_ID
  351. else:
  352. # An H2C has these two carriages and no others. A third index is a
  353. # file mapped for something else, and forwarding it raw would name
  354. # a physical nozzle by an index that does not identify one.
  355. return None
  356. return wire
  357. # A rack position as the operator counts it (and as the printer card and
  358. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  359. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  360. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  361. _RACK_POSITION_BASE = 15
  362. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  363. def rack_position_to_nozzle_id(position: int) -> int | None:
  364. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  365. if not isinstance(position, int) or isinstance(position, bool):
  366. return None
  367. if position not in RACK_POSITIONS:
  368. return None
  369. return _RACK_POSITION_BASE + position
  370. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  371. """Whether a live rack slot can print a group wanting this nozzle.
  372. Mirrors the filter BambuStudio applies in its own picker: the position has
  373. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  374. and flow type. A mismatch here is not cosmetic -- it is the printer being
  375. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  376. """
  377. if not isinstance(slot, dict):
  378. return False
  379. slot_diameter = str(slot.get("diameter") or "").strip()
  380. slot_type = str(slot.get("type") or "").strip()
  381. if not slot_diameter and not slot_type:
  382. return False # empty position
  383. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  384. # the printer does not.
  385. try:
  386. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  387. return False
  388. except (TypeError, ValueError):
  389. return False
  390. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  391. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  392. # printer that omits the code is not thereby ruled ineligible.
  393. wanted = volume_type.strip().lower()
  394. if wanted and slot_type:
  395. is_high_flow = slot_type.upper().startswith("HH")
  396. if wanted.startswith("high flow") != is_high_flow:
  397. return False
  398. return True
  399. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  400. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  401. _RACK_CARRIAGE_NOZZLE_ID = 0
  402. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  403. """Live rack contents keyed by 1-based position, mounted nozzle included.
  404. The firmware omits a rack id entirely while that nozzle is picked up onto
  405. the carriage (#943) -- it does not send an empty placeholder. Taking the
  406. omission at face value would rule the nozzle ineligible for the very print
  407. that wants it, and it is the single most likely position to be picked,
  408. because it is the one the last print left mounted.
  409. The absent id is recoverable only when exactly one is missing: rack ids are
  410. fixed at 16..21, so a single gap alongside a loaded carriage is that
  411. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  412. with four nozzles in six positions looks the same -- so those stay absent
  413. and the caller treats them as empty.
  414. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  415. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  416. """
  417. by_position: dict[int, dict] = {}
  418. carriage: dict | None = None
  419. for slot in rack_slots or []:
  420. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  421. continue
  422. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  423. carriage = slot
  424. continue
  425. position = slot["id"] - _RACK_POSITION_BASE
  426. if position in RACK_POSITIONS:
  427. by_position[position] = slot
  428. missing = [position for position in RACK_POSITIONS if position not in by_position]
  429. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  430. by_position[missing[0]] = carriage
  431. return by_position
  432. def resolve_rack_plan_mapping(
  433. slot_groups: list[int],
  434. groups: dict[int, dict],
  435. choice: dict[int, int],
  436. rack_slots: list[dict],
  437. ) -> tuple[list[int] | None, str | None]:
  438. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  439. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  440. That one can only name the single live rack position, so a plate wanting a
  441. different hotend per group is unresolvable to it. Here each group carries
  442. its own position, which is the operator's choice (#1784) -- the 3MF states
  443. it nowhere, proven by dispatching one plate twice with different picks and
  444. diffing the two files down to float noise.
  445. ``choice`` may be partial or empty; groups it does not name are assigned
  446. from the live rack, preferring a position already loaded with the group's
  447. own filament colour and otherwise taking the lowest eligible one.
  448. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  449. is a sentence naming what could not be satisfied. The caller decides what
  450. to do with a failure, and the two cases differ: a stale *explicit* pick
  451. should stop the print, while a failed auto-assignment should degrade to
  452. letting the firmware choose, exactly as before this existed.
  453. """
  454. if not isinstance(slot_groups, list) or not slot_groups:
  455. return None, "the plate lists no filament slots"
  456. if len(slot_groups) > _RACK_WIRE_SLOTS:
  457. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  458. by_position = _rack_by_position(rack_slots)
  459. # Assign every rack-bound group a position before building the wire, so a
  460. # group can never be handed one an earlier group already took. Explicit
  461. # picks are placed first: an auto-assignment must yield to them rather than
  462. # claim a position the operator asked for.
  463. assigned: dict[int, int] = {}
  464. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  465. for group_id in rack_group_ids:
  466. position = choice.get(group_id)
  467. if position is None:
  468. continue
  469. group = groups[group_id]
  470. if rack_position_to_nozzle_id(position) is None:
  471. return None, f"rack position {position} does not exist"
  472. if position in assigned.values():
  473. return None, f"rack position {position} is picked for more than one filament group"
  474. slot = by_position.get(position)
  475. if slot is None:
  476. return None, f"the printer reports nothing at rack position {position}"
  477. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  478. return None, (
  479. f"rack position {position} holds a "
  480. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  481. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  482. )
  483. assigned[group_id] = position
  484. for group_id in rack_group_ids:
  485. if group_id in assigned:
  486. continue
  487. group = groups[group_id]
  488. eligible = [
  489. position
  490. for position in RACK_POSITIONS
  491. if position not in assigned.values()
  492. and position in by_position
  493. and _rack_slot_is_eligible(
  494. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  495. )
  496. ]
  497. if not eligible:
  498. return None, (
  499. f"no free rack position holds a {group.get('nozzle_diameter')} "
  500. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  501. )
  502. # Prefer a position already carrying this group's colour: picking it
  503. # means the operator does not have to move filament to make the print
  504. # match what they asked for.
  505. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  506. assigned[group_id] = next(
  507. (
  508. position
  509. for position in eligible
  510. if wanted_colour
  511. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  512. == wanted_colour
  513. ),
  514. eligible[0],
  515. )
  516. wire = [-1] * _RACK_WIRE_SLOTS
  517. for index, group_id in enumerate(slot_groups):
  518. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  519. continue # slot this plate does not print
  520. group = groups.get(group_id)
  521. if group is None:
  522. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  523. if not group.get("on_rack"):
  524. wire[index] = _FIXED_NOZZLE_ID
  525. continue
  526. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  527. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  528. return None, f"filament group {group_id} resolved to no rack position"
  529. wire[index] = nozzle_id
  530. if all(value == -1 for value in wire):
  531. return None, "the plate assigns no filament to a nozzle"
  532. return wire, None
  533. @dataclass
  534. class MQTTLogEntry:
  535. """Log entry for MQTT message debugging."""
  536. timestamp: str
  537. topic: str
  538. direction: str # "in" or "out"
  539. payload: dict
  540. @dataclass
  541. class HMSError:
  542. """Health Management System error from printer."""
  543. code: str
  544. attr: int # Attribute value for constructing wiki URL
  545. module: int
  546. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  547. # The bundled catalogue's sentence for this fault, resolved once here so
  548. # every surface that reports it — the status response, the WebSocket
  549. # broadcast, the completion payload, notifications — says the same thing.
  550. # None when the catalogue does not cover the code; `describe_fault` documents
  551. # the lookup and why the lossy `hms[]` collapse is kept as it was.
  552. # Replaces a `message` field that was never set or read anywhere.
  553. description: str | None = None
  554. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  555. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  556. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  557. # HMSError without explicitly passing actions can't silently land None on the schema
  558. # boundary and raise ValidationError at routes/printers.py response time.
  559. actions: list[str] = field(default_factory=list)
  560. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  561. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  562. job_id: str | None = None
  563. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  564. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  565. # 32-bit `print_error` path. The frontend echoes this back to
  566. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  567. # used to send caused the firmware to silently reject HMS commands on H2C
  568. # (#1830) and on `hms[]`-sourced faults generally.
  569. full_code: str = ""
  570. # HMS short codes the firmware emits during normal user-cancel sequences.
  571. # These aren't faults — they're status echoes that confirm the cancel happened.
  572. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  573. # so they don't drive the printer card's "X problem" badge, the red pip, or
  574. # any other consumer that treats hms_errors as the active-fault list.
  575. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  576. {
  577. "0300_400C", # "The task was canceled."
  578. "0500_400E", # "Printing was cancelled."
  579. }
  580. )
  581. # "MQTT command verification failed" — the printer's authorization/authentication
  582. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  583. # command it could not verify. Queries (get_version, extrusion_cali_get,
  584. # pushall) still answer, so the connection looks perfectly healthy while
  585. # project_file, gcode_line and ams_change_filament are all silently dropped —
  586. # which is exactly how it presents: uploads succeed, the printer echoes our
  587. # subtask_id, then sits at IDLE forever (#2732).
  588. #
  589. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  590. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  591. # "0500_0007", which matches nothing in any catalog.
  592. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  593. @dataclass
  594. class KProfile:
  595. """Pressure advance (K) calibration profile from printer."""
  596. slot_id: int
  597. extruder_id: int
  598. nozzle_id: str
  599. nozzle_diameter: str
  600. filament_id: str
  601. name: str
  602. k_value: str
  603. n_coef: str = "0.000000"
  604. ams_id: int = 0
  605. tray_id: int = -1
  606. setting_id: str | None = None
  607. @dataclass
  608. class NozzleInfo:
  609. """Nozzle hardware configuration."""
  610. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  611. nozzle_diameter: str = "" # e.g., "0.4"
  612. @dataclass
  613. class FilaSwitchState:
  614. """Filament Track Switch (FTS) accessory state.
  615. The FTS is an external accessory that mediates filament routing between an
  616. AMS and the printer's extruders. When installed, the AMS no longer has a
  617. fixed extruder assignment — any slot can be routed to any extruder via the
  618. track switch. Detected from print.device.fila_switch in MQTT.
  619. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  620. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  621. stable, operator-visible relationship — it is set on the printer's "Manual
  622. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  623. Field semantics below are taken from BambuStudio's own parser
  624. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  625. """
  626. installed: bool = False
  627. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  628. # the arrays are ordered B-then-A, which is the opposite of how they read.
  629. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  630. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  631. in_slots: list[int] = field(default_factory=list)
  632. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  633. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  634. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  635. # inlet is currently paired with which outlet is not reported at all.
  636. out_extruders: list[int] = field(default_factory=list)
  637. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  638. info: int = 0 # bit 0 = inlet has filament
  639. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  640. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  641. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  642. one of A/B.
  643. """
  644. index = {"A": 1, "B": 0}.get(inlet.upper())
  645. if index is None or index >= len(self.in_slots):
  646. return None
  647. raw = self.in_slots[index]
  648. if raw < 0:
  649. return None
  650. return (raw >> 8) & 0xFF, raw & 0xFF
  651. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  652. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  653. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  654. # as empty everywhere is strictly safer than reading it as the external spool.
  655. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  656. @dataclass
  657. class ExtruderSlot:
  658. """Which AMS slot an extruder is currently fed from.
  659. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  660. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  661. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  662. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  663. ``state.tray_now`` cannot answer this: it is a single value for the whole
  664. printer, so on a dual-nozzle machine with both hotends loaded it names only
  665. one of them. Unloading a specific slot needs to know which extruder is
  666. holding it, which is what this is for.
  667. """
  668. ams_id: int | None = None
  669. slot_id: int | None = None
  670. has_filament: bool = False
  671. def holds(self, ams_id: int, slot_id: int) -> bool:
  672. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  673. return self.ams_id == ams_id and self.slot_id == slot_id
  674. @dataclass
  675. class PrintOptions:
  676. """AI detection and print options from xcam data."""
  677. # Core AI detectors
  678. spaghetti_detector: bool = False
  679. print_halt: bool = False
  680. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  681. first_layer_inspector: bool = False
  682. printing_monitor: bool = False # AI print quality monitoring
  683. buildplate_marker_detector: bool = False
  684. allow_skip_parts: bool = False
  685. # Additional AI detectors - decoded from cfg bitmask
  686. nozzle_clumping_detector: bool = True
  687. nozzle_clumping_sensitivity: str = "medium"
  688. pileup_detector: bool = True
  689. pileup_sensitivity: str = "medium"
  690. airprint_detector: bool = True
  691. airprint_sensitivity: str = "medium"
  692. auto_recovery_step_loss: bool = True # Uses print.print_option command
  693. filament_tangle_detect: bool = False
  694. @dataclass
  695. class PrinterState:
  696. connected: bool = False
  697. state: str = "unknown"
  698. current_print: str | None = None
  699. subtask_name: str | None = None
  700. progress: float = 0.0
  701. remaining_time: int = 0
  702. layer_num: int = 0
  703. total_layers: int = 0
  704. temperatures: dict = field(default_factory=dict)
  705. raw_data: dict = field(default_factory=dict)
  706. gcode_file: str | None = None
  707. subtask_id: str | None = None
  708. hms_errors: list = field(default_factory=list) # List of HMSError
  709. kprofiles: list = field(default_factory=list) # List of KProfile
  710. sdcard: bool = False # SD card inserted
  711. # Whether the printer has ever actually told us about `sdcard`. Without this
  712. # the default False is indistinguishable from a real "no card", and any
  713. # consumer that treats False as evidence would act on silence — which is how
  714. # a storage gate turns into a regression for every printer whose firmware
  715. # simply doesn't publish the field (#2780).
  716. sdcard_reported: bool = False
  717. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  718. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  719. # whoever sent it (the slicer or us). Bambu states where the sliced file
  720. # went: `ftp://<name>` is external storage, which FTPS serves, while
  721. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  722. #
  723. # Two fields, because the two readers need different guarantees.
  724. # ``current_project_url`` belongs to the print now running and is cleared
  725. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  726. # "unknown" rather than inheriting the previous job's answer. That matters:
  727. # 18% of the print starts in #2780's bundle had no dispatch on the request
  728. # topic at all (touchscreen reprints, restart recovery), and a stale
  729. # internal-storage URL would make those skip an FTPS sweep that could have
  730. # found the file — losing an archive that works today.
  731. #
  732. # ``last_project_url`` is sticky and exists for reporting only: the
  733. # connection diagnostic is usually run *after* the print that prompted it,
  734. # by which point the per-print value is rightly gone.
  735. #
  736. # None means we never saw a dispatch — say nothing, don't guess.
  737. current_project_url: str | None = None
  738. last_project_url: str | None = None
  739. timelapse: bool = False # Timelapse recording active
  740. ipcam: bool = False # Live view / camera streaming enabled
  741. wifi_signal: int | None = None # WiFi signal strength in dBm
  742. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  743. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  744. # Nozzle hardware info (for dual nozzle printers, index 0 = left, 1 = right)
  745. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  746. # AI detection and print options
  747. print_options: PrintOptions = field(default_factory=PrintOptions)
  748. # Calibration stage tracking (from stg_cur and stg fields)
  749. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  750. stg: list = field(default_factory=list) # List of stages to execute
  751. # Air conditioning mode (0=cooling, 1=heating)
  752. airduct_mode: int = 0
  753. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  754. speed_level: int = 2
  755. # Chamber light on/off
  756. chamber_light: bool = False
  757. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  758. active_extruder: int = 0
  759. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  760. tray_now: int = 255
  761. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  762. # tray_tar = the slot the paused/loading print now expects
  763. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  764. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  765. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  766. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  767. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  768. tray_tar: int = 255
  769. tray_pre: int = 255
  770. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  771. last_loaded_tray: int = -1
  772. # Pending load target - used to track what tray we're loading for H2D disambiguation
  773. pending_tray_target: int | None = None
  774. # AMS status for filament change tracking (from print.ams.ams_status field)
  775. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  776. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  777. ams_status: int = 0
  778. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  779. ams_status_sub: int = 0 # ams_status & 0xFF
  780. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  781. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  782. mc_print_sub_stage: int = 0
  783. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  784. ams_mapping: list = field(default_factory=list)
  785. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  786. ams_extruder_map: dict = field(default_factory=dict)
  787. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  788. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  789. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  790. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  791. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  792. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  793. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  794. ams_switch_inlet: dict = field(default_factory=dict)
  795. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  796. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  797. # series). Empty elsewhere, which every reader has to tolerate — see
  798. # ExtruderSlot for why tray_now cannot stand in for it.
  799. extruder_slots: dict = field(default_factory=dict)
  800. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  801. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  802. # regex used to derive the plate number from the path always falls back to
  803. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  804. # Bambuddy dispatches the print itself we know the plate authoritatively;
  805. # we record it here and prefer it over the gcode_file regex. The subtask
  806. # field guards against staleness: if the printer is currently running a
  807. # different subtask (e.g. a Studio-direct dispatch), these values are
  808. # ignored. Cleared on disconnect.
  809. dispatched_plate_id: int | None = None
  810. dispatched_subtask: str | None = None
  811. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  812. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  813. h2d_extruder_snow: dict = field(default_factory=dict)
  814. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  815. nozzle_rack: list = field(default_factory=list)
  816. # H2C rack position currently mounted / being moved to, from
  817. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  818. # the six rack slots), not extruder indices, and they are what the
  819. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  820. # can tell us which hotend is in the carriage right now, so this is read
  821. # live rather than derived from the queued job.
  822. nozzle_rack_src_id: int | None = None
  823. nozzle_rack_tar_id: int | None = None
  824. # Timestamp of last AMS data update (for RFID refresh detection)
  825. last_ams_update: float = 0.0
  826. # Printable objects for skip object functionality: {identify_id: object_name}
  827. printable_objects: dict = field(default_factory=dict)
  828. # Objects that have been skipped during the current print
  829. skipped_objects: list = field(default_factory=list)
  830. # Fan speeds (0-100 percentage, None if not available for this model)
  831. cooling_fan_speed: int | None = None # Part cooling fan
  832. big_fan1_speed: int | None = None # Auxiliary fan
  833. big_fan2_speed: int | None = None # Chamber/exhaust fan
  834. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  835. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  836. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  837. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  838. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  839. left_aux_fan_speed: int | None = None
  840. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  841. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  842. # omits it, which is the case this flag exists to detect.
  843. #
  844. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  845. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  846. # harmless because only the P2S/X2D badge consults it — those models keep
  847. # their unconditional "Chamber Fan" badge — but do not read this as
  848. # "an exhaust kit is fitted" without also checking the model.
  849. exhaust_fan_present: bool = False
  850. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  851. # Used by usage tracker to split filament weight on mid-print tray switch
  852. tray_change_log: list = field(default_factory=list)
  853. # Firmware version info (from info.module[name="ota"].sw_ver)
  854. firmware_version: str | None = None
  855. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  856. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  857. developer_mode: bool | None = None
  858. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  859. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  860. # which uses the old protocol path; field not yet found). Consumers must treat
  861. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  862. ams_filament_backup: bool | None = None
  863. # Stage name mapping from BambuStudio DeviceManager.cpp
  864. STAGE_NAMES = {
  865. 0: "Printing",
  866. 1: "Auto bed leveling",
  867. 2: "Heatbed preheating",
  868. 3: "Vibration compensation",
  869. 4: "Changing filament",
  870. 5: "M400 pause",
  871. 6: "Paused (filament ran out)",
  872. 7: "Heating nozzle",
  873. 8: "Calibrating dynamic flow",
  874. 9: "Scanning bed surface",
  875. 10: "Inspecting first layer",
  876. 11: "Identifying build plate type",
  877. 12: "Calibrating Micro Lidar",
  878. 13: "Homing toolhead",
  879. 14: "Cleaning nozzle tip",
  880. 15: "Checking extruder temperature",
  881. 16: "Paused by the user",
  882. 17: "Pause (front cover fall off)",
  883. 18: "Calibrating the micro lidar",
  884. 19: "Calibrating flow ratio",
  885. 20: "Pause (nozzle temperature malfunction)",
  886. 21: "Pause (heatbed temperature malfunction)",
  887. 22: "Filament unloading",
  888. 23: "Pause (step loss)",
  889. 24: "Filament loading",
  890. 25: "Motor noise cancellation",
  891. 26: "Pause (AMS offline)",
  892. 27: "Pause (low speed of the heatbreak fan)",
  893. 28: "Pause (chamber temperature control problem)",
  894. 29: "Cooling chamber",
  895. 30: "Pause (Gcode inserted by user)",
  896. 31: "Motor noise showoff",
  897. 32: "Pause (nozzle clumping)",
  898. 33: "Pause (cutter error)",
  899. 34: "Pause (first layer error)",
  900. 35: "Pause (nozzle clog)",
  901. 36: "Measuring motion precision",
  902. 37: "Enhancing motion precision",
  903. 38: "Measure motion accuracy",
  904. 39: "Nozzle offset calibration",
  905. 40: "High temperature auto bed leveling",
  906. 41: "Auto Check: Quick Release Lever",
  907. 42: "Auto Check: Door and Upper Cover",
  908. 43: "Laser Calibration",
  909. 44: "Auto Check: Platform",
  910. 45: "Confirming BirdsEye Camera location",
  911. 46: "Calibrating BirdsEye Camera",
  912. 47: "Auto bed leveling - phase 1",
  913. 48: "Auto bed leveling - phase 2",
  914. 49: "Heating chamber",
  915. 50: "Cooling heatbed",
  916. 51: "Printing calibration lines",
  917. 52: "Auto Check: Material",
  918. 53: "Live View Camera Calibration",
  919. 54: "Waiting for heatbed temperature",
  920. 55: "Auto Check: Material Position",
  921. 56: "Cutting Module Offset Calibration",
  922. 57: "Measuring Surface",
  923. 58: "Thermal Preconditioning",
  924. 59: "Homing Blade Holder",
  925. 60: "Calibrating Camera Offset",
  926. 61: "Calibrating Blade Holder Position",
  927. 62: "Hotend Pick and Place Test",
  928. 63: "Waiting for Chamber temperature",
  929. 64: "Preparing Hotend",
  930. 65: "Calibrating nozzle clumping detection",
  931. 66: "Purifying the chamber air",
  932. 74: "Preparing", # Seen on H2D during print preparation
  933. 77: "Preparing AMS",
  934. }
  935. def get_stage_name(stage: int) -> str:
  936. """Get human-readable stage name from stage number."""
  937. try:
  938. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  939. except TypeError:
  940. # `stage` is an int by convention only -- it comes straight out of the
  941. # printer's JSON, and an unhashable value there would otherwise raise
  942. # from inside the f-string that builds the stage-change log line, which
  943. # is evaluated on every transition whatever the log level is set to.
  944. # Labelling a value must not be able to abort the state update.
  945. return f"Unknown stage ({stage})"
  946. # #2547 end-of-print telemetry probe.
  947. #
  948. # The finish photo needs a "printing is done, toolhead parked, filament unload
  949. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  950. # but fires on no model in the field: across 247 support bundles there is not a
  951. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  952. # window where it was the only pre-FINISH trigger in the code (104 captures on
  953. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  954. #
  955. # We can't design a replacement from bundles we already have, because out of
  956. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  957. # every other stage/action field is dropped unread. The obvious candidates
  958. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  959. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  960. # own. Dumping the raw values for the window between the last object layer and
  961. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  962. # anything — marks that moment.
  963. #
  964. # Every field here is machine telemetry (stage codes, counters, bitfields).
  965. # Nothing identifying, and nothing that could carry an access code.
  966. _END_OF_PRINT_PROBE_FIELDS = (
  967. "gcode_state",
  968. "state",
  969. "print_error",
  970. "stg_cur",
  971. "stg",
  972. "stg_cd",
  973. "mc_print_stage",
  974. "mc_print_sub_stage",
  975. "mc_action",
  976. "mc_stage",
  977. "print_real_action",
  978. "print_gcode_action",
  979. "spd_lvl",
  980. "mc_percent",
  981. "mc_remaining_time",
  982. "layer_num",
  983. "total_layer_num",
  984. "home_flag",
  985. "prepare_per",
  986. )
  987. # Frame budget for one print's probe. A long final layer can hold the window
  988. # open for minutes at ~1 frame/second; this stops a single print from filling
  989. # the log the user then has to upload.
  990. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  991. # States that close the window. FINISH is the interesting one — the probe's
  992. # whole job is to show what happened in the run-up to it.
  993. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  994. class BambuMQTTClient:
  995. """MQTT client for Bambu Lab printer communication."""
  996. MQTT_PORT = 8883
  997. # Class-level cache: serial_number -> False when request topic is known unsupported.
  998. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  999. _request_topic_cache: dict[str, bool] = {}
  1000. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1001. # the request topic. A SUBACK failure is the broker answering the question;
  1002. # a disconnect is only circumstantial, and any drop inside the window looks
  1003. # identical -- a network blip, the printer rebooting, the container being
  1004. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1005. # the rest of the process on a printer that supports it perfectly well
  1006. # (#2953). Require the drop to repeat before believing it; a printer that
  1007. # really does refuse the topic answers the same way every time and pays one
  1008. # extra reconnect for it.
  1009. _request_topic_probe_failures: dict[str, int] = {}
  1010. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1011. # Counter for generating unique MQTT client IDs across instances.
  1012. _client_instance_counter: int = 0
  1013. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1014. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1015. # every few seconds (and register_assignment_verification nudges a fresh
  1016. # pushall), so this only has to survive a couple of idle push intervals.
  1017. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1018. def __init__(
  1019. self,
  1020. ip_address: str,
  1021. serial_number: str,
  1022. access_code: str,
  1023. model: str | None = None,
  1024. on_state_change: Callable[[PrinterState], None] | None = None,
  1025. on_print_start: Callable[[dict], None] | None = None,
  1026. on_print_complete: Callable[[dict], None] | None = None,
  1027. on_ams_change: Callable[[list], None] | None = None,
  1028. on_layer_change: Callable[[int], None] | None = None,
  1029. on_print_progress: Callable[[int], None] | None = None,
  1030. on_bed_temp_update: Callable[[float], None] | None = None,
  1031. on_drying_complete: Callable[[int], None] | None = None,
  1032. on_print_running_observed: Callable[[dict], None] | None = None,
  1033. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1034. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1035. on_tray_change: Callable[[int, int], None] | None = None,
  1036. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1037. ):
  1038. self.ip_address = ip_address
  1039. self.serial_number = serial_number
  1040. self.access_code = access_code
  1041. self.model = model
  1042. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1043. self._debug_last: dict[str, object] = {}
  1044. self.on_state_change = on_state_change
  1045. self.on_print_start = on_print_start
  1046. self.on_print_complete = on_print_complete
  1047. self.on_ams_change = on_ams_change
  1048. # Fired when an AMS is moved to the switch's other inlet, which changes
  1049. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1050. self.on_fts_inlet_change = on_fts_inlet_change
  1051. self.on_layer_change = on_layer_change
  1052. # #2547: fired when `mc_percent` advances during a running print.
  1053. # `on_layer_change` stops firing the instant the final layer starts, so
  1054. # it is blind to the last few percent of a print — which is exactly the
  1055. # window the finish-photo frame bank needs to keep refreshing through.
  1056. # Progress is the one field that keeps ticking there and then freezes
  1057. # before the end G-code runs, so banking on it stays inside the print.
  1058. self.on_print_progress = on_print_progress
  1059. self.on_bed_temp_update = on_bed_temp_update
  1060. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1061. # the drying cycle just finished (auto- or manually-triggered).
  1062. # Receives the AMS id of the unit that finished drying.
  1063. self.on_drying_complete = on_drying_complete
  1064. # #1485 follow-up: fired the first time we see RUNNING state in a
  1065. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1066. # print, the #1304 first-push guard skipped the start event). Lets
  1067. # main.py capture a fresh timelapse baseline at restart-recovery
  1068. # time so the completion-time snapshot-diff still works. Receives
  1069. # the same shape as on_print_start (filename / subtask_name /
  1070. # remaining_time / raw_data / ams_mapping).
  1071. self.on_print_running_observed = on_print_running_observed
  1072. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1073. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1074. # with the process, and a long print outliving a restart would
  1075. # otherwise lose the segment boundaries the usage tracker splits on.
  1076. # Receives (global_tray_id, layer_num).
  1077. self.on_tray_change = on_tray_change
  1078. # #1721: fired the moment the printer enters the end-of-print
  1079. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1080. # we've hit the last layer / remaining_time<=0). This is the
  1081. # framing #1397 was after — toolhead parked, bed not yet
  1082. # dropped — but reached via a clean state signal instead of
  1083. # the per-layer M622 J1 macros which caused per-layer nozzle
  1084. # parks on slicer profiles with Timelapse Type = Smooth.
  1085. # A FINISH-state fallback below fires this same callback if
  1086. # stage 22 never arrives (cancel mid-print, external-spool-
  1087. # only prints, HMS halt before unload, firmware variants).
  1088. self.on_finish_photo_moment = on_finish_photo_moment
  1089. # #2582: fired after a spool assignment (ams_filament_setting +
  1090. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1091. # push landed or a timeout elapses without it. Receives
  1092. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1093. # tell the user "loaded" vs "assignment didn't take" instead of the
  1094. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1095. # feel random. See _check_assignment_verifications.
  1096. self.on_assignment_verified = on_assignment_verified
  1097. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1098. # value is the desired end-state we just pushed plus a monotonic
  1099. # deadline. Populated by register_assignment_verification, drained by
  1100. # _check_assignment_verifications on every AMS push.
  1101. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1102. # Per-AMS previous dry_time, used to detect the falling edge above.
  1103. # Seeded lazily as we observe each AMS unit.
  1104. self._previous_dry_times: dict[int, int] = {}
  1105. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1106. # last start. Bambu does not echo these back in the per-tick AMS push
  1107. # — only the dry_time countdown — so we cache what we sent to drive
  1108. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1109. self._drying_targets: dict[int, dict[str, object]] = {}
  1110. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1111. # ends a cycle far short of its duration, which on the telemetry alone
  1112. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1113. # log would otherwise blame the printer for our own decision (#2770).
  1114. self._drying_stops_sent: set[int] = set()
  1115. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1116. # for, so each is reported once rather than on every transition into it.
  1117. self._unnamed_stages_seen: set[int] = set()
  1118. self.state = PrinterState()
  1119. self._client: mqtt.Client | None = None
  1120. self._loop: asyncio.AbstractEventLoop | None = None
  1121. self._previous_gcode_state: str | None = None
  1122. self._previous_gcode_file: str | None = None
  1123. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1124. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1125. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1126. # #1721: one-shot guard so the end-of-print stage-22 detector
  1127. # and the FINISH-state fallback don't both fire on the same
  1128. # print. Reset to False on every print start.
  1129. self._finish_photo_captured: bool = False
  1130. # #2702: one-shot re-request of the layer total. Armed at print start
  1131. # when the starting frame carried no `total_layer_num`, spent on the
  1132. # first layer advance that still has no denominator. Bambu firmware
  1133. # only re-sends *changed* fields, so a total we never received (or
  1134. # dropped) is only recoverable via a full pushall.
  1135. self._total_layers_refresh_armed: bool = False
  1136. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1137. # window has run for a print so a late FINISH re-send can't reopen it.
  1138. self._eop_probe_armed: bool = True
  1139. self._eop_probe_open: bool = False
  1140. self._eop_probe_frames: int = 0
  1141. self._eop_probe_last: dict = {}
  1142. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1143. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1144. # The subtask_id minted for the most recent start_print() command. The
  1145. # printer echoes it back in status, but often not within the first few
  1146. # seconds — so on_print_start uses this as the id source when the
  1147. # printer hasn't reported it yet, letting queue/scheduled archives
  1148. # persist a restart-stable id from the moment they dispatch (#1485).
  1149. self.last_dispatch_subtask_id: str | None = None
  1150. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1151. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1152. self._logging_enabled: bool = False
  1153. self._last_message_time: float = 0.0 # Track when we last received a message
  1154. # Count of report-topic messages received since the last (re)connect.
  1155. # Lets check_staleness() distinguish "printer never sent a status
  1156. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1157. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1158. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1159. self._report_messages_since_connect: int = 0
  1160. self._zero_report_hint_logged: bool = False
  1161. # Set by mark_power_off() to the gcode_state held just before we
  1162. # optimistically forced the printer to "unknown" (#2629). Restored on
  1163. # the next inbound message, because message traffic proves the power
  1164. # was never actually cut. None whenever no power-off is presumed.
  1165. self._state_before_power_off: str | None = None
  1166. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1167. # printer's pushes verbatim to slicers connected to a virtual printer).
  1168. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1169. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1170. self._disconnection_event: threading.Event | None = None
  1171. self._previous_ams_hash: str | None = None # Track AMS changes
  1172. # Track external-spool (vt_tray) identity changes separately: the AMS
  1173. # hash above covers only AMS units, so an external-spool-only filament
  1174. # swap would never re-trigger inventory reconciliation (#2575).
  1175. self._previous_vt_tray_hash: str | None = None
  1176. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1177. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1178. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1179. # Track which (ams_id, field) warnings have already been emitted this connection
  1180. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1181. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1182. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1183. # keyed by the sequence_id we sent, so two concurrent requests for
  1184. # different nozzle sizes can't steal each other's response (#1748).
  1185. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1186. self._sequence_id: int = 0
  1187. self._pending_kprofile_requests: dict[str, dict] = {}
  1188. # The printer's calibration table, one bucket per nozzle diameter.
  1189. #
  1190. # An extrusion_cali_get response is the complete table for *one* nozzle
  1191. # size, and the printer answers whoever asks — including BambuStudio,
  1192. # whose queries land on the same report topic we subscribe to. Assigning
  1193. # each response straight to state.kprofiles therefore let any single
  1194. # answer stand for the whole printer: a GitHub backup probing
  1195. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1196. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1197. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1198. # card because H2-series trays carry no `k` of their own — the slot's
  1199. # K value is resolved from cali_idx against exactly this list.
  1200. #
  1201. # Keyed by diameter so a response only ever replaces the bucket it
  1202. # actually describes; state.kprofiles is then the union across buckets.
  1203. # An empty answer for a nozzle the printer doesn't have empties that
  1204. # bucket alone.
  1205. self._kprofiles_by_nozzle: dict[str, list] = {}
  1206. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1207. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1208. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1209. # by await_cali_ack.
  1210. self._pending_cali_acks: dict[str, dict | None] = {}
  1211. # Identifies the one project_file *we* dispatched, so its echo on the
  1212. # topic can be told apart from a slicer's. One-shot: consumed by the
  1213. # first frame that matches. See _project_file_key.
  1214. self._own_project_file_key: str | None = None
  1215. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1216. # Key: module_name, Value: timestamp when command was sent
  1217. self._xcam_hold_start: dict[str, float] = {}
  1218. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1219. # Track last requested tray ID for H2D dual-nozzle printers
  1220. # H2D only reports slot number (0-3) in tray_now, not global tray ID
  1221. # We use our tracked value to resolve the correct global ID
  1222. self._last_load_tray_id: int | None = None
  1223. # Captured ams_mapping from print commands on the request topic
  1224. # Intercepts slicer/Bambuddy print commands to get the slot-to-tray mapping
  1225. self._captured_ams_mapping: list[int] | None = None
  1226. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1227. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1228. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1229. self._has_a2l_am_unit: bool = False
  1230. # Why the last connection attempt was refused by the printer, or None
  1231. # when we have never seen a CONNACK failure since the last success.
  1232. # Without this a rejected access code was completely invisible: paho
  1233. # reports the follow-up disconnect as the generic "Unspecified error"
  1234. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1235. # printer stuck in a reconnect loop looked identical whether it was
  1236. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1237. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1238. # string, kept for the log line only.
  1239. self.last_connect_error: str | None = None
  1240. self.last_connect_error_name: str | None = None
  1241. # Request topic subscription tracking
  1242. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1243. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1244. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1245. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1246. self._request_topic_sub_mid: int | None = None
  1247. self._request_topic_sub_time: float = 0.0
  1248. self._request_topic_confirmed: bool = False
  1249. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1250. # we probe by sending an ams_filament_setting and checking the response.
  1251. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1252. self._dev_mode_probed: bool = False
  1253. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1254. self._dev_mode_probe_seq: str | None = None
  1255. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1256. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1257. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1258. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1259. # the printer reports it until the fault clears, so when a later hms[]
  1260. # arrives without it (user enabled Developer Mode and restarted the
  1261. # printer) we drop back to "unknown" and let the probe re-run instead of
  1262. # leaving a permanently-wrong False behind (#2732).
  1263. self._dev_mode_from_hms: bool = False
  1264. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1265. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1266. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1267. self._stale_reconnecting: bool = False
  1268. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1269. # when the frontend polls status faster than paho can reconnect.
  1270. self._last_stale_reconnect: float = 0.0
  1271. # Zombie session detection via ams_filament_setting response tracking (#887).
  1272. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1273. # that develop later (telemetry flows but publishes silently fail).
  1274. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1275. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1276. @property
  1277. def topic_subscribe(self) -> str:
  1278. return f"device/{self.serial_number}/report"
  1279. @property
  1280. def topic_publish(self) -> str:
  1281. return f"device/{self.serial_number}/request"
  1282. @property
  1283. def report_messages_since_connect(self) -> int:
  1284. """Count of report-topic messages received since the latest (re)connect.
  1285. Exposed for the connection diagnostic so it can distinguish "MQTT
  1286. broker accepted us but the printer never published" (typically a
  1287. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1288. bridge that happens to be idle right now. Zero immediately after a
  1289. fresh connect is normal; zero after a full status push cycle is the
  1290. wrong-serial failure mode.
  1291. """
  1292. return self._report_messages_since_connect
  1293. # Maximum time (seconds) without a message before considering connection stale
  1294. STALE_TIMEOUT = 60.0
  1295. def is_stale(self) -> bool:
  1296. """Check if the connection is stale (no messages for too long)."""
  1297. if self._last_message_time == 0:
  1298. return False # Never received a message yet
  1299. time_since_last = time.time() - self._last_message_time
  1300. return time_since_last > self.STALE_TIMEOUT
  1301. def mark_power_off(self) -> bool:
  1302. """Presume the printer lost power (smart plug switched off).
  1303. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1304. The presumption is undone by ``_on_message`` if the printer keeps
  1305. talking — inbound traffic proves the power was never cut (#2629).
  1306. Returns True when the state was actually changed.
  1307. """
  1308. if not self.state.connected:
  1309. return False
  1310. previous = self.state.state
  1311. # Blank the state BEFORE recording what to restore. This runs on the
  1312. # event loop while _on_message runs on the paho thread, and the restore
  1313. # is a two-step (read saved state, compare against "unknown"). Writing
  1314. # "unknown" first means an interleaved message either sees no saved
  1315. # state yet (and skips, leaving the next message to restore) or sees a
  1316. # consistent pair — never a saved state paired with a live state it
  1317. # then discards, which would strand the printer on "unknown".
  1318. self.state.connected = False
  1319. self.state.state = "unknown"
  1320. # Only the first mark wins: a second call before any message arrives
  1321. # must not overwrite the real state with the "unknown" it just wrote.
  1322. # Nothing to restore if the state was already blank.
  1323. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1324. self._state_before_power_off = previous
  1325. return True
  1326. def _restore_state_after_false_power_off(self) -> bool:
  1327. """Undo a presumed power-off once the printer proves it is alive.
  1328. ``connected`` self-heals on the next message, but ``state`` does not:
  1329. it is only rewritten when a payload carries ``gcode_state``, and the
  1330. steady-state ``push_status`` frames are partial. Without this the
  1331. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1332. and the queue scheduler treats the printer as not idle the whole time
  1333. (#2629). Returns True when a state was restored.
  1334. """
  1335. previous = self._state_before_power_off
  1336. self._state_before_power_off = None
  1337. if previous is None or self.state.state != "unknown":
  1338. return False
  1339. logger.info(
  1340. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1341. self.serial_number,
  1342. previous,
  1343. )
  1344. self.state.state = previous
  1345. return True
  1346. # Minimum seconds between stale reconnect attempts. Frontend polls
  1347. # status every few seconds — without a cooldown, each poll would
  1348. # force-close the socket before paho has time to reconnect.
  1349. STALE_RECONNECT_COOLDOWN = 30.0
  1350. def check_staleness(self) -> bool:
  1351. """Check staleness and update connected state if stale. Returns True if connected."""
  1352. if self.state.connected and self.is_stale():
  1353. # Don't force-close again if we already did recently — give paho
  1354. # time to reconnect and the printer time to send its first message.
  1355. now = time.time()
  1356. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1357. return self.state.connected
  1358. logger.warning(
  1359. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1360. )
  1361. # A connection that keeps going stale without ever receiving a
  1362. # status report is almost always a wrong or mis-cased serial
  1363. # number — the broker accepts the connection and the subscription
  1364. # regardless, but the printer publishes to device/<real-serial>/
  1365. # report, which is case-sensitive. Surface that once so the user
  1366. # has something actionable instead of an endless reconnect loop.
  1367. # Only meaningful once the *current* session has had time to receive
  1368. # something. _report_messages_since_connect is reset by _on_connect,
  1369. # so a reconnect that lands microseconds before this check leaves it
  1370. # at 0 for reasons that have nothing to do with the serial — which is
  1371. # how a healthy P1S ended up being told to go check its serial number
  1372. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1373. # on this session means the hint only fires when the printer really
  1374. # has published nothing to the topic we subscribed to.
  1375. # _connect_time of 0 means we have no timestamp to judge by (never went
  1376. # through _on_connect); fall back to the old unconditional behaviour
  1377. # rather than silently swallowing the hint.
  1378. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1379. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1380. self._zero_report_hint_logged = True
  1381. logger.warning(
  1382. "[%s] Connected and subscribed, but the printer has sent zero "
  1383. "status reports. The most common cause is a wrong or mis-cased "
  1384. "serial number — the device/<serial>/report MQTT topic is "
  1385. "case-sensitive. Verify the serial number configured in Bambuddy "
  1386. "exactly matches the printer.",
  1387. self.serial_number,
  1388. )
  1389. self._last_stale_reconnect = now
  1390. self.state.connected = False
  1391. if self.on_state_change:
  1392. self.on_state_change(self.state)
  1393. # Route based on caller thread — see force_reconnect_stale_session.
  1394. # check_staleness is normally called from FastAPI handlers (async,
  1395. # gets the hard-reset path) but the dispatcher exists for safety.
  1396. self._stale_reconnecting = True
  1397. self._reset_client_for_reconnect()
  1398. return self.state.connected
  1399. def force_reconnect_stale_session(self, reason: str) -> None:
  1400. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1401. # arriving but our publishes don't reach the printer.
  1402. #
  1403. # Two routing paths:
  1404. #
  1405. # Async-context callers (queue dispatch deadline)
  1406. # → full client teardown + fresh client_id. Wipes paho's client-side
  1407. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1408. # `project_file` from the broken session would otherwise replay on
  1409. # reconnect, mixing stale commands into the next dispatch and
  1410. # triggering 0500_4003 SD R/W on the printer.
  1411. #
  1412. # Paho-network-thread callers (line ~2604/~2623 — dev-mode probe and
  1413. # ams_filament_setting zombie detection inside `_update_state`)
  1414. # → socket-close fallback. Calling `loop_stop()` from inside the
  1415. # network thread would self-join and deadlock; the safe pattern is
  1416. # to close the socket and let paho's own loop detect the broken
  1417. # connection and auto-reconnect (same instance, same client_id —
  1418. # queue replay is theoretically possible here but those paths have
  1419. # always done socket-close and #1136 was specifically triggered
  1420. # from the dispatch path).
  1421. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1422. self._stale_reconnecting = True
  1423. self.state.connected = False
  1424. if self.on_state_change:
  1425. self.on_state_change(self.state)
  1426. self._reset_client_for_reconnect()
  1427. def _reset_client_for_reconnect(self) -> None:
  1428. """Route between hard-reset and socket-close based on caller thread.
  1429. Hard-reset (preferred) requires we're not running on paho's network
  1430. thread, since `loop_stop()` on the same thread deadlocks. Detect via
  1431. ``asyncio.get_running_loop()`` — paho's callback thread has no loop;
  1432. every legitimate hard-reset caller (FastAPI handlers, background
  1433. async tasks) does."""
  1434. try:
  1435. loop = asyncio.get_running_loop()
  1436. except RuntimeError:
  1437. loop = None
  1438. if loop is not None:
  1439. self._loop = loop
  1440. self._hard_reset_client()
  1441. else:
  1442. self._socket_close_for_reconnect()
  1443. def _hard_reset_client(self) -> None:
  1444. """Tear down the paho client entirely and rebuild it with a fresh
  1445. client_id, so the broker drops the old session and paho's local
  1446. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1447. Caller is responsible for setting ``_stale_reconnecting`` and
  1448. broadcasting the disconnected state."""
  1449. old_client = self._client
  1450. self._client = None
  1451. if old_client is not None:
  1452. try:
  1453. old_client.disconnect() # MQTT DISCONNECT — broker drops session
  1454. except Exception:
  1455. pass
  1456. try:
  1457. old_client.loop_stop() # blocks briefly until the network thread exits
  1458. except Exception:
  1459. pass
  1460. # Skip reconnect if no asyncio loop is available (test environment or
  1461. # pre-init). The next initial connect() call from PrinterManager will
  1462. # set up the client fresh.
  1463. if self._loop is None:
  1464. return
  1465. try:
  1466. self.connect(loop=self._loop)
  1467. except Exception as e:
  1468. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1469. def _socket_close_for_reconnect(self) -> None:
  1470. """Close the underlying socket so paho's loop thread detects the
  1471. broken connection and triggers auto-reconnect on the SAME client
  1472. instance. Safe to call from paho's own network thread (the loop
  1473. polls the socket on every iteration and handles a closed socket
  1474. gracefully). Used as a fallback when hard-reset isn't safe; queue
  1475. replay remains theoretically possible here but #1136 specifically
  1476. traced through the dispatch-deadline path which now hard-resets."""
  1477. if self._client:
  1478. try:
  1479. sock = self._client.socket()
  1480. if sock:
  1481. sock.close()
  1482. except Exception:
  1483. pass
  1484. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1485. if rc == 0:
  1486. self.state.connected = True
  1487. self.last_connect_error = None
  1488. self.last_connect_error_name = None
  1489. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1490. # A dropped-and-restored MQTT session means the presumed power-off was
  1491. # real (or at least that the printer restarted): there is nothing
  1492. # legitimate left to restore, and the printer will send a full status
  1493. # push shortly. Dropping the saved state keeps a stale one from being
  1494. # broadcast ahead of the first real report (#2629, #1679).
  1495. self._state_before_power_off = None
  1496. # Reset per-connection warning state so warnings fire once per (re)connection
  1497. self._ams_version_warned = set()
  1498. # Preserve cached developer_mode across auto-reconnects to avoid
  1499. # re-probing on every reconnect. The probe (ams_filament_setting to
  1500. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1501. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1502. # once when developer_mode is truly unknown (first connect).
  1503. # Reset probe tracking so stale timeout state doesn't carry over.
  1504. self._dev_mode_probed = False
  1505. self._dev_mode_needs_probe = False
  1506. self._dev_mode_probe_seq = None
  1507. self._dev_mode_probe_time = 0.0
  1508. self._dev_mode_probe_failures = 0
  1509. self._connect_time = time.monotonic()
  1510. self._report_messages_since_connect = 0
  1511. self._last_ams_cmd_time = 0.0
  1512. self._ams_cmd_unanswered = 0
  1513. # Drop any assignment verifications that were mid-flight before the
  1514. # reconnect — their deadlines are stale and the tray state we would
  1515. # compare against is about to be re-pushed from scratch (#2582).
  1516. # Dropping is silent (no failure event) on purpose.
  1517. self._pending_assignments.clear()
  1518. client.subscribe(self.topic_subscribe)
  1519. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1520. if self._request_topic_supported:
  1521. result, mid = client.subscribe(self.topic_publish)
  1522. if result == mqtt.MQTT_ERR_SUCCESS:
  1523. self._request_topic_sub_mid = mid
  1524. self._request_topic_sub_time = time.time()
  1525. self._request_topic_confirmed = False
  1526. else:
  1527. logger.warning(
  1528. "[%s] Failed to send request topic subscription",
  1529. self.serial_number,
  1530. )
  1531. self._request_topic_supported = False
  1532. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1533. # Request full status update (includes nozzle info in push_status response)
  1534. self._request_push_all()
  1535. # Request firmware version info
  1536. self._request_version()
  1537. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1538. # The correct nozzle data comes from push_status.
  1539. # Prime K-profile request (Bambu printers often ignore first request)
  1540. self._prime_kprofile_request()
  1541. # Immediately broadcast connection state change
  1542. if self.on_state_change:
  1543. self.on_state_change(self.state)
  1544. else:
  1545. self.state.connected = False
  1546. self._record_connect_refusal(rc)
  1547. def _record_connect_refusal(self, rc) -> None:
  1548. """Log and remember why the printer refused the MQTT connection.
  1549. The failure branch of ``_on_connect`` used to be a bare
  1550. ``connected = False``, which threw away the only signal that says
  1551. *why* a printer never comes online. The user-visible result was a
  1552. 30-second reconnect loop logging nothing but paho's generic
  1553. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1554. powered-off printer, so "my printer won't print" reports could not be
  1555. triaged without a round trip (#2698).
  1556. Never logs the access code itself; the code is the likely culprit but
  1557. printing it would put a credential in every support bundle.
  1558. """
  1559. code = getattr(rc, "value", rc)
  1560. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1561. self.last_connect_error_name = name
  1562. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1563. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1564. logger.warning(
  1565. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1566. "or serial number is wrong — the access code changes every time LAN Only or "
  1567. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1568. self.serial_number,
  1569. name,
  1570. code,
  1571. )
  1572. else:
  1573. self.last_connect_error = CONNECT_ERROR_REFUSED
  1574. logger.warning(
  1575. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1576. self.serial_number,
  1577. name,
  1578. code,
  1579. )
  1580. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1581. """Handle SUBACK responses to detect request topic subscription rejection."""
  1582. if mid == self._request_topic_sub_mid:
  1583. for rc in reason_code_list:
  1584. if rc.is_failure:
  1585. logger.warning(
  1586. "[%s] Request topic subscription rejected (code=%d: %s). "
  1587. "ams_mapping capture from slicer-initiated prints unavailable.",
  1588. self.serial_number,
  1589. rc.value,
  1590. rc.getName(),
  1591. )
  1592. self._request_topic_supported = False
  1593. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1594. else:
  1595. logger.info(
  1596. "[%s] Request topic subscription accepted. "
  1597. "ams_mapping capture enabled for slicer-initiated prints.",
  1598. self.serial_number,
  1599. )
  1600. self._request_topic_confirmed = True
  1601. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  1602. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  1603. self._request_topic_sub_mid = None
  1604. self._request_topic_sub_time = 0.0
  1605. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  1606. # Always unblock disconnect() callers, regardless of whether we suppress
  1607. # the state broadcast below. disconnect() sets _disconnection_event and
  1608. # waits on it — every callback path must fire it.
  1609. if self._disconnection_event:
  1610. self._disconnection_event.set()
  1611. # If we intentionally closed the socket for stale reconnect, don't broadcast
  1612. # another state change — check_staleness() already set connected=False and
  1613. # notified the UI. Just log and let paho auto-reconnect.
  1614. if self._stale_reconnecting:
  1615. logger.info(
  1616. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  1617. self.serial_number,
  1618. rc,
  1619. )
  1620. return
  1621. # Ignore spurious disconnect callbacks if we've received a message recently
  1622. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  1623. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  1624. # — only suppress when rc indicates a clean/normal disconnect.
  1625. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  1626. time_since_last_message = time.time() - self._last_message_time
  1627. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  1628. logger.debug(
  1629. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  1630. )
  1631. return
  1632. # Carry the last CONNACK refusal into the disconnect line. paho reports
  1633. # the drop that follows a refused CONNACK as "Unspecified error", so on
  1634. # its own this line says nothing useful about a printer that is looping
  1635. # on bad credentials — and this is the line that fills a support bundle
  1636. # (#2698).
  1637. if self.last_connect_error:
  1638. logger.warning(
  1639. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  1640. self.serial_number,
  1641. rc,
  1642. disconnect_flags,
  1643. self.last_connect_error_name,
  1644. )
  1645. else:
  1646. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  1647. # Detect if request topic subscription caused the disconnect.
  1648. # If we just subscribed and got disconnected before any SUBACK confirmation,
  1649. # the broker likely killed the connection due to the unauthorized subscription.
  1650. if (
  1651. self._request_topic_sub_time > 0
  1652. and not self._request_topic_confirmed
  1653. and time.time() - self._request_topic_sub_time < 10.0
  1654. # A disconnect we asked for says nothing about the subscription.
  1655. and self._disconnection_event is None
  1656. ):
  1657. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  1658. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  1659. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  1660. logger.warning(
  1661. "[%s] Disconnected shortly after request topic subscription %d times. "
  1662. "Disabling request topic for this printer — ams_mapping capture from "
  1663. "slicer-initiated prints is unavailable, and their filament will be "
  1664. "attributed from the printer's own tray reporting instead.",
  1665. self.serial_number,
  1666. failures,
  1667. )
  1668. self._request_topic_supported = False
  1669. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1670. else:
  1671. logger.info(
  1672. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  1673. "Retrying it on the next connection before giving up.",
  1674. self.serial_number,
  1675. failures,
  1676. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  1677. )
  1678. self._request_topic_sub_mid = None
  1679. self._request_topic_sub_time = 0.0
  1680. self.state.connected = False
  1681. if self.on_state_change:
  1682. self.on_state_change(self.state)
  1683. def _on_message(self, client, userdata, msg):
  1684. for handler in self._raw_message_handlers:
  1685. try:
  1686. handler(msg.topic, msg.payload)
  1687. except Exception:
  1688. logger.exception(
  1689. "[%s] raw-message handler crashed for topic=%s",
  1690. self.serial_number,
  1691. msg.topic,
  1692. )
  1693. try:
  1694. try:
  1695. raw = msg.payload.decode()
  1696. except UnicodeDecodeError:
  1697. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  1698. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  1699. raw = msg.payload.decode(errors="replace")
  1700. logger.warning(
  1701. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  1702. self.serial_number,
  1703. msg.topic,
  1704. len(msg.payload),
  1705. )
  1706. payload = json.loads(raw)
  1707. # Track last message time - receiving a message proves we're connected
  1708. self._last_message_time = time.time()
  1709. self.state.connected = True
  1710. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  1711. if msg.topic == self.topic_publish:
  1712. # Record it before returning. This topic carries every command
  1713. # travelling *to* the printer, including the ones Bambu Studio
  1714. # sends, and it used to be the one thing an MQTT capture could
  1715. # never show -- which is why "what does Studio put in the drying
  1716. # command?" had no answer from a user's log (#2774). Filed as
  1717. # "out" so the direction filter groups it with our own commands
  1718. # rather than with printer telemetry; anything sent through
  1719. # send_command lands twice, once on publish and once on the
  1720. # broker's echo, and the pair is itself evidence the command
  1721. # reached the broker.
  1722. if self._logging_enabled:
  1723. self._message_log.append(
  1724. MQTTLogEntry(
  1725. timestamp=datetime.now(timezone.utc).isoformat(),
  1726. topic=msg.topic,
  1727. direction="out",
  1728. payload=payload,
  1729. )
  1730. )
  1731. self._handle_request_message(payload)
  1732. return
  1733. # Count status reports per connection so check_staleness() can tell
  1734. # "printer never sent a report" apart from a mid-session quiet gap.
  1735. if msg.topic == self.topic_subscribe:
  1736. self._report_messages_since_connect += 1
  1737. # Only report-topic traffic proves the *printer* is alive — the
  1738. # request topic also carries slicer/Bambuddy commands.
  1739. if self._state_before_power_off is not None:
  1740. if self._restore_state_after_false_power_off() and self.on_state_change:
  1741. self.on_state_change(self.state)
  1742. # Log message if logging is enabled
  1743. if self._logging_enabled:
  1744. self._message_log.append(
  1745. MQTTLogEntry(
  1746. timestamp=datetime.now(timezone.utc).isoformat(),
  1747. topic=msg.topic,
  1748. direction="in",
  1749. payload=payload,
  1750. )
  1751. )
  1752. self._process_message(payload)
  1753. except json.JSONDecodeError:
  1754. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  1755. def _handle_request_message(self, data: dict) -> None:
  1756. """Intercept print commands on the request topic to capture ams_mapping."""
  1757. print_data = data.get("print", {})
  1758. if not isinstance(print_data, dict):
  1759. return
  1760. command = print_data.get("command", "")
  1761. if command == "project_file":
  1762. # Where the dispatcher put the sliced file. Captured for every
  1763. # project_file, ours included: we publish to this same topic and
  1764. # subscribe to it, so whoever dispatched last wins, which is exactly
  1765. # the print the archive lookup is about to go looking for (#2780).
  1766. url = print_data.get("url")
  1767. if isinstance(url, str) and url:
  1768. self.state.current_project_url = url
  1769. self.state.last_project_url = url
  1770. if "ams_mapping" in print_data:
  1771. self._captured_ams_mapping = print_data["ams_mapping"]
  1772. logger.info(
  1773. "[%s] Captured ams_mapping from print command: %s",
  1774. self.serial_number,
  1775. self._captured_ams_mapping,
  1776. )
  1777. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  1778. # slicer-launched project_file passes through the request topic,
  1779. # log the full payload so we can diff Studio's field set against
  1780. # ours.
  1781. #
  1782. # This used to read `sequence_id != "20000"`, on the belief that
  1783. # 20000 was ours alone. It is not: 20000 is the slicer convention
  1784. # Bambuddy adopted -- bind_server documents the slicer sending it
  1785. # during detect, and measured on the wire OrcaSlicer dispatched
  1786. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  1787. # counting up from the same base. So the test swallowed whichever
  1788. # slicer dispatch happened to land on 20000, which on a fresh
  1789. # slicer start is the first one. Match our own dispatch instead.
  1790. if self._project_file_key(print_data) == self._own_project_file_key:
  1791. self._own_project_file_key = None
  1792. else:
  1793. logger.info(
  1794. "[%s] External project_file payload: %s",
  1795. self.serial_number,
  1796. json.dumps(print_data),
  1797. )
  1798. def _capture_report_project_file(self, print_data: dict) -> None:
  1799. """Read a print's destination off a ``project_file`` *response* (#1820).
  1800. ``_handle_request_message`` only ever sees the request topic, so a print
  1801. started from the printer's own touchscreen -- which publishes nothing --
  1802. left ``current_project_url`` at None, and the storage verdict fell
  1803. through to the ``sdcard`` fallback for the one case it was written for.
  1804. On an H2S that flag is True (its "card" is the internal eMMC), so the
  1805. verdict came back reachable and the ~110-connection sweep ran in full.
  1806. The printer does announce it: an unsolicited ``project_file`` response
  1807. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  1808. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  1809. This also covers an install nobody had in view: some brokers refuse the
  1810. request-topic subscription, and on those no print of any kind has ever
  1811. populated the field.
  1812. Both kinds of ``project_file`` on this topic are read -- the printer's
  1813. echo of a dispatch and a screen start -- because both name the
  1814. destination in ``url``, which is the only thing the verdict wants. What
  1815. this must NOT do is reuse ``_handle_request_message``'s "External
  1816. project_file payload" diagnostic: our own dispatch is echoed on *both*
  1817. topics, the request-topic echo arrives first and clears
  1818. ``_own_project_file_key``, so by the time this frame lands the key is
  1819. already None and every Bambuddy-started print would log itself as
  1820. someone else's.
  1821. """
  1822. # Same shape as _handle_request_message: the frame is whatever the
  1823. # printer put on the wire, and this is the first thing to touch it.
  1824. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  1825. return
  1826. # A refused dispatch names a file that was never written. Acting on it
  1827. # would pin an archive on a destination nothing ever went to.
  1828. if print_data.get("result") != "SUCCESS":
  1829. return
  1830. url = print_data.get("url")
  1831. if not isinstance(url, str) or not url:
  1832. return
  1833. if self.state.current_project_url != url:
  1834. logger.info(
  1835. "[%s] Print destination from the report topic: %s",
  1836. self.serial_number,
  1837. url,
  1838. )
  1839. self.state.current_project_url = url
  1840. self.state.last_project_url = url
  1841. # On a screen start this frame is the only place the mapping appears --
  1842. # no slicer ever sent one. Fill a gap only: when the request topic
  1843. # already captured this print's mapping that copy is the slicer's own,
  1844. # and the echo can arrive without the field at all.
  1845. if self._captured_ams_mapping is None and isinstance(print_data.get("ams_mapping"), list):
  1846. self._captured_ams_mapping = print_data["ams_mapping"]
  1847. logger.info(
  1848. "[%s] Captured ams_mapping from print response: %s",
  1849. self.serial_number,
  1850. self._captured_ams_mapping,
  1851. )
  1852. @staticmethod
  1853. def _project_file_key(print_data: dict) -> str:
  1854. """Identity of a project_file dispatch, for telling ours from a slicer's.
  1855. Sequence id alone cannot do it -- every slicer counts up from the same
  1856. 20000 -- so this also carries the file and its destination, which differ
  1857. between any two real dispatches.
  1858. """
  1859. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  1860. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  1861. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  1862. The state dumps in the push_status handler fire whenever their field is
  1863. *present* in the frame — and a full push_status carries every field, so
  1864. they fire on every frame regardless of whether anything changed. Several
  1865. even say "updated" or "changes" in their own comment while doing nothing
  1866. of the sort.
  1867. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  1868. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  1869. minutes: the reporter enabled debug logging as asked and the support
  1870. bundle came back holding under five minutes of history, almost none of it
  1871. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  1872. these dumps.
  1873. Deduplicating on the value keeps every transition — which is the only part
  1874. anyone reads these lines for — and drops the steady-state repetition.
  1875. ``value`` must capture everything interpolated into ``msg``, or a change
  1876. will be swallowed; pass a tuple when the message renders several fields.
  1877. """
  1878. if not logger.isEnabledFor(logging.DEBUG):
  1879. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  1880. # and these clients outlive the toggle. Letting INFO-level frames warm
  1881. # the cache would be self-defeating: the operator turns debug on
  1882. # precisely to see the printer's current state, and a cache already
  1883. # holding every steady-state value would suppress that baseline until
  1884. # something happened to change. On an idle printer the bundle would
  1885. # come back with none of these lines at all.
  1886. #
  1887. # So while debug is off we record nothing and drop whatever we had.
  1888. # Every enable then starts cold and dumps a full baseline on the next
  1889. # frame, exactly as it did before this method existed.
  1890. self._debug_last.clear()
  1891. return
  1892. if self._debug_last.get(key) == value:
  1893. return
  1894. self._debug_last[key] = value
  1895. logger.debug(msg, *args)
  1896. def _process_message(self, payload: dict):
  1897. """Process incoming MQTT message from printer."""
  1898. # Handle top-level AMS data (comes outside of "print" key)
  1899. # Wrap in try/except to prevent breaking the MQTT connection
  1900. if "ams" in payload:
  1901. try:
  1902. self._handle_ams_data(payload["ams"])
  1903. except Exception as e:
  1904. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  1905. # Handle xcam data (camera settings and AI detection) at top level
  1906. if "xcam" in payload:
  1907. xcam_data = payload["xcam"]
  1908. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  1909. self._parse_xcam_data(xcam_data)
  1910. # Fire state change callback for top-level xcam (not nested in "print")
  1911. if "print" not in payload and self.on_state_change:
  1912. self.on_state_change(self.state)
  1913. # Handle system responses (accessories info, etc.)
  1914. if "system" in payload:
  1915. system_data = payload["system"]
  1916. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  1917. self._handle_system_response(system_data)
  1918. # Handle info responses (firmware version info from get_version command)
  1919. if "info" in payload:
  1920. info_data = payload["info"]
  1921. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  1922. self._handle_version_info(info_data)
  1923. # Parse WiFi signal at top level (some printers send it here)
  1924. if "wifi_signal" in payload:
  1925. wifi_signal = payload["wifi_signal"]
  1926. if isinstance(wifi_signal, (int, float)):
  1927. self.state.wifi_signal = int(wifi_signal)
  1928. elif isinstance(wifi_signal, str):
  1929. try:
  1930. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  1931. except ValueError:
  1932. pass # Ignore unparseable wifi_signal strings; field is non-critical
  1933. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  1934. from backend.app.utils.printer_models import has_ethernet
  1935. if has_ethernet(self.model):
  1936. self.state.wired_network = self.state.wifi_signal == -90
  1937. # Parse developer LAN mode from top-level "fun" field
  1938. # Some firmware versions send "fun" at the top level, others inside "print"
  1939. if "fun" in payload:
  1940. try:
  1941. fun_val = payload["fun"]
  1942. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  1943. self.state.developer_mode = (fun_int & 0x20000000) == 0
  1944. except (ValueError, TypeError):
  1945. pass
  1946. if "print" in payload:
  1947. print_data = payload["print"]
  1948. # Before anything reads the state: this is where a touchscreen-
  1949. # started print announces where its file lives, and the print-start
  1950. # handler asks ~2 s later (#1820).
  1951. self._capture_report_project_file(print_data)
  1952. # Check if xcam is nested inside print data
  1953. if "xcam" in print_data:
  1954. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  1955. self._parse_xcam_data(print_data["xcam"])
  1956. # Log when we see gcode_state changes
  1957. if "gcode_state" in print_data:
  1958. logger.debug(
  1959. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  1960. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  1961. )
  1962. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  1963. # new-protocol printers. Verified against OrcaSlicer's
  1964. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  1965. # and live H2D ON/OFF capture 2026-06-20.
  1966. #
  1967. # Hold-timer guard: when the user just toggled via the badge, the
  1968. # next 1-2 push_status frames may still carry the printer's OLD cfg
  1969. # for ~3 s before the firmware reflects the change. Without this
  1970. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  1971. new_backup = parse_ams_filament_backup_from_cfg(print_data.get("cfg"))
  1972. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  1973. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  1974. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  1975. logger.debug(
  1976. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  1977. self.serial_number,
  1978. time.time() - hold_start,
  1979. )
  1980. else:
  1981. logger.info(
  1982. "[%s] AMS Filament Backup: %s",
  1983. self.serial_number,
  1984. "ON" if new_backup else "OFF",
  1985. )
  1986. self.state.ams_filament_backup = new_backup
  1987. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  1988. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  1989. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  1990. if not self._is_dual_nozzle and "device" in print_data:
  1991. dev = print_data.get("device")
  1992. if isinstance(dev, dict):
  1993. ext_info = dev.get("extruder", {}).get("info", [])
  1994. if isinstance(ext_info, list) and len(ext_info) >= 2:
  1995. self._is_dual_nozzle = True
  1996. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  1997. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  1998. # out of the AMS info bits, but only means anything once we know a
  1999. # switch is installed. Parsing them the other way round would lose
  2000. # the binding on every frame where the two arrive together.
  2001. self._parse_fila_switch(print_data)
  2002. # Handle AMS data that comes inside print key
  2003. if "ams" in print_data:
  2004. try:
  2005. self._handle_ams_data(print_data["ams"])
  2006. except Exception as e:
  2007. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2008. # Handle vir_slot (H2-series external spool data) — list of external trays
  2009. # Process vir_slot FIRST so it takes priority over vt_tray
  2010. if "vir_slot" in print_data:
  2011. vir_slot = print_data["vir_slot"]
  2012. if isinstance(vir_slot, list) and vir_slot:
  2013. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2014. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2015. # Remap id=255→254 for single-slot printers so active detection works.
  2016. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2017. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2018. vir_slot[0]["id"] = "254"
  2019. self.state.raw_data["vt_tray"] = vir_slot
  2020. # Handle vt_tray (virtual tray / external spool) data
  2021. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2022. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2023. # which would overwrite the correct multi-slot vir_slot data)
  2024. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2025. vt_tray = print_data["vt_tray"]
  2026. existing = self.state.raw_data.get("vt_tray")
  2027. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2028. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2029. pass # Keep the vir_slot data
  2030. else:
  2031. if isinstance(vt_tray, dict):
  2032. vt_tray = [vt_tray]
  2033. self.state.raw_data["vt_tray"] = vt_tray
  2034. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2035. # units, and _handle_ams_data runs before this block — so a change
  2036. # to the external spool alone (e.g. swapping generic TPU for generic
  2037. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2038. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2039. # external-spool identity changes here and fire the same callback.
  2040. self._maybe_trigger_external_spool_change()
  2041. # Parse ams_status directly from print data (NOT from print.ams)
  2042. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2043. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2044. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2045. if "ams_status" in print_data:
  2046. raw_ams_status = print_data["ams_status"]
  2047. if isinstance(raw_ams_status, str):
  2048. try:
  2049. self.state.ams_status = int(raw_ams_status)
  2050. except ValueError:
  2051. self.state.ams_status = 0
  2052. else:
  2053. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2054. # Compute main and sub status
  2055. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2056. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2057. # Log when ams_status changes (for filament change tracking debug)
  2058. self._debug_on_change(
  2059. "ams_status:print",
  2060. self.state.ams_status,
  2061. "[%s] ams_status: %s (main=%s, sub=%s)",
  2062. self.serial_number,
  2063. self.state.ams_status,
  2064. self.state.ams_status_main,
  2065. self.state.ams_status_sub,
  2066. )
  2067. # Check for command responses
  2068. if "command" in print_data:
  2069. cmd = print_data.get("command")
  2070. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2071. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2072. # INFO, not debug: this is the printer's verdict on a write
  2073. # the user just made, and it was invisible in support
  2074. # bundles for as long as it sat at DEBUG (#2718). Same
  2075. # reasoning as ams_filament_drying below.
  2076. logger.info(
  2077. "[%s] %s response: result=%s reason=%s seq=%s",
  2078. self.serial_number,
  2079. cmd,
  2080. print_data.get("result"),
  2081. print_data.get("reason", ""),
  2082. print_data.get("sequence_id"),
  2083. )
  2084. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2085. ack_seq = str(print_data.get("sequence_id", ""))
  2086. if ack_seq in self._pending_cali_acks:
  2087. self._pending_cali_acks[ack_seq] = print_data
  2088. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2089. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2090. # A refused ams_filament_setting is the printer's verdict on
  2091. # a write the user just made, and at DEBUG it never reached
  2092. # a support bundle: #2756 reported six manual Configure Slot
  2093. # attempts on an X1C, each returning HTTP 200 with the
  2094. # read-back still showing the previous profile, and no
  2095. # record of what the printer said about any of them. Same
  2096. # promotion as extrusion_cali_set (#2718) and
  2097. # ams_filament_drying (#1447) — but only on a non-success,
  2098. # because unlike those two this command is not rare: every
  2099. # spool assignment and every K-profile re-apply sends one,
  2100. # so promoting each ack would bury the interesting line.
  2101. #
  2102. # The developer-mode probe is excluded. It sends this exact
  2103. # command to the external slot precisely to see it refused
  2104. # on P1 firmware, so its failure is a normal reading rather
  2105. # than a fault. Its response is still matched below (this
  2106. # runs before _handle_dev_mode_probe_response clears the
  2107. # seq), and user-initiated commands can't be mistaken for
  2108. # it — they publish a hardcoded sequence_id of "0".
  2109. result = print_data.get("result")
  2110. is_dev_mode_probe = (
  2111. self._dev_mode_probe_seq is not None
  2112. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2113. )
  2114. if (
  2115. cmd == "ams_filament_setting"
  2116. and not is_dev_mode_probe
  2117. and isinstance(result, str)
  2118. and result.lower() != "success"
  2119. ):
  2120. logger.info(
  2121. "[%s] ams_filament_setting refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2122. self.serial_number,
  2123. result,
  2124. print_data.get("reason", ""),
  2125. print_data.get("ams_id"),
  2126. print_data.get("tray_id"),
  2127. )
  2128. # AMS drying responses are rare (user-initiated only) and the
  2129. # full payload — including `result` and any `reason` code —
  2130. # is the only way to diagnose silent rejections like #1447.
  2131. # INFO level so the body lands in support bundles by default.
  2132. elif cmd == "ams_filament_drying":
  2133. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2134. # Check for developer mode probe response
  2135. if (
  2136. cmd == "ams_filament_setting"
  2137. and self._dev_mode_probe_seq is not None
  2138. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2139. ):
  2140. self._handle_dev_mode_probe_response(print_data)
  2141. # Track user-initiated ams_filament_setting responses (#887
  2142. # zombie detection). Reset both the timer AND the unanswered
  2143. # counter on ANY response — the response proves the channel is
  2144. # alive, so the counter must not stay armed even when the
  2145. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2146. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2147. # caused #1164: one sluggish response (>10s) would set the
  2148. # counter to 1 and zero the timer; the late response arrived
  2149. # but was ignored by this branch (timer is 0); the counter
  2150. # stayed at 1 indefinitely; the very next slow response —
  2151. # possibly hours later, on a totally unrelated command — would
  2152. # take it to 2 and force-reconnect, surfacing as "filament
  2153. # config doesn't reach the printer ~6 changes in".
  2154. elif cmd == "ams_filament_setting":
  2155. self._last_ams_cmd_time = 0.0
  2156. self._ams_cmd_unanswered = 0
  2157. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2158. if is_kprofile_response:
  2159. self._handle_kprofile_response(print_data)
  2160. # An extrusion_cali_get response echoes the *requested* nozzle
  2161. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2162. # installed hardware. Feeding it to _update_state clobbered the real
  2163. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2164. # which then failed the #1899 dispatch guard. The response carries no
  2165. # status telemetry, so skip it; the true nozzle comes from pushall.
  2166. # (Same reasoning as get_accessories in _handle_system_response.)
  2167. if not is_kprofile_response:
  2168. self._update_state(print_data)
  2169. def _handle_system_response(self, data: dict):
  2170. """Handle system responses including accessories info.
  2171. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2172. The correct nozzle data comes from push_status, so we don't update
  2173. nozzle type/diameter from get_accessories. We just log the response
  2174. for debugging purposes.
  2175. """
  2176. command = data.get("command")
  2177. if command == "get_accessories":
  2178. # Log response for debugging - but DON'T use it to update nozzle data
  2179. # because it returns stale values (e.g., 'stainless_steel' when the
  2180. # actual nozzle is 'HH01' hardened steel high-flow)
  2181. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2182. def _handle_version_info(self, data: dict):
  2183. """Handle version info response from get_version command.
  2184. Parses firmware version from the 'ota' module in the module list.
  2185. Also extracts AMS unit firmware versions from AMS modules and stores
  2186. them on the corresponding AMS unit in raw_data so the status route can
  2187. expose them to the frontend.
  2188. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2189. - ``ams/<id>`` – original AMS
  2190. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2191. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2192. Message format:
  2193. {
  2194. "command": "get_version",
  2195. "module": [
  2196. {"name": "ota", "sw_ver": "01.08.05.00"},
  2197. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2198. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2199. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2200. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2201. ...
  2202. ]
  2203. }
  2204. """
  2205. modules = data.get("module", [])
  2206. if not isinstance(modules, list):
  2207. return
  2208. state_changed = False
  2209. for module in modules:
  2210. if not isinstance(module, dict):
  2211. continue
  2212. if module.get("name") == "ota":
  2213. version = module.get("sw_ver")
  2214. if version:
  2215. old_version = self.state.firmware_version
  2216. self.state.firmware_version = version
  2217. if old_version != version:
  2218. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2219. state_changed = True
  2220. break
  2221. # Extract AMS unit firmware versions from AMS modules.
  2222. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2223. # Always cache regardless of whether AMS data has arrived yet — get_version
  2224. # often arrives before the first push_status, so caching must be unconditional.
  2225. ams_raw = self.state.raw_data.get("ams")
  2226. for module in modules:
  2227. if not isinstance(module, dict):
  2228. continue
  2229. name = module.get("name", "")
  2230. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2231. continue
  2232. try:
  2233. ams_id = int(name.split("/", 1)[1])
  2234. except (ValueError, IndexError):
  2235. continue
  2236. sw_ver = module.get("sw_ver", "")
  2237. sn = module.get("sn", "")
  2238. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2239. module_type = name.split("/", 1)[0]
  2240. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2241. if sw_ver or sn or module_type:
  2242. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2243. state_changed = True
  2244. # Also directly update any AMS unit already present in raw_data
  2245. if ams_raw and isinstance(ams_raw, list):
  2246. for ams_unit in ams_raw:
  2247. if not isinstance(ams_unit, dict):
  2248. continue
  2249. try:
  2250. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2251. except (ValueError, TypeError):
  2252. unit_id = None
  2253. if unit_id == ams_id:
  2254. if sw_ver:
  2255. ams_unit["sw_ver"] = sw_ver
  2256. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2257. # Only set sn from version info if not already present in AMS data
  2258. if sn and not ams_unit.get("sn"):
  2259. ams_unit["sn"] = sn
  2260. if module_type:
  2261. ams_unit["module_type"] = module_type
  2262. break
  2263. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2264. # included in the broadcast (not just the printer firmware version).
  2265. if state_changed and self.on_state_change:
  2266. self.on_state_change(self.state)
  2267. # Warn if any AMS unit is still missing serial number or firmware version
  2268. # after processing the version info response. Warn only once per connection
  2269. # to avoid repeated noise on older firmware that doesn't report these fields.
  2270. if ams_raw and isinstance(ams_raw, list):
  2271. for ams_unit in ams_raw:
  2272. if not isinstance(ams_unit, dict):
  2273. continue
  2274. ams_id = ams_unit.get("id", "?")
  2275. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2276. key = (ams_id, "sn")
  2277. if key not in self._ams_version_warned:
  2278. self._ams_version_warned.add(key)
  2279. logger.warning(
  2280. "[%s] AMS unit %s: serial number not available in version info",
  2281. self.serial_number,
  2282. ams_id,
  2283. )
  2284. if not ams_unit.get("sw_ver"):
  2285. key = (ams_id, "sw_ver")
  2286. if key not in self._ams_version_warned:
  2287. self._ams_version_warned.add(key)
  2288. logger.warning(
  2289. "[%s] AMS unit %s: firmware version not available in version info",
  2290. self.serial_number,
  2291. ams_id,
  2292. )
  2293. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2294. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2295. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2296. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2297. sw_ver/sn fields without overwriting values already present.
  2298. """
  2299. if not ams_list or not isinstance(ams_list, list):
  2300. return
  2301. cache = self._ams_version_cache
  2302. if not cache:
  2303. return
  2304. for unit in ams_list:
  2305. if not isinstance(unit, dict):
  2306. continue
  2307. raw_id = unit.get("id")
  2308. try:
  2309. unit_id = int(raw_id) if raw_id is not None else None
  2310. except (ValueError, TypeError):
  2311. unit_id = None
  2312. if unit_id is None:
  2313. continue
  2314. cached = cache.get(unit_id)
  2315. if not cached:
  2316. continue
  2317. sw_ver = cached.get("sw_ver") or ""
  2318. sn = cached.get("sn") or ""
  2319. if sw_ver and not unit.get("sw_ver"):
  2320. unit["sw_ver"] = sw_ver
  2321. # Only set sn if not already present in AMS data
  2322. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2323. unit["sn"] = sn
  2324. module_type = cached.get("module_type") or ""
  2325. if module_type and not unit.get("module_type"):
  2326. unit["module_type"] = module_type
  2327. def _parse_xcam_data(self, xcam_data):
  2328. """Parse xcam data for camera settings and AI detection options."""
  2329. if not isinstance(xcam_data, dict):
  2330. return
  2331. current_time = time.time()
  2332. # Helper to check if we should accept incoming value for a module
  2333. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2334. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2335. """Check if we should accept an incoming xcam value.
  2336. OrcaSlicer pattern: After sending a command, ignore incoming data
  2337. for 3 seconds. After that, accept whatever the printer sends.
  2338. """
  2339. if module_name not in self._xcam_hold_start:
  2340. return True # No hold timer, accept incoming
  2341. hold_start = self._xcam_hold_start[module_name]
  2342. elapsed = current_time - hold_start
  2343. if elapsed > self._xcam_hold_time:
  2344. # Hold timer expired - accept incoming and clear hold
  2345. del self._xcam_hold_start[module_name]
  2346. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2347. return True
  2348. # Within hold period - ignore incoming data
  2349. logger.debug(
  2350. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2351. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2352. )
  2353. return False
  2354. # Log all xcam fields for debugging
  2355. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2356. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2357. # fields (spaghetti_detector, etc.) are often stale/cached.
  2358. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2359. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2360. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2361. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2362. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2363. # Sensitivity values: 0=low, 1=medium, 2=high
  2364. if "cfg" in xcam_data:
  2365. cfg = xcam_data["cfg"]
  2366. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2367. def decode_detector(start_bit):
  2368. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2369. sens_bits = (cfg >> start_bit) & 0x3
  2370. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2371. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2372. return enabled, sensitivity
  2373. # Spaghetti detector (bits 5-7)
  2374. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2375. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2376. old_value = self.state.print_options.spaghetti_detector
  2377. if cfg_spaghetti != old_value:
  2378. logger.debug(
  2379. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2380. )
  2381. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2382. # Check hold timer for sensitivity before accepting
  2383. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2384. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2385. logger.debug(
  2386. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2387. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2388. )
  2389. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2390. else:
  2391. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2392. elapsed = current_time - hold_start
  2393. if elapsed <= self._xcam_hold_time:
  2394. logger.debug(
  2395. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2396. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2397. )
  2398. else:
  2399. # Hold expired - accept from cfg
  2400. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2401. logger.debug(
  2402. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2403. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2404. )
  2405. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2406. del self._xcam_hold_start["halt_print_sensitivity"]
  2407. # Pileup detector (bits 8-10)
  2408. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2409. if should_accept_value("pileup_detector", cfg_pileup):
  2410. if cfg_pileup != self.state.print_options.pileup_detector:
  2411. logger.debug(
  2412. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2413. )
  2414. self.state.print_options.pileup_detector = cfg_pileup
  2415. # Pileup sensitivity with hold timer
  2416. if "pileup_sensitivity" not in self._xcam_hold_start:
  2417. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2418. logger.debug(
  2419. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2420. )
  2421. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2422. else:
  2423. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2424. elapsed = current_time - hold_start
  2425. if elapsed > self._xcam_hold_time:
  2426. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2427. logger.debug(
  2428. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2429. )
  2430. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2431. del self._xcam_hold_start["pileup_sensitivity"]
  2432. # Clump/nozzle clumping detector (bits 11-13)
  2433. cfg_clump, cfg_clump_sens = decode_detector(11)
  2434. if should_accept_value("clump_detector", cfg_clump):
  2435. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2436. logger.debug(
  2437. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2438. )
  2439. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2440. # Clump sensitivity with hold timer
  2441. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2442. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2443. logger.debug(
  2444. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2445. )
  2446. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2447. else:
  2448. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2449. elapsed = current_time - hold_start
  2450. if elapsed > self._xcam_hold_time:
  2451. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2452. logger.debug(
  2453. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2454. )
  2455. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2456. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2457. # Airprint detector (bits 14-16)
  2458. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2459. if should_accept_value("airprint_detector", cfg_airprint):
  2460. if cfg_airprint != self.state.print_options.airprint_detector:
  2461. logger.debug(
  2462. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2463. )
  2464. self.state.print_options.airprint_detector = cfg_airprint
  2465. # Airprint sensitivity with hold timer
  2466. if "airprint_sensitivity" not in self._xcam_hold_start:
  2467. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2468. logger.debug(
  2469. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2470. )
  2471. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2472. else:
  2473. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2474. elapsed = current_time - hold_start
  2475. if elapsed > self._xcam_hold_time:
  2476. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2477. logger.debug(
  2478. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2479. )
  2480. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2481. del self._xcam_hold_start["airprint_sensitivity"]
  2482. # Camera settings
  2483. if "ipcam_record" in xcam_data:
  2484. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2485. if "timelapse" in xcam_data:
  2486. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2487. # Track if timelapse was ever active during this print
  2488. if self.state.timelapse and self._was_running:
  2489. self._timelapse_during_print = True
  2490. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2491. if "print_halt" in xcam_data:
  2492. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  2493. # Skip halt_print_sensitivity field - it's always stale ("medium")
  2494. # We read the actual sensitivity from cfg bits 5-6 above
  2495. if "first_layer_inspector" in xcam_data:
  2496. new_value = bool(xcam_data.get("first_layer_inspector"))
  2497. if should_accept_value("first_layer_inspector", new_value):
  2498. self.state.print_options.first_layer_inspector = new_value
  2499. if "printing_monitor" in xcam_data:
  2500. new_value = bool(xcam_data.get("printing_monitor"))
  2501. if should_accept_value("printing_monitor", new_value):
  2502. self.state.print_options.printing_monitor = new_value
  2503. if "buildplate_marker_detector" in xcam_data:
  2504. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  2505. if should_accept_value("buildplate_marker_detector", new_value):
  2506. self.state.print_options.buildplate_marker_detector = new_value
  2507. if "allow_skip_parts" in xcam_data:
  2508. new_value = bool(xcam_data.get("allow_skip_parts"))
  2509. if should_accept_value("allow_skip_parts", new_value):
  2510. self.state.print_options.allow_skip_parts = new_value
  2511. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  2512. # individual boolean fields (which are not sent by the printer)
  2513. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  2514. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  2515. if "auto_recovery_step_loss" in xcam_data:
  2516. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  2517. if "filament_tangle_detect" in xcam_data:
  2518. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  2519. @staticmethod
  2520. def _resolve_local_slot_from_mapping(local_slot: int, mapping_raw: list | None) -> int | None:
  2521. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  2522. The MQTT mapping field is an array of snow-encoded values:
  2523. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  2524. Finds entries where the local slot matches, then computes the global tray ID.
  2525. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  2526. """
  2527. if not isinstance(mapping_raw, list) or not mapping_raw:
  2528. return None
  2529. candidates: set[int] = set()
  2530. for value in mapping_raw:
  2531. if not isinstance(value, int) or value >= 65535:
  2532. continue
  2533. ams_hw_id = value >> 8
  2534. slot = value & 0xFF
  2535. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  2536. candidates.add(ams_hw_id * 4 + local_slot)
  2537. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  2538. candidates.add(ams_hw_id)
  2539. if len(candidates) == 1:
  2540. return candidates.pop()
  2541. return None
  2542. def _maybe_trigger_external_spool_change(self):
  2543. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  2544. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  2545. an external-spool-only filament swap would otherwise never re-run the
  2546. inventory reconciliation that unlinks a stale ams_id=255 assignment
  2547. (#2575). The reconciliation reads vt_tray from live status itself, so we
  2548. just need to re-fire the callback with the current merged AMS data.
  2549. """
  2550. import hashlib
  2551. vt_tray = self.state.raw_data.get("vt_tray")
  2552. if not isinstance(vt_tray, list):
  2553. return
  2554. # Identity fields only — deliberately exclude `remain` so a print's
  2555. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  2556. fp_parts = [
  2557. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  2558. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  2559. for vt in vt_tray
  2560. if isinstance(vt, dict)
  2561. ]
  2562. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  2563. if vt_hash == self._previous_vt_tray_hash:
  2564. return
  2565. self._previous_vt_tray_hash = vt_hash
  2566. if self.on_ams_change:
  2567. logger.debug(
  2568. "[%s] External spool (vt_tray) changed, triggering sync callback",
  2569. self.serial_number,
  2570. )
  2571. self.on_ams_change(self.state.raw_data.get("ams") or [])
  2572. def _normalize_a2l_am_units(self, ams_list) -> None:
  2573. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  2574. id 16 -> 6 in place, as early as possible, so every downstream reader —
  2575. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  2576. the DB constraint — sees the normalised id and needs no special-casing.
  2577. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  2578. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  2579. both the dict-wrapped and bare-list AMS shapes.
  2580. """
  2581. if not isinstance(ams_list, list):
  2582. return
  2583. for unit in ams_list:
  2584. if not isinstance(unit, dict):
  2585. continue
  2586. try:
  2587. uid = int(unit.get("id"))
  2588. except (TypeError, ValueError):
  2589. continue
  2590. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  2591. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  2592. if not self._has_a2l_am_unit:
  2593. logger.info(
  2594. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  2595. self.serial_number,
  2596. A2L_LITE_NORMALIZED_AMS_ID,
  2597. )
  2598. self._has_a2l_am_unit = True
  2599. def _parse_fila_switch(self, data: dict) -> None:
  2600. """Read the Filament Track Switch block out of a print payload — #1162.
  2601. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  2602. separate from the rest of the state update because ``_handle_ams_data``
  2603. needs the answer before it parses the AMS info bits, and that runs first.
  2604. """
  2605. if not isinstance(data.get("device"), dict):
  2606. return
  2607. fs_data = data["device"].get("fila_switch")
  2608. if not isinstance(fs_data, dict):
  2609. return
  2610. in_raw = fs_data.get("in")
  2611. out_raw = fs_data.get("out")
  2612. self.state.fila_switch = FilaSwitchState(
  2613. installed=True,
  2614. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2615. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2616. stat=int(fs_data.get("stat", 0) or 0),
  2617. info=int(fs_data.get("info", 0) or 0),
  2618. )
  2619. def _parse_extruder_slots(self, data: dict) -> None:
  2620. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  2621. Absent on printers that do not report the block, in which case the
  2622. previous answer is kept rather than cleared: a partial payload carrying
  2623. only temperatures must not look like "both hotends are now empty".
  2624. """
  2625. device = data.get("device")
  2626. if not isinstance(device, dict):
  2627. return
  2628. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  2629. if not isinstance(info, list) or not info:
  2630. return
  2631. slots: dict[int, ExtruderSlot] = {}
  2632. for entry in info:
  2633. if not isinstance(entry, dict) or "id" not in entry:
  2634. continue
  2635. try:
  2636. ext_id = int(entry["id"])
  2637. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  2638. flags = int(entry.get("info", 0) or 0)
  2639. except (TypeError, ValueError):
  2640. continue
  2641. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  2642. ams_id = slot_id = None
  2643. else:
  2644. ams_id = (snow >> 8) & 0xFF
  2645. slot_id = snow & 0xFF
  2646. slots[ext_id] = ExtruderSlot(
  2647. ams_id=ams_id,
  2648. slot_id=slot_id,
  2649. has_filament=bool(flags & 0b10),
  2650. )
  2651. if slots:
  2652. self.state.extruder_slots = slots
  2653. def _handle_ams_data(self, ams_data):
  2654. """Handle AMS data changes for Spoolman integration.
  2655. This is called when we receive top-level AMS data in MQTT messages.
  2656. It detects changes and triggers the callback for Spoolman sync.
  2657. """
  2658. import hashlib
  2659. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  2660. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  2661. ams_list = None
  2662. if isinstance(ams_data, dict):
  2663. if "ams" in ams_data:
  2664. ams_list = ams_data["ams"]
  2665. self._normalize_a2l_am_units(ams_list)
  2666. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  2667. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  2668. if non_list_fields:
  2669. self._debug_on_change(
  2670. "ams_dict_fields",
  2671. non_list_fields,
  2672. "[%s] AMS dict fields: %s",
  2673. self.serial_number,
  2674. non_list_fields,
  2675. )
  2676. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  2677. # when checking if we're in filament change mode for tray_now disambiguation
  2678. if "ams_status" in ams_data:
  2679. raw_ams_status = ams_data["ams_status"]
  2680. if isinstance(raw_ams_status, str):
  2681. try:
  2682. self.state.ams_status = int(raw_ams_status)
  2683. except ValueError:
  2684. self.state.ams_status = 0
  2685. else:
  2686. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2687. # Compute main and sub status
  2688. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2689. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2690. self._debug_on_change(
  2691. "ams_status:ams",
  2692. self.state.ams_status,
  2693. "[%s] ams_status: %s (main=%s, sub=%s)",
  2694. self.serial_number,
  2695. self.state.ams_status,
  2696. self.state.ams_status_main,
  2697. self.state.ams_status_sub,
  2698. )
  2699. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  2700. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  2701. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  2702. # next compatible slot (#2587). Stored raw here; globalised at the API
  2703. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  2704. # these are local slot numbers (0-3), not global IDs.
  2705. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  2706. if _tk in ams_data:
  2707. _raw = ams_data[_tk]
  2708. if isinstance(_raw, str):
  2709. try:
  2710. _val = int(_raw)
  2711. except ValueError:
  2712. _val = 255
  2713. else:
  2714. _val = _raw if _raw is not None else 255
  2715. prev = getattr(self.state, _attr)
  2716. setattr(self.state, _attr, _val)
  2717. # Log changes only while paused — the moment the operator cares —
  2718. # so a healthy print's normal tar churn doesn't spam the log.
  2719. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  2720. logger.info(
  2721. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  2722. self.serial_number,
  2723. _tk,
  2724. _val,
  2725. )
  2726. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  2727. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  2728. if "tray_now" in ams_data:
  2729. raw_tray_now = ams_data["tray_now"]
  2730. # Convert string to int if needed
  2731. if isinstance(raw_tray_now, str):
  2732. try:
  2733. parsed_tray_now = int(raw_tray_now)
  2734. except ValueError:
  2735. parsed_tray_now = 255
  2736. else:
  2737. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  2738. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  2739. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  2740. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  2741. # — disambiguated below using MQTT mapping field
  2742. ams_map = self.state.ams_extruder_map
  2743. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  2744. # First, check if we have a pending target that matches this slot
  2745. pending_target = self.state.pending_tray_target
  2746. if pending_target is not None:
  2747. pending_slot = pending_target % 4
  2748. if pending_slot == parsed_tray_now:
  2749. # Slot matches our pending target - use the full global ID
  2750. logger.debug(
  2751. f"[{self.serial_number}] H2D tray_now disambiguation: "
  2752. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  2753. )
  2754. self.state.tray_now = pending_target
  2755. # Clear pending target now that load is confirmed
  2756. self.state.pending_tray_target = None
  2757. else:
  2758. # Slot doesn't match our pending target - something changed, use slot as-is
  2759. logger.warning(
  2760. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  2761. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  2762. )
  2763. self.state.tray_now = parsed_tray_now
  2764. # Clear pending target since it's stale
  2765. self.state.pending_tray_target = None
  2766. else:
  2767. # No pending target - use h2d_extruder_snow for accurate disambiguation
  2768. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  2769. active_ext = self.state.active_extruder # 0=right, 1=left
  2770. # Best source: use snow value from device.extruder.info if available
  2771. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  2772. if snow_tray is not None and snow_tray != 255:
  2773. # snow_tray is already normalized to global ID
  2774. # Verify the slot matches what we see in tray_now
  2775. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  2776. snow_slot = snow_tray % 4 if snow_tray < 128 else (0 if snow_tray <= 135 else -1)
  2777. if snow_slot == parsed_tray_now:
  2778. if self.state.tray_now != snow_tray:
  2779. logger.debug(
  2780. f"[{self.serial_number}] H2D tray_now from snow: "
  2781. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  2782. )
  2783. self.state.tray_now = snow_tray
  2784. else:
  2785. # Slot mismatch - snow field may not have updated yet, trust snow
  2786. logger.debug(
  2787. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  2788. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  2789. )
  2790. self.state.tray_now = snow_tray
  2791. else:
  2792. # Fallback: snow not available, use ams_extruder_map (less reliable)
  2793. # Find ALL AMS units on the active extruder
  2794. ams_on_extruder = []
  2795. for ams_id_str, ext_id in ams_map.items():
  2796. if ext_id == active_ext:
  2797. try:
  2798. ams_on_extruder.append(int(ams_id_str))
  2799. except ValueError:
  2800. pass # Skip AMS IDs that aren't valid integers
  2801. if len(ams_on_extruder) == 1:
  2802. # Single AMS on this extruder - unambiguous
  2803. active_ams_id = ams_on_extruder[0]
  2804. if 128 <= active_ams_id <= 135:
  2805. # AMS-HT: single slot per unit, global ID = unit ID
  2806. global_tray_id = active_ams_id
  2807. else:
  2808. global_tray_id = active_ams_id * 4 + parsed_tray_now
  2809. logger.debug(
  2810. f"[{self.serial_number}] H2D tray_now fallback: "
  2811. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  2812. )
  2813. self.state.tray_now = global_tray_id
  2814. elif len(ams_on_extruder) > 1:
  2815. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  2816. current_tray = self.state.tray_now
  2817. # Determine which AMS unit and slot the current tray belongs to
  2818. if 0 <= current_tray <= 15:
  2819. current_ams = current_tray // 4
  2820. current_slot = current_tray % 4
  2821. elif 128 <= current_tray <= 135:
  2822. current_ams = current_tray # AMS-HT: ID = tray ID
  2823. current_slot = 0
  2824. else:
  2825. current_ams = -1
  2826. current_slot = -1
  2827. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  2828. # Current is valid and matches slot - keep it
  2829. logger.debug(
  2830. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  2831. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  2832. )
  2833. else:
  2834. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  2835. if parsed_tray_now > 0:
  2836. candidates = [a for a in ams_on_extruder if a <= 3]
  2837. else:
  2838. candidates = ams_on_extruder
  2839. if len(candidates) == 1:
  2840. cand = candidates[0]
  2841. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  2842. logger.debug(
  2843. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  2844. f"narrowed to AMS {cand} -> global ID {resolved}"
  2845. )
  2846. self.state.tray_now = resolved
  2847. else:
  2848. # Genuinely ambiguous - use slot as-is (will be wrong for non-first AMS)
  2849. logger.warning(
  2850. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on extruder {active_ext}, "
  2851. f"no snow field, using slot {parsed_tray_now} (may be incorrect)"
  2852. )
  2853. self.state.tray_now = parsed_tray_now
  2854. else:
  2855. # No AMS on this extruder - use slot as-is
  2856. logger.warning(
  2857. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  2858. f"using slot {parsed_tray_now}"
  2859. )
  2860. self.state.tray_now = parsed_tray_now
  2861. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  2862. # Single-nozzle printer with tray_now in 0-3 range.
  2863. # #1822: H2S firmware reports tray_now as the AMS's idle
  2864. # slot (typically 0) when the active feed is actually the
  2865. # external spool. X1C / P1S / A1 correctly report 254 in
  2866. # that case; H2S does not. When the slicer-captured
  2867. # ams_mapping is all-external (every entry == -1), the
  2868. # print can only be feeding from the external spool, so
  2869. # promote tray_now to 254. Mixed (e.g. [5, -1]) and
  2870. # AMS-only mappings are NOT overridden — there's no
  2871. # evidence the firmware misreports in those cases. Prints
  2872. # started without a captured mapping (printer-screen start,
  2873. # or before Bambuddy connected) fall through unchanged.
  2874. captured = self._captured_ams_mapping
  2875. if captured and all(s == -1 for s in captured):
  2876. if self.state.tray_now != 254:
  2877. logger.debug(
  2878. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  2879. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  2880. )
  2881. self.state.tray_now = 254
  2882. else:
  2883. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  2884. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  2885. # (snow-encoded) to resolve the correct AMS unit.
  2886. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  2887. try:
  2888. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  2889. except (ValueError, TypeError):
  2890. ams_exist = 0
  2891. num_ams = bin(ams_exist).count("1")
  2892. if self._has_a2l_am_unit and num_ams <= 1:
  2893. # A2L AMS-Lite (normalised unit 6): the firmware reports
  2894. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  2895. # otherwise usage tracking keys the wrong spool (it would
  2896. # deduct from AMS 0's slot). Confirmed by capture:
  2897. # tray_now="2" while printing physical slot 3.
  2898. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  2899. elif num_ams > 1:
  2900. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  2901. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  2902. if self._has_a2l_am_unit:
  2903. # A2L Lite + a regular AMS attached together is out of
  2904. # scope: the flat mapping ids are unknown for that combo
  2905. # and could collide with AMS 0. Fall through to the
  2906. # mapping-based resolve, but warn — a capture is needed.
  2907. logger.warning(
  2908. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  2909. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  2910. self.serial_number,
  2911. )
  2912. mapping_raw = self.state.raw_data.get("mapping")
  2913. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  2914. if resolved is not None:
  2915. if resolved != parsed_tray_now:
  2916. logger.debug(
  2917. f"[{self.serial_number}] Multi-AMS tray_now: "
  2918. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  2919. )
  2920. self.state.tray_now = resolved
  2921. else:
  2922. # No mapping available (not printing, or ambiguous) — use as-is.
  2923. # This matches the old behavior and is correct for AMS 0.
  2924. self.state.tray_now = parsed_tray_now
  2925. else:
  2926. # Single AMS — local slot 0-3 equals global ID
  2927. self.state.tray_now = parsed_tray_now
  2928. else:
  2929. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  2930. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  2931. # During filament change, the printer sends 255 first (unload), then the slot.
  2932. # We only clear pending_tray_target explicitly in ams_unload_filament().
  2933. # Trust the printer's reported value.
  2934. self.state.tray_now = parsed_tray_now
  2935. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  2936. # Valid physical trays: 0-15 (regular AMS), 24-27 (A2L AMS-Lite,
  2937. # normalised unit 6), 128-135 (AMS-HT), 254 (external spool)
  2938. tn = self.state.tray_now
  2939. if (
  2940. (0 <= tn <= 15)
  2941. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  2942. or (128 <= tn <= 135)
  2943. or tn == 254
  2944. ):
  2945. # Log tray change for mid-print usage splitting. Gate on the
  2946. # print-lifecycle flags (`_was_running` set on first RUNNING /
  2947. # new print, `_completion_triggered` set when on_print_complete
  2948. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  2949. # firmware briefly transitions out of RUNNING during AMS
  2950. # auto-fallback (#957), so a literal-string gate misses the
  2951. # switch and the usage tracker double-credits at completion.
  2952. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  2953. self.state.tray_change_log.append((tn, self.state.layer_num))
  2954. logger.info(
  2955. "[%s] Tray change during print: tray=%d at layer=%d",
  2956. self.serial_number,
  2957. tn,
  2958. self.state.layer_num,
  2959. )
  2960. if self.on_tray_change:
  2961. self.on_tray_change(tn, self.state.layer_num)
  2962. self.state.last_loaded_tray = self.state.tray_now
  2963. self._debug_on_change(
  2964. "tray_now",
  2965. self.state.tray_now,
  2966. "[%s] tray_now updated: %s",
  2967. self.serial_number,
  2968. self.state.tray_now,
  2969. )
  2970. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  2971. # state when checking filament change mode for H2D disambiguation
  2972. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  2973. # We've already processed the status fields above, so just return if no ams list
  2974. if ams_list is None:
  2975. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  2976. return
  2977. elif isinstance(ams_data, list):
  2978. ams_list = ams_data
  2979. self._normalize_a2l_am_units(ams_list)
  2980. else:
  2981. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  2982. return
  2983. # Merge AMS data instead of replacing, to handle partial updates
  2984. # During prints, the printer may only send updates for active AMS units
  2985. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  2986. existing_ams = self.state.raw_data.get("ams", [])
  2987. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  2988. # Update existing units with new data, add new units
  2989. for ams_unit in ams_list:
  2990. ams_id = ams_unit.get("id")
  2991. if ams_id is not None:
  2992. existing_unit = existing_by_id.get(ams_id)
  2993. if existing_unit and "tray" in ams_unit:
  2994. # Deep merge trays to preserve fields from previous updates
  2995. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  2996. merged_trays = []
  2997. for new_tray in ams_unit.get("tray", []):
  2998. tray_id = new_tray.get("id")
  2999. if tray_id is not None and tray_id in existing_trays:
  3000. # Merge: start with existing, update with new non-empty values
  3001. merged_tray = existing_trays[tray_id].copy()
  3002. # Detect slot-clearing updates (spool removal):
  3003. # When tray_type is explicitly empty, clear everything
  3004. # including RFID data (tag_uid/tray_uuid).
  3005. slot_clearing = new_tray.get("tray_type") == ""
  3006. # Some printers (e.g. H2D) only send {id, state} in
  3007. # incremental updates when a tray is not fully loaded.
  3008. # state=11 means loaded; other values (9=empty,
  3009. # 10=spool present but filament not in feeder) indicate
  3010. # the slot should be cleared. Without this, old
  3011. # tray_type/tray_color persist indefinitely (#784).
  3012. #
  3013. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3014. # tray high-temp dry box, id >= 128) reports its loaded
  3015. # tray as state=9, not 11 — it doesn't feed filament into
  3016. # a shared buffer the way a 4-slot AMS does. Applying the
  3017. # `state != 11 → empty` rule to an HT unit wiped a present
  3018. # spool on every power-on, when the printer sends a partial
  3019. # {id, state=9} for the HT tray (#2594). Skip the state
  3020. # heuristic for HT units — a genuine HT spool removal still
  3021. # clears via the explicit tray_type=="" case above and the
  3022. # tray_exist_bits cleanup below.
  3023. try:
  3024. _is_ht_unit = int(ams_id) >= 128
  3025. except (TypeError, ValueError):
  3026. _is_ht_unit = False
  3027. tray_state = new_tray.get("state")
  3028. if (
  3029. tray_state is not None
  3030. and tray_state != 11
  3031. and not _is_ht_unit
  3032. and "tray_type" not in new_tray
  3033. and merged_tray.get("tray_type")
  3034. ):
  3035. logger.info(
  3036. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3037. self.serial_number,
  3038. ams_id,
  3039. tray_id,
  3040. tray_state,
  3041. )
  3042. slot_clearing = True
  3043. # The incremental update only has {id, state} — inject
  3044. # empty values for all content fields so the merge loop
  3045. # below clears the stale data from merged_tray.
  3046. new_tray.update(
  3047. {
  3048. "tray_type": "",
  3049. "tray_sub_brands": "",
  3050. "tray_color": "",
  3051. "tray_id_name": "",
  3052. "tray_info_idx": "",
  3053. "tag_uid": "0000000000000000",
  3054. "tray_uuid": "00000000000000000000000000000000",
  3055. "remain": 0,
  3056. "k": None,
  3057. "cali_idx": None,
  3058. }
  3059. )
  3060. for key, value in new_tray.items():
  3061. # Fields that should always be updated (even with empty/zero values):
  3062. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3063. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3064. # tray_id_name: slot content indicators that must be cleared
  3065. # when a spool is removed (fixes #147 - old AMS empty slot)
  3066. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3067. # They are only cleared during spool removal (slot_clearing=True).
  3068. # Periodic AMS updates often include empty RFID fields which
  3069. # would overwrite valid data from the initial pushall.
  3070. always_update_fields = (
  3071. "remain",
  3072. "k",
  3073. "id",
  3074. "cali_idx",
  3075. "tray_type",
  3076. "tray_sub_brands",
  3077. "tray_info_idx",
  3078. "tray_color",
  3079. "tray_id_name",
  3080. )
  3081. if (
  3082. key in always_update_fields
  3083. or slot_clearing
  3084. or value
  3085. not in (
  3086. None,
  3087. "",
  3088. "0000000000000000",
  3089. "00000000000000000000000000000000",
  3090. )
  3091. ):
  3092. merged_tray[key] = value
  3093. merged_trays.append(merged_tray)
  3094. else:
  3095. merged_trays.append(new_tray)
  3096. # Update ams_unit with merged trays. Spread existing_unit
  3097. # FIRST so top-level fields the partial update omits —
  3098. # dry_time, info (which drives dry_status / dry_sub_status),
  3099. # humidity, temp — are preserved instead of dropped. The
  3100. # printer sends tray-bearing partials that carry no drying
  3101. # fields; without this, dry_time reads as absent → 0 and the
  3102. # falling-edge detector below fires a false "drying complete"
  3103. # (#1462). Mirrors the no-tray branch's merge semantics.
  3104. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3105. elif existing_unit:
  3106. # Partial update without tray data: merge new fields into existing
  3107. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3108. ams_unit = {**existing_unit, **ams_unit}
  3109. existing_by_id[ams_id] = ams_unit
  3110. # Convert back to list, sorted by ID for consistent ordering
  3111. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  3112. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3113. # Shared with the VP bridge cache so the slicer-facing view stays in
  3114. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3115. # for the full rationale and the printer-shutdown guard.
  3116. if isinstance(ams_data, dict):
  3117. apply_tray_exist_bits(
  3118. merged_ams,
  3119. ams_data.get("tray_exist_bits"),
  3120. power_on_flag=ams_data.get("power_on_flag", True),
  3121. log_label=self.serial_number,
  3122. annotate_exists=True,
  3123. )
  3124. self.state.raw_data["ams"] = merged_ams
  3125. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3126. self._apply_ams_version_cache(merged_ams)
  3127. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3128. self.state.last_ams_update = time.time()
  3129. self._debug_on_change(
  3130. "merged_ams",
  3131. (len(ams_list), len(merged_ams)),
  3132. "[%s] Merged AMS data: %s new units, %s total",
  3133. self.serial_number,
  3134. len(ams_list),
  3135. len(merged_ams),
  3136. )
  3137. # Extract ams_extruder_map from each AMS unit's info field
  3138. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3139. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3140. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3141. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3142. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3143. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3144. #
  3145. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3146. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3147. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3148. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3149. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3150. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3151. # the switch being installed.
  3152. #
  3153. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3154. # the full map. Merge into existing map to preserve entries from prior updates.
  3155. fts_installed = self.state.fila_switch.installed
  3156. inlet_moves: list[tuple[int, str]] = []
  3157. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3158. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3159. for ams_unit in merged_ams:
  3160. ams_id = ams_unit.get("id")
  3161. info = ams_unit.get("info")
  3162. if ams_id is not None and info is not None:
  3163. try:
  3164. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3165. info_val = int(str(info), 16)
  3166. # Extract 4 bits starting at bit 8 for extruder assignment
  3167. extruder_id = (info_val >> 8) & 0xF
  3168. if extruder_id == 0xE:
  3169. if fts_installed:
  3170. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3171. if inlet is not None:
  3172. previous = ams_switch_inlet.get(str(ams_id))
  3173. ams_switch_inlet[str(ams_id)] = inlet
  3174. self._debug_on_change(
  3175. f"ams_inlet:{ams_id}",
  3176. inlet,
  3177. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3178. self.serial_number,
  3179. ams_id,
  3180. info,
  3181. inlet,
  3182. )
  3183. if previous is not None and previous != inlet:
  3184. # Only a genuine move, never the first sighting:
  3185. # re-applying K-profiles on every reconnect would
  3186. # fight a binding the operator set deliberately.
  3187. logger.info(
  3188. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3189. self.serial_number,
  3190. ams_id,
  3191. inlet,
  3192. previous,
  3193. )
  3194. inlet_moves.append((int(ams_id), inlet))
  3195. continue
  3196. ams_extruder_map[str(ams_id)] = extruder_id
  3197. self._debug_on_change(
  3198. f"ams_info:{ams_id}",
  3199. (info, extruder_id),
  3200. "[%s] AMS %s info=0x%s -> extruder %s",
  3201. self.serial_number,
  3202. ams_id,
  3203. info,
  3204. extruder_id,
  3205. )
  3206. except (ValueError, TypeError):
  3207. pass # Skip AMS units with unparseable info bitmask values
  3208. if ams_extruder_map:
  3209. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3210. self.state.ams_extruder_map = ams_extruder_map
  3211. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3212. if ams_switch_inlet:
  3213. self.state.ams_switch_inlet = ams_switch_inlet
  3214. for moved_ams_id, moved_inlet in inlet_moves:
  3215. if self.on_fts_inlet_change:
  3216. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3217. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3218. # BambuStudio DevFilaSystem.cpp parses info bits:
  3219. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3220. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3221. for ams_unit in merged_ams:
  3222. info = ams_unit.get("info")
  3223. if info is not None:
  3224. try:
  3225. info_val = int(str(info), 16)
  3226. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3227. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3228. except (ValueError, TypeError):
  3229. pass # Skip unparseable info values
  3230. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3231. if "dry_sf_reason" in ams_unit:
  3232. sf_reason = ams_unit["dry_sf_reason"]
  3233. if isinstance(sf_reason, list):
  3234. ams_unit["dry_sf_reason"] = [
  3235. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3236. ]
  3237. else:
  3238. ams_unit["dry_sf_reason"] = []
  3239. # Persist updated drying fields back to raw_data
  3240. self.state.raw_data["ams"] = merged_ams
  3241. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3242. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3243. # — fire the callback so smart-plug auto-off-after-drying can run,
  3244. # and drop our cached target-cycle params so the badge stops claiming
  3245. # an active cycle. Works identically for queue-triggered, ambient,
  3246. # and manual drying because we observe the firmware-reported state.
  3247. for ams_unit in merged_ams:
  3248. try:
  3249. ams_id = int(ams_unit.get("id", -1))
  3250. except (TypeError, ValueError):
  3251. continue
  3252. if ams_id < 0:
  3253. continue
  3254. # Only evaluate the edge when this update carries an explicit
  3255. # dry_time. An absent / unparseable value is NOT zero — treating
  3256. # it as 0 lets a tray-only partial fake a drying-complete edge
  3257. # (#1462). Skip without touching the remembered value so the
  3258. # next update that DOES carry dry_time sees the true previous.
  3259. raw_dry_time = ams_unit.get("dry_time")
  3260. if raw_dry_time is None:
  3261. continue
  3262. try:
  3263. current = int(raw_dry_time)
  3264. except (TypeError, ValueError):
  3265. continue
  3266. # A dry_time of 0 only means "finished" when the unit also reports
  3267. # an idle phase. Between the command ack and the countdown settling
  3268. # the firmware publishes a transient 0 while the AMS is still
  3269. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3270. # 12-hour cycle. Taking that at face value dropped the cached target
  3271. # (leaving the badge to guess the filament from tray 1, so a PLA
  3272. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3273. # schedules smart-plug auto-off. dry_status comes from the same info
  3274. # hex parsed above; when it is absent we let the edge through, so a
  3275. # firmware that never reports one still ends its cycles.
  3276. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3277. # Leave the remembered value alone, exactly as the absent-
  3278. # dry_time skip above does: whichever push ends the cycle for
  3279. # real must still see a non-zero previous.
  3280. logger.debug(
  3281. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3282. self.serial_number,
  3283. ams_id,
  3284. ams_unit.get("dry_status"),
  3285. )
  3286. continue
  3287. previous = self._previous_dry_times.get(ams_id, 0)
  3288. self._previous_dry_times[ams_id] = current
  3289. if previous > 0 and current == 0:
  3290. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  3291. if self.on_drying_complete:
  3292. self.on_drying_complete(ams_id)
  3293. # Create a hash of relevant AMS data to detect changes.
  3294. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  3295. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  3296. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  3297. # above but leaves the raw payload's tracked fields untouched — so a
  3298. # raw-based hash never flips and on_ams_change never fires, leaving the
  3299. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  3300. # always spans every unit, so a partial single-unit update can't produce a
  3301. # spuriously different hash from a full pushall.
  3302. ams_hash_data = []
  3303. for ams_unit in merged_ams:
  3304. for tray in ams_unit.get("tray", []):
  3305. # Include fields that matter for filament tracking
  3306. ams_hash_data.append(
  3307. f"{ams_unit.get('id')}:{tray.get('id')}:"
  3308. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  3309. )
  3310. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  3311. # Only trigger callback if AMS data actually changed
  3312. if ams_hash != self._previous_ams_hash:
  3313. self._previous_ams_hash = ams_hash
  3314. if self.on_ams_change:
  3315. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  3316. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  3317. # may lack fields like 'remain' that the merged state preserves
  3318. self.on_ams_change(merged_ams)
  3319. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  3320. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  3321. # or cali_idx — so an assignment that only swaps the filament id on an
  3322. # already-loaded slot would not flip the hash, and gating the check on
  3323. # it would miss exactly the confirmation we are after.
  3324. if self._pending_assignments:
  3325. self._check_assignment_verifications()
  3326. def _log_drying_cycle_end(
  3327. self,
  3328. ams_id: int,
  3329. remaining: int,
  3330. ams_unit: dict,
  3331. target: dict[str, object] | None,
  3332. ) -> None:
  3333. """Report a finished drying cycle, with the firmware's reason when it was
  3334. cut short (#2770).
  3335. A cycle that reaches its configured duration needs no explanation and
  3336. keeps the one-line "drying complete" it has always had. One that ends
  3337. with most of its countdown left was ended by somebody, and there are
  3338. only two candidates: a stop Bambuddy sent — the print-takes-priority
  3339. stop, or the user's Stop button — which is named as such, or the
  3340. firmware.
  3341. For the firmware case the only account of why lives in fields we already
  3342. parse but have never written down: the ``dry_status`` /
  3343. ``dry_sub_status`` phase from the info hex, the per-unit
  3344. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  3345. that moment. Logging them at INFO puts them in every support bundle by
  3346. default, which is what a report like #2770 needs before its cause can be
  3347. argued about at all.
  3348. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  3349. logged for every cycle, early or not, because they are what decides
  3350. whether auto-drying re-arms. Reconstructing them for #2770 meant
  3351. cross-referencing hourly alarm lines against 30-second scheduler debug
  3352. that was switched off at the time; one line here says it outright — a
  3353. cycle ending at 63 degC with the reading still above the threshold is
  3354. the whole shape of the re-arm loop.
  3355. """
  3356. box = f"temp={ams_unit.get('temp')} humidity={ams_unit.get('humidity_raw', ams_unit.get('humidity'))}"
  3357. if ams_id in self._drying_stops_sent:
  3358. self._drying_stops_sent.discard(ams_id)
  3359. logger.info(
  3360. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  3361. self.serial_number,
  3362. ams_id,
  3363. remaining,
  3364. box,
  3365. )
  3366. return
  3367. if remaining <= _EARLY_DRY_END_MINUTES:
  3368. logger.info(
  3369. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  3370. self.serial_number,
  3371. ams_id,
  3372. remaining,
  3373. box,
  3374. )
  3375. return
  3376. requested_minutes: int | None = None
  3377. if target is not None:
  3378. try:
  3379. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  3380. except (TypeError, ValueError):
  3381. requested_minutes = None
  3382. logger.info(
  3383. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  3384. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  3385. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  3386. self.serial_number,
  3387. ams_id,
  3388. remaining,
  3389. requested_minutes if requested_minutes is not None else "?",
  3390. ams_unit.get("dry_status"),
  3391. ams_unit.get("dry_sub_status"),
  3392. ams_unit.get("dry_sf_reason") or [],
  3393. [e.full_code for e in self.state.hms_errors] or "none",
  3394. box,
  3395. )
  3396. def register_assignment_verification(
  3397. self,
  3398. ams_id: int,
  3399. tray_id: int,
  3400. tray_info_idx: str,
  3401. tray_color: str,
  3402. cali_idx: int | None,
  3403. ) -> None:
  3404. """Record an assignment we just pushed so subsequent AMS telemetry can
  3405. confirm the tray actually accepted it (#2582).
  3406. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  3407. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  3408. accepted filament id back in the per-tray push, so a match means the
  3409. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  3410. signal so we can specifically flag "filament loaded but K-profile not
  3411. applied", which is the exact symptom the reporter chased via flow-cal.
  3412. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  3413. there is nothing to verify and no record is stored.
  3414. """
  3415. want_idx = (tray_info_idx or "").strip().upper()
  3416. if not want_idx:
  3417. return
  3418. self._pending_assignments[(ams_id, tray_id)] = {
  3419. "tray_info_idx": want_idx,
  3420. "tray_color": (tray_color or "").strip().upper(),
  3421. "cali_idx": cali_idx,
  3422. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  3423. "last_seen_idx": None,
  3424. }
  3425. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  3426. """Locate the live tray dict for a pending verification.
  3427. External spools (ams_id 255) live in ``vt_tray`` under global ids
  3428. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  3429. report a single tray whose id may not equal the logical tray_id, so fall
  3430. back to the sole tray when an id match fails.
  3431. """
  3432. raw = self.state.raw_data or {}
  3433. if ams_id == 255:
  3434. want_ext = 254 + tray_id
  3435. for vt in raw.get("vt_tray", []) or []:
  3436. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  3437. return vt
  3438. return None
  3439. for unit in raw.get("ams", []) or []:
  3440. if str(unit.get("id")) != str(ams_id):
  3441. continue
  3442. trays = unit.get("tray", []) or []
  3443. for tray in trays:
  3444. if str(tray.get("id")) == str(tray_id):
  3445. return tray
  3446. if ams_id >= 128 and len(trays) == 1:
  3447. return trays[0]
  3448. return None
  3449. return None
  3450. def _check_assignment_verifications(self) -> None:
  3451. """Compare each pending assignment against live tray telemetry and fire
  3452. ``on_assignment_verified`` on a match or once the deadline passes.
  3453. Runs on every AMS push. Non-matching-but-still-within-window entries are
  3454. left in place for the next push. The timeout branch only fires when a
  3455. later push arrives after the deadline; if the printer goes silent we
  3456. simply never confirm, which is preferable to inventing a failure.
  3457. """
  3458. now = time.monotonic()
  3459. for key, want in list(self._pending_assignments.items()):
  3460. ams_id, tray_id = key
  3461. tray = self._find_verify_tray(ams_id, tray_id)
  3462. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  3463. if tray is not None and actual_idx:
  3464. want["last_seen_idx"] = actual_idx
  3465. if actual_idx and actual_idx == want["tray_info_idx"]:
  3466. self._pending_assignments.pop(key, None)
  3467. kprofile_applied = True
  3468. want_cali = want.get("cali_idx")
  3469. if want_cali is not None and want_cali >= 0:
  3470. actual_cali = tray.get("cali_idx")
  3471. kprofile_applied = actual_cali == want_cali
  3472. self._fire_assignment_verified(
  3473. ams_id,
  3474. tray_id,
  3475. True,
  3476. {
  3477. "tray_info_idx": actual_idx,
  3478. "kprofile_applied": kprofile_applied,
  3479. },
  3480. )
  3481. elif now >= want["deadline"]:
  3482. self._pending_assignments.pop(key, None)
  3483. self._fire_assignment_verified(
  3484. ams_id,
  3485. tray_id,
  3486. False,
  3487. {
  3488. "expected_tray_info_idx": want["tray_info_idx"],
  3489. "actual_tray_info_idx": want.get("last_seen_idx"),
  3490. # True when we saw the tray at least once (so the push
  3491. # channel is alive and the printer really stored a
  3492. # different/blank id) vs never observing it at all.
  3493. "saw_tray": want.get("last_seen_idx") is not None,
  3494. },
  3495. )
  3496. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  3497. if verified:
  3498. logger.info(
  3499. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  3500. self.serial_number,
  3501. ams_id,
  3502. tray_id,
  3503. detail.get("tray_info_idx"),
  3504. detail.get("kprofile_applied"),
  3505. )
  3506. else:
  3507. logger.warning(
  3508. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  3509. self.serial_number,
  3510. ams_id,
  3511. tray_id,
  3512. detail.get("expected_tray_info_idx"),
  3513. detail.get("actual_tray_info_idx"),
  3514. detail.get("saw_tray"),
  3515. )
  3516. if self.on_assignment_verified:
  3517. try:
  3518. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  3519. except Exception:
  3520. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  3521. @staticmethod
  3522. def _probe_number(value, fallback: float | None = None) -> float | None:
  3523. """Coerce a telemetry field to a number, or return `fallback`.
  3524. Firmware is inconsistent about whether these arrive as ints or as
  3525. numeric strings, and the probe must never raise on a surprise type.
  3526. """
  3527. try:
  3528. return float(value)
  3529. except (TypeError, ValueError):
  3530. return fallback
  3531. def _probe_end_of_print(self, data: dict) -> None:
  3532. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  3533. Opens on the first frame that looks like end-of-print (last object
  3534. layer reached, progress at 99+, or no remaining time), then logs each
  3535. frame in which any probed field changed, and closes on the transition
  3536. out of RUNNING. Armed once per print — see the module-level comment on
  3537. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  3538. currently see into.
  3539. Read-only with respect to printer state: this is instrumentation, and
  3540. nothing downstream may come to depend on it.
  3541. """
  3542. if not logger.isEnabledFor(logging.DEBUG):
  3543. return
  3544. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  3545. return
  3546. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  3547. if not present:
  3548. return
  3549. if not self._eop_probe_open:
  3550. # Open on any end-of-print signal. Read from the raw frame first so
  3551. # the frame that *carries* the signal is itself captured — state
  3552. # fields are only updated further down this same call.
  3553. layer = self._probe_number(data.get("layer_num"), self.state.layer_num) or 0
  3554. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  3555. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  3556. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  3557. at_last_layer = total > 0 and layer >= total
  3558. # `remaining <= 0` is only meaningful once the print has actually
  3559. # progressed — it reads 0 during the pre-print calibration too.
  3560. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  3561. if not (at_last_layer or percent >= 99 or out_of_time):
  3562. return
  3563. self._eop_probe_open = True
  3564. self._eop_probe_frames = 0
  3565. self._eop_probe_last = {}
  3566. logger.debug(
  3567. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  3568. self.serial_number,
  3569. layer,
  3570. total,
  3571. percent,
  3572. remaining,
  3573. )
  3574. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  3575. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  3576. self._eop_probe_last.update(present)
  3577. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  3578. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  3579. self._eop_probe_frames += 1
  3580. logger.debug(
  3581. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  3582. self.serial_number,
  3583. _END_OF_PRINT_PROBE_MAX_FRAMES,
  3584. )
  3585. return
  3586. if changed or closing:
  3587. self._eop_probe_frames += 1
  3588. logger.debug(
  3589. "[%s] EOP-PROBE %s%s: %s",
  3590. self.serial_number,
  3591. self._eop_probe_frames,
  3592. " CLOSE" if closing else "",
  3593. # `changed` on a closing frame can be empty; fall back to the
  3594. # full picture so the last line is always self-contained.
  3595. changed if changed else present,
  3596. )
  3597. if closing:
  3598. self._eop_probe_open = False
  3599. self._eop_probe_armed = False
  3600. self._eop_probe_last = {}
  3601. def _update_state(self, data: dict):
  3602. """Update printer state from message data."""
  3603. _previous_state = self.state.state
  3604. # #2547: instrumentation only — runs before any state mutation so the
  3605. # frame carrying an end-of-print signal is logged as it arrived.
  3606. try:
  3607. self._probe_end_of_print(data)
  3608. except Exception: # pragma: no cover - a probe must never break ingest
  3609. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  3610. # Update state fields
  3611. if "gcode_state" in data:
  3612. self.state.state = data["gcode_state"]
  3613. if "gcode_file" in data:
  3614. self.state.gcode_file = data["gcode_file"]
  3615. self.state.current_print = data["gcode_file"]
  3616. if "subtask_name" in data:
  3617. self.state.subtask_name = data["subtask_name"]
  3618. # Prefer subtask_name as current_print if available
  3619. if data["subtask_name"]:
  3620. self.state.current_print = data["subtask_name"]
  3621. if "subtask_id" in data:
  3622. self.state.subtask_id = data["subtask_id"]
  3623. if "mc_percent" in data:
  3624. # Billing: retain this frame's latest positive value immediately.
  3625. # A display-side abort may be the very next frame (and may omit
  3626. # mc_percent entirely), so retaining only the previous frame can
  3627. # lose the only usable estimate for proportional charging.
  3628. previous_progress = self.state.progress
  3629. new_progress = float(data["mc_percent"])
  3630. if new_progress > 0:
  3631. self._last_valid_progress = new_progress
  3632. self.state.progress = new_progress
  3633. # #2547: strictly-increasing only. The firmware resets progress to 0
  3634. # on cancel and re-reports the same percent on most frames; neither
  3635. # is the print advancing, and both would make the frame bank grab a
  3636. # camera frame for nothing.
  3637. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  3638. self.on_print_progress(int(self.state.progress))
  3639. if "mc_remaining_time" in data:
  3640. self.state.remaining_time = int(data["mc_remaining_time"])
  3641. if "mc_print_sub_stage" in data:
  3642. new_sub_stage = int(data["mc_print_sub_stage"])
  3643. if new_sub_stage != self.state.mc_print_sub_stage:
  3644. logger.debug(
  3645. f"[{self.serial_number}] mc_print_sub_stage changed: "
  3646. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  3647. )
  3648. self.state.mc_print_sub_stage = new_sub_stage
  3649. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  3650. # front because three places below consult it and they run in an order
  3651. # that is not the order they read most naturally in: the layer-advance
  3652. # refresh (#2702) must not fire on a frame that already answers it, the
  3653. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  3654. # reset must not discard a total that belongs to the starting print.
  3655. total_from_this_frame = 0
  3656. if "total_layer_num" in data:
  3657. try:
  3658. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  3659. except (TypeError, ValueError):
  3660. # Must not escape. `_on_message` catches only JSONDecodeError
  3661. # and paho is left at `suppress_exceptions = False`, so an
  3662. # exception raised here is re-raised on the network thread and
  3663. # takes the printer connection down over one unusable field.
  3664. # Treat it as "not reported": the refresh below then recovers
  3665. # the real total from a pushall.
  3666. logger.debug(
  3667. "[%s] ignoring unusable total_layer_num: %r",
  3668. self.serial_number,
  3669. data["total_layer_num"],
  3670. )
  3671. if "layer_num" in data:
  3672. try:
  3673. new_layer = int(data["layer_num"])
  3674. except (TypeError, ValueError):
  3675. # Contained for the same reason as `total_layer_num` above: an
  3676. # exception raised here escapes `_update_state` and paho
  3677. # re-raises it on the network thread. Losing this frame would
  3678. # also lose the print-start and completion detection further
  3679. # down, which is worse than losing a layer number.
  3680. #
  3681. # Held at the last known layer rather than substituted with 0:
  3682. # a fabricated 0 reads as the firmware's cancel reset, which
  3683. # would move `_last_valid_layer_num` and show layer 0 in the UI
  3684. # until the next good frame.
  3685. logger.debug(
  3686. "[%s] ignoring unusable layer_num: %r",
  3687. self.serial_number,
  3688. data["layer_num"],
  3689. )
  3690. new_layer = self.state.layer_num
  3691. old_layer = self.state.layer_num
  3692. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  3693. if old_layer > 0:
  3694. self._last_valid_layer_num = old_layer
  3695. self.state.layer_num = new_layer
  3696. # Trigger layer change callback if layer increased
  3697. if new_layer > old_layer and self.on_layer_change:
  3698. self.on_layer_change(new_layer)
  3699. # #2702: the print is demonstrably laying down layers but we still
  3700. # have no denominator, so the pushall requested at print start
  3701. # either went unanswered or raced the printer learning the total.
  3702. # Ask once more — by layer 1 the printer definitely knows it.
  3703. # One-shot: an unanswered pushall must not turn into a per-layer
  3704. # retry loop for the rest of the print.
  3705. if (
  3706. new_layer > old_layer
  3707. and self._total_layers_refresh_armed
  3708. and not self.state.total_layers
  3709. and not total_from_this_frame
  3710. ):
  3711. self._total_layers_refresh_armed = False
  3712. logger.debug(
  3713. "[%s] layer %s with no total_layer_num — re-requesting full status",
  3714. self.serial_number,
  3715. new_layer,
  3716. )
  3717. self._request_push_all()
  3718. # #2547: there is deliberately NO finish-photo trigger on the
  3719. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  3720. # moment the printer *starts* the final layer, not the moment it
  3721. # finishes it — on the H2C capture that closed #2547 the edge
  3722. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  3723. # filament change before the print actually ended, so the photo
  3724. # showed the toolhead mid-print over the part. Worse, the trigger
  3725. # latched `_finish_photo_captured`, locking out both the stage-22
  3726. # and FINISH triggers below for the rest of the print.
  3727. #
  3728. # #1867 (End G-code ejects the plate before FINISH) is handled
  3729. # where it belongs instead: `on_finish_photo_moment` prefers the
  3730. # in-print frame bank when the dispatcher recorded that it injected
  3731. # End G-code into this print. See services/print_dispatch_context.
  3732. if total_from_this_frame:
  3733. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  3734. # end — same shape as the `layer_num` reset guarded above. Applying
  3735. # only positive values preserves the last known good denominator so
  3736. # the usage-tracker split path (#1771) survives the reset frame.
  3737. self.state.total_layers = total_from_this_frame
  3738. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  3739. # Convert to 0-100 percentage for display
  3740. def parse_fan_speed(value: str | int | None) -> int | None:
  3741. if value is None:
  3742. return None
  3743. try:
  3744. speed = int(value)
  3745. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  3746. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  3747. if speed <= 15:
  3748. return round(speed * 100 / 15)
  3749. # If already a percentage (0-255 scale from some printers), convert
  3750. elif speed <= 255:
  3751. return round(speed * 100 / 255)
  3752. return speed
  3753. except (ValueError, TypeError):
  3754. return None
  3755. # Log fan fields once for debugging
  3756. if not hasattr(self, "_fan_fields_logged"):
  3757. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  3758. if fan_fields:
  3759. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  3760. self._fan_fields_logged = True
  3761. if "cooling_fan_speed" in data:
  3762. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  3763. if "big_fan1_speed" in data:
  3764. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  3765. if "big_fan2_speed" in data:
  3766. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  3767. if "heatbreak_fan_speed" in data:
  3768. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  3769. # Calibration stage tracking
  3770. if "stg_cur" in data:
  3771. new_stg = data["stg_cur"]
  3772. prev_stg = self.state.stg_cur
  3773. # Always log ANY stg_cur change for debugging filament operations
  3774. if new_stg != prev_stg:
  3775. logger.debug(
  3776. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  3777. )
  3778. # A stage we cannot name is the one worth seeing at the default
  3779. # log level: the DEBUG line above is off in normal running, so
  3780. # an unnamed stage otherwise reaches the user as "Unknown stage
  3781. # (72)" on a card with nothing behind it to say when it
  3782. # happened or what the printer was doing. Recorded once per
  3783. # stage number per session, with the stage it came from and the
  3784. # print state, which is what naming it later needs. Guarded on
  3785. # the int type because the field is whatever the firmware sent.
  3786. if (
  3787. isinstance(new_stg, int)
  3788. and not isinstance(new_stg, bool)
  3789. # -1 is Bambuddy's own "not in a stage" sentinel and the
  3790. # initial value of the field, not something the firmware
  3791. # reports; every print would otherwise report it on the way
  3792. # out of its last real stage.
  3793. and new_stg != -1
  3794. and new_stg not in STAGE_NAMES
  3795. and new_stg not in self._unnamed_stages_seen
  3796. ):
  3797. self._unnamed_stages_seen.add(new_stg)
  3798. logger.info(
  3799. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  3800. "state=%s progress=%s%% layer=%s/%s",
  3801. self.serial_number,
  3802. new_stg,
  3803. self.model,
  3804. prev_stg,
  3805. get_stage_name(prev_stg),
  3806. self.state.state,
  3807. self.state.progress,
  3808. self.state.layer_num,
  3809. self.state.total_layers,
  3810. )
  3811. self.state.stg_cur = new_stg
  3812. # #1721 end-of-print finish photo trigger.
  3813. # Stage 22 = "Filament unloading" fires at end-of-print AND
  3814. # during mid-print color swaps. The end-of-print gate
  3815. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  3816. # — those signals only line up at the real end. Edge-only
  3817. # (prev != 22) so the trigger fires once per stage entry.
  3818. if (
  3819. new_stg == 22
  3820. and prev_stg != 22
  3821. and self._was_running
  3822. and not self._finish_photo_captured
  3823. and self.on_finish_photo_moment
  3824. ):
  3825. progress = self.state.progress or 0.0
  3826. layer_num = self.state.layer_num or 0
  3827. total_layers = self.state.total_layers or 0
  3828. remaining = self.state.remaining_time or 0
  3829. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  3830. if is_end_of_print:
  3831. self._finish_photo_captured = True
  3832. logger.info(
  3833. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  3834. f"progress={progress}, layer={layer_num}/{total_layers}, "
  3835. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  3836. )
  3837. self.on_finish_photo_moment(
  3838. {
  3839. "trigger": "stage_22",
  3840. "filename": self._previous_gcode_file or self.state.gcode_file,
  3841. "subtask_name": self.state.subtask_name,
  3842. "timelapse_was_active": self._timelapse_during_print,
  3843. }
  3844. )
  3845. if "stg" in data:
  3846. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  3847. # Temperature data
  3848. temps = {}
  3849. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  3850. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  3851. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  3852. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  3853. # Log ALL keys in print data for H2D temperature discovery
  3854. all_keys = sorted(data.keys())
  3855. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  3856. self._temp_fields_logged = True
  3857. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  3858. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  3859. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  3860. self._vir_slot_logged = True
  3861. # Log nozzle hardware info fields (once)
  3862. nozzle_fields = {
  3863. k: v
  3864. for k, v in data.items()
  3865. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  3866. }
  3867. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  3868. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  3869. self._nozzle_fields_logged = True
  3870. # Parse active extruder from device.extruder.state bit 8
  3871. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  3872. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  3873. if "device" in data and isinstance(data.get("device"), dict):
  3874. device = data["device"]
  3875. # One-shot identification probe: surface whatever the firmware uses to
  3876. # name itself so an unknown model in a support bundle becomes self-
  3877. # diagnosing. INFO level so it shows up without debug logging. Falls
  3878. # back to dumping device.keys() if none of the known fields are present
  3879. # (so a future Bambu rename like `model_name` is still observable).
  3880. if not getattr(self, "_device_id_logged", False):
  3881. id_fields = {
  3882. k: device.get(k)
  3883. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  3884. if k in device
  3885. }
  3886. if id_fields:
  3887. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  3888. else:
  3889. logger.info(
  3890. "[%s] Device identification: no known id fields; device.keys=%s",
  3891. self.serial_number,
  3892. sorted(device.keys()),
  3893. )
  3894. self._device_id_logged = True
  3895. if "extruder" in device and "state" in device["extruder"]:
  3896. state_val = device["extruder"]["state"]
  3897. # Extract bit 8 for extruder position
  3898. new_extruder = (state_val >> 8) & 0x1
  3899. if new_extruder != self.state.active_extruder:
  3900. logger.debug(
  3901. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  3902. )
  3903. self.state.active_extruder = new_extruder
  3904. # Log device.extruder structure for active extruder
  3905. if "device" in data and isinstance(data.get("device"), dict):
  3906. device = data["device"]
  3907. if "extruder" in device:
  3908. ext_data = device["extruder"]
  3909. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  3910. if "state" in ext_data:
  3911. state_val = ext_data["state"]
  3912. # Extract bits 12-14 (3 bits) for switch state
  3913. switch_state = (state_val >> 12) & 0x7
  3914. self._debug_on_change(
  3915. "extruder_state",
  3916. state_val,
  3917. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  3918. self.serial_number,
  3919. state_val,
  3920. switch_state,
  3921. )
  3922. # Log 'cur' field if present (might indicate current/active extruder)
  3923. if "cur" in ext_data:
  3924. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  3925. # Also parsed earlier in _process_message, because _handle_ams_data needs
  3926. # it first. Repeated here so _update_state stays a complete "absorb this
  3927. # payload" step for any other caller; re-parsing the same block is free.
  3928. self._parse_fila_switch(data)
  3929. self._parse_extruder_slots(data)
  3930. if "bed_temper" in data:
  3931. temps["bed"] = float(data["bed_temper"])
  3932. if "bed_target_temper" in data:
  3933. temps["bed_target"] = float(data["bed_target_temper"])
  3934. # Check if this is H2D (has device.extruder.info with 2 extruders)
  3935. has_h2d_extruder_info = (
  3936. "device" in data
  3937. and isinstance(data.get("device"), dict)
  3938. and "extruder" in data["device"]
  3939. and isinstance(data["device"]["extruder"].get("info"), list)
  3940. and len(data["device"]["extruder"]["info"]) >= 2
  3941. )
  3942. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  3943. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  3944. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  3945. if "nozzle_temper" in data:
  3946. if has_h2d_extruder_info:
  3947. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  3948. else:
  3949. temps["nozzle"] = float(data["nozzle_temper"])
  3950. if "nozzle_target_temper" in data:
  3951. if has_h2d_extruder_info:
  3952. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  3953. else:
  3954. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  3955. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  3956. if not has_h2d_extruder_info:
  3957. # Try multiple possible field names used by different firmware versions
  3958. if "nozzle_temper_2" in data:
  3959. val = float(data["nozzle_temper_2"])
  3960. if -50 < val < 500: # Valid temp range
  3961. temps["nozzle_2"] = val
  3962. else:
  3963. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  3964. elif "right_nozzle_temper" in data:
  3965. val = float(data["right_nozzle_temper"])
  3966. if -50 < val < 500: # Valid temp range
  3967. temps["nozzle_2"] = val
  3968. else:
  3969. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  3970. if "nozzle_target_temper_2" in data:
  3971. val = float(data["nozzle_target_temper_2"])
  3972. if 0 <= val < 500: # Valid temp range
  3973. temps["nozzle_2_target"] = val
  3974. else:
  3975. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  3976. elif "right_nozzle_target_temper" in data:
  3977. val = float(data["right_nozzle_target_temper"])
  3978. if 0 <= val < 500: # Valid temp range
  3979. temps["nozzle_2_target"] = val
  3980. else:
  3981. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  3982. # Also check for left nozzle as primary (some H2 models)
  3983. if "left_nozzle_temper" in data and "nozzle" not in temps:
  3984. temps["nozzle"] = float(data["left_nozzle_temper"])
  3985. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  3986. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  3987. if "chamber_temper" in data:
  3988. chamber_val = float(data["chamber_temper"])
  3989. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  3990. # Check if we recently set the target locally (within 5 seconds)
  3991. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  3992. respect_local = (time.time() - local_set_time) < 5.0
  3993. # H2D protocol: chamber_temper encoding indicates heater state
  3994. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  3995. # - When < 500: direct Celsius current temp only - heater is OFF
  3996. if -50 < chamber_val < 100:
  3997. # Direct value = heater is OFF
  3998. temps["chamber"] = chamber_val
  3999. if not respect_local:
  4000. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4001. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4002. else:
  4003. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4004. # Try to decode if it looks like an encoded value
  4005. if chamber_val > 500:
  4006. mqtt_target = int(chamber_val) // 65536
  4007. current = int(chamber_val) % 65536
  4008. logger.debug(
  4009. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4010. )
  4011. if -50 < current < 100:
  4012. temps["chamber"] = float(current)
  4013. # Store decoded target for later use, but DON'T set chamber_heating here!
  4014. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4015. # which is the authoritative source the slicer uses.
  4016. if not respect_local:
  4017. if 0 <= mqtt_target <= 60:
  4018. # Store as "decoded" target - may be overridden by explicit target fields
  4019. temps["_chamber_decoded_target"] = float(mqtt_target)
  4020. # Chamber target temperature (set by print file or display)
  4021. if "mc_target_cham" in data:
  4022. mc_target = float(data["mc_target_cham"])
  4023. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4024. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4025. if 0 <= mc_target <= 60:
  4026. temps["chamber_target"] = mc_target
  4027. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4028. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4029. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4030. try:
  4031. if "info" in data and isinstance(data["info"], dict):
  4032. info_temp = data["info"].get("temp")
  4033. if info_temp is not None and "chamber" not in temps:
  4034. # Check for encoded value (target * 65536 + current)
  4035. if info_temp > 500:
  4036. # Decode: extract current temperature and target
  4037. target = info_temp // 65536
  4038. current = info_temp % 65536
  4039. temps["chamber"] = float(current)
  4040. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4041. if "_chamber_decoded_target" not in temps:
  4042. temps["_chamber_decoded_target"] = float(target)
  4043. logger.debug(
  4044. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4045. )
  4046. elif -50 < info_temp < 100:
  4047. # Valid direct temperature - heater is OFF
  4048. temps["chamber"] = float(info_temp)
  4049. temps["chamber_target"] = 0.0 # Direct value means heater off
  4050. self._debug_on_change(
  4051. "info_temp_direct",
  4052. info_temp,
  4053. "[%s] info.temp direct: %s°C (heater OFF)",
  4054. self.serial_number,
  4055. info_temp,
  4056. )
  4057. # H2D series: Dual extruder temps are in device.extruder.info array
  4058. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4059. if "device" in data and isinstance(data["device"], dict):
  4060. device = data["device"]
  4061. # Parse dual extruder temperatures
  4062. extruder_data = device.get("extruder", {})
  4063. extruder_info = extruder_data.get("info", [])
  4064. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4065. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4066. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4067. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4068. if has_h2d_extruder_info:
  4069. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4070. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4071. if "temp" in extruder_info[0]:
  4072. temp_val = extruder_info[0]["temp"]
  4073. if temp_val > 500:
  4074. # Encoded format: temp = target * 65536 + current
  4075. target = temp_val // 65536
  4076. current = temp_val % 65536
  4077. if -50 < current < 500:
  4078. temps["nozzle_2"] = float(current)
  4079. if 0 < target < 500:
  4080. temps["nozzle_2_target"] = float(target)
  4081. temps["nozzle_2_heating"] = target > 0 and current < target
  4082. elif -50 < temp_val < 500:
  4083. # Direct Celsius value = heater is OFF
  4084. temps["nozzle_2"] = float(temp_val)
  4085. temps["nozzle_2_target"] = 0.0
  4086. temps["nozzle_2_heating"] = False
  4087. # Left nozzle (extruder 1) - only for dual nozzle printers
  4088. # H2D protocol: temp field encoding depends on value
  4089. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4090. # - When < 500: direct Celsius current temp only - heater is OFF
  4091. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4092. ext1 = extruder_info[1]
  4093. temp_val = ext1["temp"]
  4094. # Check if we recently set the target locally (within 5 seconds)
  4095. # If so, don't let MQTT data overwrite it
  4096. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4097. respect_local_target = (time.time() - local_set_time) < 5.0
  4098. if temp_val > 500:
  4099. # Encoded format: temp = target * 65536 + current
  4100. target = temp_val // 65536
  4101. current = temp_val % 65536
  4102. if 0 < target < 500 and not respect_local_target:
  4103. temps["nozzle_target"] = float(target)
  4104. if -50 < current < 500:
  4105. temps["nozzle"] = float(current)
  4106. # Heating = encoded AND we're using the MQTT target (not local override)
  4107. # If local target is being respected, use local target to determine heating
  4108. if respect_local_target:
  4109. local_target = self.state.temperatures.get("nozzle_target", 0)
  4110. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4111. else:
  4112. temps["nozzle_heating"] = target > 0 and current < target
  4113. elif -50 < temp_val < 500:
  4114. # Direct Celsius = heater is OFF (or at target with heater off)
  4115. temps["nozzle"] = float(temp_val)
  4116. if not respect_local_target:
  4117. temps["nozzle_target"] = 0.0
  4118. temps["nozzle_heating"] = False # Direct = not heating
  4119. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  4120. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  4121. if has_h2d_extruder_info:
  4122. for ext_info in extruder_info:
  4123. ext_id = ext_info.get("id")
  4124. snow = ext_info.get("snow")
  4125. if ext_id is not None and snow is not None and ext_id <= 1:
  4126. # Normalize H2D snow value to global tray ID
  4127. ams_id = snow >> 8
  4128. slot = snow & 0xFF
  4129. if 0 <= ams_id <= 3:
  4130. # Regular AMS slot
  4131. global_tray = ams_id * 4 + (slot & 0x03)
  4132. old_val = self.state.h2d_extruder_snow.get(ext_id)
  4133. if old_val != global_tray:
  4134. logger.debug(
  4135. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  4136. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  4137. )
  4138. self.state.h2d_extruder_snow[ext_id] = global_tray
  4139. elif ams_id == 254 or ams_id == 255:
  4140. # External spool or unloaded
  4141. normalized = 254 if slot != 255 else 255
  4142. old_val = self.state.h2d_extruder_snow.get(ext_id)
  4143. if old_val != normalized:
  4144. logger.debug(
  4145. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  4146. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  4147. )
  4148. self.state.h2d_extruder_snow[ext_id] = normalized
  4149. elif 128 <= ams_id <= 135:
  4150. # External spool with hub mapping
  4151. old_val = self.state.h2d_extruder_snow.get(ext_id)
  4152. if old_val != ams_id:
  4153. logger.debug(
  4154. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  4155. f"raw={snow} -> external hub {ams_id}"
  4156. )
  4157. self.state.h2d_extruder_snow[ext_id] = ams_id
  4158. # Parse bed heating state from device.bed.info.temp encoding
  4159. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4160. bed_data = device.get("bed", {})
  4161. bed_info = bed_data.get("info", {})
  4162. if "temp" in bed_info:
  4163. temp_val = bed_info["temp"]
  4164. if temp_val > 500:
  4165. target = temp_val // 65536
  4166. current = temp_val % 65536
  4167. temps["bed_heating"] = target > 0 and current < target
  4168. else:
  4169. temps["bed_heating"] = False
  4170. # Parse chamber temp from device.ctc.info.temp if not already set
  4171. ctc_data = device.get("ctc", {})
  4172. ctc_info = ctc_data.get("info", {})
  4173. # Parse airduct mode (0=cooling, 1=heating)
  4174. airduct_data = device.get("airduct", {})
  4175. if "modeCur" in airduct_data:
  4176. new_mode = airduct_data["modeCur"]
  4177. if new_mode != self.state.airduct_mode:
  4178. logger.debug(
  4179. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4180. )
  4181. self.state.airduct_mode = new_mode
  4182. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4183. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4184. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4185. # AIR_FUN enum: 1=part cooling, 2=right aux, 3=chamber/exhaust,
  4186. # 10=left aux (FAN_REMOTE_COOLING_1). The airduct `parts` list only
  4187. # contains the fans that physically exist, so it doubles as a
  4188. # presence signal for the two P2S/X2D add-on kits:
  4189. # - id 10 (left auxiliary part cooling fan) — reported ONLY here,
  4190. # never mirrored into a flat big_fanX_speed field.
  4191. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4192. # big_fan2_speed, but the part is only listed when the External
  4193. # Exhaust Fan kit (get_version module "eef") is installed.
  4194. # `state` is already a 0-100 percentage.
  4195. parts = airduct_data.get("parts")
  4196. if isinstance(parts, list):
  4197. speeds: dict[int, int] = {}
  4198. for part in parts:
  4199. if not isinstance(part, dict):
  4200. continue
  4201. try:
  4202. # Studio reads the id with get_flag_bits(id, 4, 8),
  4203. # so mask after shifting for the same reason `state`
  4204. # is masked below. Every id seen in the wild
  4205. # (16/32/48/160) decodes identically either way —
  4206. # this is consistency, not a live bug.
  4207. part_id = (int(part["id"]) >> 4) & 0xFF
  4208. # `state` is bit-packed like its sibling `range`
  4209. # (end << 16 | start), so take only the low 8 bits —
  4210. # the same decode Bambu Studio does with
  4211. # get_flag_bits(state, 0, 8). Without the mask a
  4212. # packed value would clamp to 100 instead of
  4213. # decoding to the real percentage.
  4214. part_state = int(part["state"]) & 0xFF
  4215. except (KeyError, ValueError, TypeError):
  4216. continue
  4217. # Ids seen across the support-package archive:
  4218. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4219. # 6 (H2 series, unmapped), 10 left aux.
  4220. speeds[part_id] = max(0, min(100, part_state))
  4221. # Absence in this list is what tells us a kit is NOT fitted,
  4222. # so it may only be trusted when the list is a full
  4223. # inventory rather than a diff frame. `device.airduct` is
  4224. # pushed field by field — the `modeCur` handler above exists
  4225. # for exactly that reason — and a truncated `parts` read as
  4226. # gospel would retract both accessory badges mid-print and
  4227. # start rejecting `aux2` on a printer that has the fan.
  4228. #
  4229. # Every airduct layout in the support-package archive
  4230. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4231. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4232. # part cooling fan and the aux fan, neither of which is
  4233. # optional on any machine that reports an airduct at all.
  4234. # A list carrying both is therefore a complete inventory; a
  4235. # list missing either is a partial frame, and we take its
  4236. # speeds without touching presence.
  4237. is_full_inventory = 1 in speeds and 2 in speeds
  4238. left_aux_speed = speeds.get(10)
  4239. if left_aux_speed is None and not is_full_inventory:
  4240. # Partial frame that didn't mention the left aux fan —
  4241. # keep whatever we already knew about it.
  4242. left_aux_speed = self.state.left_aux_fan_speed
  4243. if left_aux_speed != self.state.left_aux_fan_speed:
  4244. logger.debug(
  4245. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4246. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4247. )
  4248. # A FULL parts list without id 10 means the left aux fan is
  4249. # not installed — report None so the UI can hide the widget.
  4250. self.state.left_aux_fan_speed = left_aux_speed
  4251. # id 3 present == chamber exhaust fan installed (base P2S
  4252. # omits it). Only ever retracted on a full inventory.
  4253. if 3 in speeds:
  4254. self.state.exhaust_fan_present = True
  4255. elif is_full_inventory:
  4256. self.state.exhaust_fan_present = False
  4257. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  4258. # Check if we recently set the target locally (within 5 seconds)
  4259. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4260. respect_local_target = (time.time() - local_set_time) < 5.0
  4261. # Log ctc_info contents for debugging
  4262. if ctc_info:
  4263. self._debug_on_change(
  4264. "ctc_info_keys",
  4265. tuple(ctc_info.keys()),
  4266. "[%s] ctc_info keys: %s",
  4267. self.serial_number,
  4268. list(ctc_info.keys()),
  4269. )
  4270. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  4271. # (what the slicer shows). This OVERRIDES any previously decoded target.
  4272. explicit_target = None
  4273. if "target" in ctc_info:
  4274. target_val = ctc_info["target"]
  4275. logger.debug(
  4276. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  4277. )
  4278. # Filter out invalid values (valid chamber target is 0-60°C)
  4279. if 0 <= target_val <= 60 and not respect_local_target:
  4280. explicit_target = float(target_val)
  4281. temps["chamber_target"] = explicit_target # Override any previous value
  4282. logger.debug(
  4283. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  4284. )
  4285. # Parse chamber temp from ctc.info.temp - may be encoded
  4286. if "temp" in ctc_info and "chamber" not in temps:
  4287. temp_val = ctc_info["temp"]
  4288. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  4289. if temp_val > 500:
  4290. # Encoded value: decode target and current
  4291. decoded_target = temp_val // 65536
  4292. current = temp_val % 65536
  4293. temps["chamber"] = float(current)
  4294. logger.debug(
  4295. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  4296. )
  4297. # Determine which target to use for heating state:
  4298. # Priority: local target > explicit target > decoded target
  4299. if respect_local_target:
  4300. local_target = self.state.temperatures.get("chamber_target", 0)
  4301. temps["chamber_heating"] = local_target > 0 and current < local_target
  4302. elif explicit_target is not None:
  4303. # Use explicit ctc.info.target - this is what slicer sees
  4304. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  4305. else:
  4306. # Fallback to decoded target only if no explicit target available
  4307. if not respect_local_target and "chamber_target" not in temps:
  4308. temps["chamber_target"] = float(decoded_target)
  4309. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  4310. else:
  4311. # Direct value (not encoded) - heater is OFF
  4312. temps["chamber"] = float(temp_val)
  4313. temps["chamber_heating"] = False
  4314. except Exception as e:
  4315. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  4316. if temps:
  4317. # Handle chamber_target: prefer explicit over decoded
  4318. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  4319. # No explicit target available, use decoded target from chamber_temper
  4320. temps["chamber_target"] = temps["_chamber_decoded_target"]
  4321. # Remove internal temp key before merging
  4322. temps.pop("_chamber_decoded_target", None)
  4323. # Merge new temps into existing, preserving valid values when new ones are filtered out
  4324. for key, value in temps.items():
  4325. self.state.temperatures[key] = value
  4326. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  4327. if "bed" in temps and self.on_bed_temp_update:
  4328. self.on_bed_temp_update(temps["bed"])
  4329. # Calculate chamber_heating after all targets are known
  4330. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  4331. if "chamber" in temps and "chamber_heating" not in temps:
  4332. current = self.state.temperatures.get("chamber", 0)
  4333. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4334. respect_local = (time.time() - local_set_time) < 5.0
  4335. if respect_local:
  4336. # Use locally-set target
  4337. target = self.state.temperatures.get("chamber_target", 0)
  4338. else:
  4339. # Use explicit/decoded target from MQTT
  4340. target = self.state.temperatures.get("chamber_target", 0)
  4341. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  4342. self._debug_on_change(
  4343. "chamber_heating",
  4344. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  4345. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  4346. self.serial_number,
  4347. target,
  4348. current,
  4349. self.state.temperatures["chamber_heating"],
  4350. respect_local,
  4351. )
  4352. # Debug: log chamber value if it was updated
  4353. if "chamber" in temps:
  4354. self._debug_on_change(
  4355. "chamber_temp",
  4356. (
  4357. self.state.temperatures.get("chamber"),
  4358. self.state.temperatures.get("chamber_target"),
  4359. self.state.temperatures.get("chamber_heating"),
  4360. ),
  4361. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  4362. self.serial_number,
  4363. self.state.temperatures.get("chamber"),
  4364. self.state.temperatures.get("chamber_target"),
  4365. self.state.temperatures.get("chamber_heating"),
  4366. )
  4367. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  4368. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  4369. if "nozzle" in temps and "nozzle_heating" not in temps:
  4370. current = self.state.temperatures.get("nozzle", 0)
  4371. target = self.state.temperatures.get("nozzle_target", 0)
  4372. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  4373. # Parse HMS (Health Management System) errors
  4374. if "hms" in data:
  4375. hms_list = data["hms"]
  4376. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  4377. self.state.hms_errors = []
  4378. verify_failed = False
  4379. if isinstance(hms_list, list):
  4380. for hms in hms_list:
  4381. if isinstance(hms, dict):
  4382. # HMS format: {"attr": attribute_code, "code": error_code}
  4383. # attr contains module/severity info, code contains error number
  4384. # Both are needed to construct the wiki URL
  4385. attr = hms.get("attr", 0)
  4386. code = hms.get("code", 0)
  4387. if isinstance(attr, str):
  4388. attr = int(attr.replace("0x", ""), 16) if attr else 0
  4389. if isinstance(code, str):
  4390. code = int(code.replace("0x", ""), 16) if code else 0
  4391. # Severity is in attr byte 1 (bits 8-15)
  4392. severity = (attr >> 8) & 0xF
  4393. # Module is in attr byte 3 (bits 24-31)
  4394. module = (attr >> 24) & 0xFF
  4395. # Skip non-error status codes — all real HMS errors
  4396. # have code >= 0x4000. Lower values are status/phase
  4397. # indicators that some firmware sends during normal printing.
  4398. if code < 0x4000:
  4399. continue
  4400. # Skip user-action echoes — the printer firmware emits these
  4401. # as part of normal user-cancel sequences. They're not faults
  4402. # and shouldn't count toward "X problem" badges or surface as
  4403. # red pips on the printer card. Backend's notification path
  4404. # already suppresses 0500_400E for the same reason.
  4405. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  4406. if short_code in _HMS_USER_ACTION_CODES:
  4407. continue
  4408. # Catalog has both 8-char keys (base class) and 16-char keys
  4409. # (specific variants). The full 16-char identifier preserves
  4410. # the 32 bits of `attr_low` + `code_high` that the short_code
  4411. # discards — that's the firmware's matching key, so try it
  4412. # first and fall back to the short form.
  4413. full_code = f"{attr:08X}{code:08X}"
  4414. if full_code == HMS_MQTT_VERIFY_FAILED:
  4415. verify_failed = True
  4416. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  4417. if not actions:
  4418. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4419. self.state.hms_errors.append(
  4420. HMSError(
  4421. code=f"0x{code:x}" if code else "0x0",
  4422. attr=attr,
  4423. module=module,
  4424. severity=severity if severity > 0 else 2,
  4425. actions=actions,
  4426. job_id=self.state.subtask_id,
  4427. full_code=full_code,
  4428. description=describe_fault(full_code),
  4429. )
  4430. )
  4431. self._apply_mqtt_verify_state(verify_failed)
  4432. # Parse print_error - this is a different error format than HMS
  4433. # print_error is a 32-bit integer where:
  4434. # - High 16 bits contain module info (e.g., 0x0500)
  4435. # - Low 16 bits contain error code (e.g., 0x8061)
  4436. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  4437. if "print_error" in data:
  4438. print_error = data["print_error"]
  4439. if print_error and print_error != 0:
  4440. # Extract components: MMMMEEEE -> MMMM_EEEE
  4441. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  4442. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  4443. # Values below 0x4000 are status/phase indicators, not real errors.
  4444. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  4445. # Some firmware sends low values like 0x0002 during normal printing.
  4446. if error < 0x4000:
  4447. pass # Skip — not a real error
  4448. else:
  4449. # Store in a format that matches the community error database
  4450. # attr stores the full 32-bit value for reconstruction
  4451. # code stores the short format string for lookup
  4452. short_code = f"{module:04X}_{error:04X}"
  4453. logger.debug(
  4454. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  4455. )
  4456. # Same user-action filter as the hms[] branch above — print_error
  4457. # carries the same cancel echoes (e.g. 0500_400E) and they must
  4458. # not surface as faults on the printer card.
  4459. if short_code in _HMS_USER_ACTION_CODES:
  4460. pass # cancel echo — silently drop
  4461. else:
  4462. # Only add if not already in HMS errors (avoid duplicates)
  4463. existing_short_codes = set()
  4464. for e in self.state.hms_errors:
  4465. # Extract short code from existing errors
  4466. e_module = (e.attr >> 16) & 0xFFFF
  4467. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  4468. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  4469. if short_code not in existing_short_codes:
  4470. # Bambu's HMS catalog keys by 3-letter device code (the SN
  4471. # prefix) and a 16-char short error code without the
  4472. # underscore separator we store internally.
  4473. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4474. # Bambu pushes the current job as `subtask_id` on the
  4475. # state stream; the HMS-action commands echo it back as
  4476. # `job_id`. The error payload itself doesn't carry the
  4477. # id, so snapshot it from the live state at parse time
  4478. # and freeze it on the HMSError so subsequent
  4479. # job changes don't invalidate the action.
  4480. job_id = self.state.subtask_id
  4481. logger.debug(
  4482. "[%s, %s] HMS available actions: %s (job_id=%s)",
  4483. self.serial_number[:3],
  4484. short_code.replace("_", ""),
  4485. actions,
  4486. job_id,
  4487. )
  4488. self.state.hms_errors.append(
  4489. HMSError(
  4490. code=f"0x{error:x}",
  4491. attr=print_error, # Store full value for display
  4492. module=module >> 8, # High byte of module (e.g., 0x05)
  4493. severity=3, # Warning level for print_error
  4494. actions=actions,
  4495. job_id=job_id,
  4496. # print_error is already 32-bit — `f"{print_error:08X}"`
  4497. # is the firmware's matching key with no truncation.
  4498. full_code=f"{print_error:08X}",
  4499. description=describe_fault(f"{print_error:08X}"),
  4500. )
  4501. )
  4502. # Parse home_flag first so SD-card detection below can prefer it.
  4503. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  4504. # bit 23 = door-open (X1 family only).
  4505. home_flag = None
  4506. if "home_flag" in data:
  4507. home_flag = data["home_flag"]
  4508. if home_flag < 0:
  4509. home_flag = home_flag & 0xFFFFFFFF
  4510. # SD card presence: the only remaining consumer is the firmware-update
  4511. # precondition check (firmware_update.py). Use the top-level `sdcard`
  4512. # field when present with a permissive truthy check covering the
  4513. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  4514. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  4515. # when a card is inserted, which caused the badge to flap before the
  4516. # badge was removed entirely.
  4517. if "sdcard" in data:
  4518. raw_sdcard = data["sdcard"]
  4519. if isinstance(raw_sdcard, str):
  4520. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  4521. else:
  4522. self.state.sdcard = bool(raw_sdcard)
  4523. self.state.sdcard_reported = True
  4524. if home_flag is not None:
  4525. store_to_sdcard = bool((home_flag >> 11) & 1)
  4526. if store_to_sdcard != self.state.store_to_sdcard:
  4527. logger.debug(
  4528. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  4529. )
  4530. self.state.store_to_sdcard = store_to_sdcard
  4531. # Door open detection — source depends on printer family:
  4532. # X1 series (X1, X1C, X1E): home_flag bit 23
  4533. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  4534. # Both share the same bitmask (0x00800000) but live in different fields.
  4535. model_upper = (self.model or "").upper().strip()
  4536. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  4537. if is_x1_family and home_flag is not None:
  4538. door_open = (home_flag & 0x00800000) != 0
  4539. if door_open != self.state.door_open:
  4540. logger.debug(
  4541. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  4542. self.serial_number,
  4543. self.state.door_open,
  4544. door_open,
  4545. home_flag,
  4546. )
  4547. self.state.door_open = door_open
  4548. elif not is_x1_family and "stat" in data:
  4549. try:
  4550. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  4551. door_open = (stat_value & 0x00800000) != 0
  4552. if door_open != self.state.door_open:
  4553. logger.debug(
  4554. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  4555. self.serial_number,
  4556. self.state.door_open,
  4557. door_open,
  4558. stat_value,
  4559. )
  4560. self.state.door_open = door_open
  4561. except (ValueError, TypeError):
  4562. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  4563. # Parse timelapse status (recording active during print)
  4564. if "timelapse" in data:
  4565. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  4566. self.state.timelapse = data["timelapse"] is True
  4567. # Track if timelapse was ever active during this print
  4568. if self.state.timelapse and self._was_running:
  4569. self._timelapse_during_print = True
  4570. # Parse ipcam/live view status
  4571. if "ipcam" in data:
  4572. ipcam_data = data["ipcam"]
  4573. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  4574. if isinstance(ipcam_data, dict):
  4575. # Check ipcam_record field for live view status
  4576. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  4577. # Check timelapse field (H2D sends it here, not in xcam)
  4578. if "timelapse" in ipcam_data:
  4579. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  4580. if timelapse_enabled != self.state.timelapse:
  4581. logger.debug(
  4582. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  4583. )
  4584. self.state.timelapse = timelapse_enabled
  4585. # Track if timelapse was ever active during this print
  4586. if self.state.timelapse and self._was_running:
  4587. self._timelapse_during_print = True
  4588. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  4589. else:
  4590. self.state.ipcam = ipcam_data is True
  4591. # Parse WiFi signal strength (dBm)
  4592. if "wifi_signal" in data:
  4593. wifi_signal = data["wifi_signal"]
  4594. self._debug_on_change(
  4595. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  4596. )
  4597. if isinstance(wifi_signal, (int, float)):
  4598. self.state.wifi_signal = int(wifi_signal)
  4599. elif isinstance(wifi_signal, str):
  4600. # Handle string format like "-52dBm"
  4601. try:
  4602. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  4603. except ValueError:
  4604. pass # Ignore unparseable wifi_signal strings; field is non-critical
  4605. # Detect ethernet connection: printers on ethernet with WiFi disabled
  4606. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  4607. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  4608. from backend.app.utils.printer_models import has_ethernet
  4609. if has_ethernet(self.model):
  4610. self.state.wired_network = self.state.wifi_signal == -90
  4611. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  4612. if "spd_lvl" in data:
  4613. new_speed = data["spd_lvl"]
  4614. if new_speed != self.state.speed_level:
  4615. logger.debug(
  4616. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  4617. )
  4618. self.state.speed_level = new_speed
  4619. # Parse skipped objects from printer status (s_obj field)
  4620. # This allows us to restore skipped objects state after reconnection
  4621. if "s_obj" in data:
  4622. s_obj = data["s_obj"]
  4623. if isinstance(s_obj, list):
  4624. # Update skipped objects from printer's list
  4625. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  4626. if new_skipped != self.state.skipped_objects:
  4627. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  4628. self.state.skipped_objects = new_skipped
  4629. # Parse chamber light status from lights_report
  4630. if "lights_report" in data:
  4631. lights = data["lights_report"]
  4632. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  4633. if isinstance(lights, list):
  4634. for light in lights:
  4635. if isinstance(light, dict) and light.get("node") == "chamber_light":
  4636. new_light_state = light.get("mode") == "on"
  4637. if new_light_state != self.state.chamber_light:
  4638. logger.debug(
  4639. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  4640. )
  4641. self.state.chamber_light = new_light_state
  4642. break
  4643. # Parse nozzle hardware info (single nozzle printers)
  4644. if "nozzle_type" in data:
  4645. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  4646. if "nozzle_diameter" in data:
  4647. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  4648. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  4649. # Left nozzle
  4650. if "left_nozzle_type" in data:
  4651. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  4652. if "left_nozzle_diameter" in data:
  4653. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  4654. # Right nozzle
  4655. if "right_nozzle_type" in data:
  4656. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  4657. if "right_nozzle_diameter" in data:
  4658. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  4659. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  4660. if "nozzle_type_2" in data:
  4661. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  4662. if "nozzle_diameter_2" in data:
  4663. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  4664. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  4665. if "device" in data and isinstance(data["device"], dict):
  4666. device = data["device"]
  4667. nozzle_data = device.get("nozzle", {})
  4668. # H2C rack position (#2800). `tar_id` is where the carriage is
  4669. # headed, `src_id` where it came from; mid-swap they differ, so
  4670. # dispatch prefers tar_id and falls back to src_id. Both are
  4671. # sticky — the field is only pushed when it changes, so an
  4672. # absent key must leave the last known value alone rather than
  4673. # reset it to None.
  4674. if isinstance(nozzle_data, dict):
  4675. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  4676. if key not in nozzle_data:
  4677. continue
  4678. try:
  4679. parsed_id = int(nozzle_data[key])
  4680. except (TypeError, ValueError):
  4681. continue
  4682. if getattr(self.state, attr) != parsed_id:
  4683. setattr(self.state, attr, parsed_id)
  4684. # DEBUG, not INFO: these move on every tool change, so
  4685. # a long multi-material print would otherwise write
  4686. # thousands of lines. The dispatch log records both
  4687. # values once per print, which is where triage needs
  4688. # them. Same reasoning as the one-shot `nozzle_info`
  4689. # log below.
  4690. logger.debug(
  4691. "[%s] Nozzle rack %s -> %s",
  4692. self.serial_number,
  4693. key,
  4694. parsed_id,
  4695. )
  4696. nozzle_info = nozzle_data.get("info", [])
  4697. if isinstance(nozzle_info, list):
  4698. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  4699. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  4700. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  4701. # for hover cards on both the L/R indicator and the nozzle rack card.
  4702. if nozzle_info:
  4703. self.state.nozzle_rack = sorted(
  4704. [
  4705. {
  4706. "id": n.get("id", i),
  4707. "type": str(n.get("type", "")),
  4708. "diameter": str(n.get("diameter", "")),
  4709. "wear": n.get("wear"),
  4710. "stat": n.get("stat"),
  4711. # H2C uses "tm", H2D uses "max_temp"
  4712. "max_temp": n.get("max_temp") or n.get("tm", 0),
  4713. # H2C uses "sn", H2D uses "serial_number"
  4714. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  4715. # H2C uses "color_m", H2D uses "filament_colour"
  4716. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  4717. # H2C uses "fila_id", H2D uses "filament_id"
  4718. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  4719. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  4720. }
  4721. for i, n in enumerate(nozzle_info)
  4722. ],
  4723. key=lambda x: x["id"],
  4724. )
  4725. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  4726. self._nozzle_rack_logged = True
  4727. logger.debug(
  4728. "[%s] Nozzle info: %d entries, IDs: %s",
  4729. self.serial_number,
  4730. len(nozzle_info),
  4731. [n.get("id") for n in nozzle_info],
  4732. )
  4733. for nozzle in nozzle_info:
  4734. idx = nozzle.get("id", 0)
  4735. if idx < len(self.state.nozzles):
  4736. if "type" in nozzle and nozzle["type"]:
  4737. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  4738. if "diameter" in nozzle:
  4739. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  4740. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  4741. # (these fields aren't sent in every MQTT push, only when changed)
  4742. ams_data = self.state.raw_data.get("ams")
  4743. vt_tray_data = self.state.raw_data.get("vt_tray")
  4744. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  4745. mapping_data = self.state.raw_data.get("mapping")
  4746. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  4747. # as a dict but consumers expect a list. Without this, the dev mode probe
  4748. # below can release the GIL (via publish), letting the event-loop thread
  4749. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  4750. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  4751. data["vt_tray"] = [data["vt_tray"]]
  4752. self.state.raw_data = data
  4753. # Restore preserved fields BEFORE any work that may release the GIL
  4754. # (e.g. _probe_developer_mode publishes an MQTT message).
  4755. if ams_data is not None:
  4756. self.state.raw_data["ams"] = ams_data
  4757. if vt_tray_data is not None:
  4758. self.state.raw_data["vt_tray"] = vt_tray_data
  4759. if ams_extruder_map_data is not None:
  4760. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  4761. if mapping_data is not None and "mapping" not in data:
  4762. self.state.raw_data["mapping"] = mapping_data
  4763. # Parse developer LAN mode from "fun" field
  4764. if "fun" in data:
  4765. try:
  4766. fun_val = data["fun"]
  4767. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  4768. self.state.developer_mode = (fun_int & 0x20000000) == 0
  4769. except (ValueError, TypeError):
  4770. pass
  4771. elif self.state.developer_mode is None and not self._dev_mode_probed:
  4772. # No "fun" field — A1/P1 series never send it, so we need to probe.
  4773. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  4774. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  4775. # after connect to let the MQTT session stabilize — probing too early
  4776. # can destabilize some firmware MQTT brokers (#887).
  4777. if not self._dev_mode_needs_probe and len(data) > 30:
  4778. # First full status without "fun" — mark that probe is needed
  4779. self._dev_mode_needs_probe = True
  4780. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  4781. self._probe_developer_mode()
  4782. elif self._dev_mode_needs_probe:
  4783. logger.debug(
  4784. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  4785. self.serial_number,
  4786. time.monotonic() - self._connect_time,
  4787. )
  4788. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  4789. # Probe was sent but no response yet — check for timeout.
  4790. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  4791. # may deliver status pushes but silently drop commands (#887).
  4792. elapsed = time.monotonic() - self._dev_mode_probe_time
  4793. if elapsed > 10.0:
  4794. self._dev_mode_probe_failures += 1
  4795. logger.warning(
  4796. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  4797. self.serial_number,
  4798. elapsed,
  4799. self._dev_mode_probe_failures,
  4800. )
  4801. self._dev_mode_probe_seq = None
  4802. if self._dev_mode_probe_failures >= 2:
  4803. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  4804. else:
  4805. # Allow retry on next full status message
  4806. self._dev_mode_probed = False
  4807. # Zombie session detection: if an ams_filament_setting command has been
  4808. # pending for >10s with no response, the publish path is likely dead (#887).
  4809. if self._last_ams_cmd_time > 0:
  4810. elapsed = time.monotonic() - self._last_ams_cmd_time
  4811. if elapsed > 10.0:
  4812. self._ams_cmd_unanswered += 1
  4813. logger.warning(
  4814. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  4815. self.serial_number,
  4816. elapsed,
  4817. self._ams_cmd_unanswered,
  4818. )
  4819. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  4820. if self._ams_cmd_unanswered >= 2:
  4821. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  4822. self._ams_cmd_unanswered = 0
  4823. # Log mapping data when received (for usage tracking debugging)
  4824. if "mapping" in data:
  4825. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  4826. # Log state transitions for debugging
  4827. if "gcode_state" in data:
  4828. logger.debug(
  4829. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  4830. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  4831. )
  4832. # Detect print start (state changes TO RUNNING with a file)
  4833. current_file = self.state.gcode_file or self.state.current_print
  4834. is_new_print = (
  4835. self.state.state == "RUNNING"
  4836. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  4837. and self._previous_gcode_state != "RUNNING"
  4838. and current_file
  4839. and not self._was_running # Prevent duplicates when resuming from PAUSE
  4840. )
  4841. # Also detect if file changed while running (new print started)
  4842. is_file_change = (
  4843. self.state.state == "RUNNING"
  4844. and current_file
  4845. and current_file != self._previous_gcode_file
  4846. and self._previous_gcode_file is not None
  4847. )
  4848. # Track RUNNING state for more robust completion detection
  4849. running_first_observed = False
  4850. if self.state.state == "RUNNING" and current_file:
  4851. if not self._was_running:
  4852. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  4853. # Check if timelapse was enabled in the same message (xcam parsed before this)
  4854. if self.state.timelapse:
  4855. self._timelapse_during_print = True
  4856. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  4857. # Mark this as the first RUNNING observation of the session.
  4858. # If is_new_print also fires below, on_print_start handles
  4859. # baseline capture and we suppress on_print_running_observed
  4860. # to avoid double-capture. If is_new_print does NOT fire
  4861. # (Bambuddy started mid-print — the #1304 guard suppressed
  4862. # it), main.py needs this hook to catch the restart-recovery
  4863. # case (#1485 follow-up).
  4864. running_first_observed = True
  4865. self._was_running = True
  4866. self._completion_triggered = False
  4867. if is_new_print or is_file_change:
  4868. # Clear any old HMS errors when a new print starts
  4869. self.state.hms_errors = []
  4870. # Reset layer tracking for new print (needed for layer-based timelapse)
  4871. self.state.layer_num = 0
  4872. # Reset total_layers so the previous print's value can't bleed into
  4873. # this print's usage-tracker split (#1771 follow-on to the
  4874. # preservation guard at the `total_layer_num` parse above — that
  4875. # guard ignores firmware-reset 0s, so the explicit reset has to
  4876. # happen here instead).
  4877. #
  4878. # #2702: reset to *this frame's* total, not to 0. The frame that
  4879. # trips the new-print detection can carry the new print's
  4880. # `total_layer_num` as well — the parse above has already applied
  4881. # it, and zeroing unconditionally threw it away. That looked
  4882. # harmless but is not recoverable: Bambu firmware sends only
  4883. # changed fields, so the printer never offers the total again, and
  4884. # the print runs to completion at `n/0` in the UI, in
  4885. # `{total_layers}` notifications, and as the usage-split
  4886. # denominator. The value only reappears on the next full pushall
  4887. # (reconnect / Force Refresh), which is why the symptom looked
  4888. # random and why a *stable* connection made it worse.
  4889. self.state.total_layers = total_from_this_frame
  4890. # If the starting frame brought no total, ask for one. Costs one
  4891. # MQTT message per print and covers the ordering where the printer
  4892. # published the total a frame or two before the state flip.
  4893. self._total_layers_refresh_armed = not total_from_this_frame
  4894. if self._total_layers_refresh_armed:
  4895. self._request_push_all()
  4896. # Reset completion tracking for new print
  4897. self._was_running = True
  4898. self._completion_triggered = False
  4899. # #1721: rearm the end-of-print finish-photo trigger for the new print
  4900. self._finish_photo_captured = False
  4901. # #2547: rearm the end-of-print telemetry probe for the new print
  4902. self._eop_probe_armed = True
  4903. self._eop_probe_open = False
  4904. self._eop_probe_frames = 0
  4905. self._eop_probe_last = {}
  4906. # Reset last valid progress/layer for usage tracking
  4907. self._last_valid_progress = 0.0
  4908. self._last_valid_layer_num = 0
  4909. # Clear and seed tray change log for mid-print usage splitting
  4910. self.state.tray_change_log.clear()
  4911. tn = self.state.tray_now
  4912. if (
  4913. (0 <= tn <= 15)
  4914. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  4915. or (128 <= tn <= 135)
  4916. or tn == 254
  4917. ):
  4918. self.state.tray_change_log.append((tn, 0))
  4919. # Initialize timelapse tracking based on current state
  4920. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  4921. # so self.state.timelapse may already be set from this message.
  4922. # We preserve that value instead of blindly resetting to False.
  4923. if self.state.timelapse:
  4924. self._timelapse_during_print = True
  4925. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  4926. else:
  4927. self._timelapse_during_print = False
  4928. if (is_new_print or is_file_change) and self.on_print_start:
  4929. logger.info(
  4930. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  4931. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  4932. )
  4933. self.on_print_start(
  4934. {
  4935. "filename": current_file,
  4936. "subtask_name": self.state.subtask_name,
  4937. "remaining_time": self.state.remaining_time * 60
  4938. if self.state.remaining_time > 0
  4939. else None, # Convert minutes to seconds
  4940. "raw_data": data,
  4941. "ams_mapping": self._captured_ams_mapping,
  4942. }
  4943. )
  4944. elif running_first_observed and self.on_print_running_observed:
  4945. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  4946. # print, so the #1304 first-push guard suppressed on_print_start,
  4947. # but we still need main.py to capture a fresh timelapse baseline
  4948. # before the printer uploads the in-flight MP4. Same payload
  4949. # shape as on_print_start so the consumer can reuse fields.
  4950. logger.info(
  4951. f"[{self.serial_number}] RUNNING observed without PRINT START "
  4952. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  4953. )
  4954. self.on_print_running_observed(
  4955. {
  4956. "filename": current_file,
  4957. "subtask_name": self.state.subtask_name,
  4958. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  4959. "raw_data": data,
  4960. "ams_mapping": self._captured_ams_mapping,
  4961. }
  4962. )
  4963. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  4964. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  4965. # This handles cases where server restarts during a print
  4966. should_trigger_completion = (
  4967. self.state.state in ("FINISH", "FAILED")
  4968. and not self._completion_triggered
  4969. and self.on_print_complete
  4970. and (
  4971. self._previous_gcode_state == "RUNNING" # Normal transition
  4972. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  4973. # Pre-print failure (#1111): printer rejected the job during setup
  4974. # — wrong nozzle size, AMS error, etc. The print never reaches
  4975. # RUNNING, so without this branch neither the RUNNING check nor
  4976. # _was_running match and the queue item stays stuck at "printing".
  4977. # Restricted to FAILED from pre-print states so a stale FAILED on
  4978. # first connection (prev=None) still can't accidentally fire.
  4979. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  4980. )
  4981. )
  4982. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  4983. if (
  4984. self.state.state == "IDLE"
  4985. and self._previous_gcode_state == "RUNNING"
  4986. and not self._completion_triggered
  4987. and self.on_print_complete
  4988. ):
  4989. should_trigger_completion = True
  4990. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  4991. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  4992. if (
  4993. not should_trigger_completion
  4994. and self.state.state in ("FINISH", "FAILED")
  4995. and self._previous_gcode_state != self.state.state
  4996. ):
  4997. logger.info(
  4998. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  4999. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5000. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5001. )
  5002. # Mark as triggered so state is clean for the next print cycle
  5003. self._completion_triggered = True
  5004. if should_trigger_completion:
  5005. if self.state.state == "FINISH":
  5006. status = "completed"
  5007. elif self.state.state == "FAILED":
  5008. status = "failed"
  5009. else:
  5010. status = "aborted"
  5011. logger.info(
  5012. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5013. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5014. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5015. f"timelapse_during_print: {self._timelapse_during_print}"
  5016. )
  5017. timelapse_was_active = self._timelapse_during_print
  5018. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5019. # external-spool-only, HMS halt, or firmware variant that skips
  5020. # the unload phase) fire the finish-photo moment now. Bed has
  5021. # already dropped, framing is worse, but we still capture.
  5022. # Only on successful completion — aborted/failed prints don't
  5023. # produce a meaningful finish photo.
  5024. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5025. self._finish_photo_captured = True
  5026. logger.info(
  5027. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5028. f"stage-22 never fired; capturing at FINISH-state transition"
  5029. )
  5030. self.on_finish_photo_moment(
  5031. {
  5032. "trigger": "finish_state",
  5033. "filename": self._previous_gcode_file or current_file,
  5034. "subtask_name": self.state.subtask_name,
  5035. "timelapse_was_active": timelapse_was_active,
  5036. }
  5037. )
  5038. self._completion_triggered = True
  5039. self._was_running = False
  5040. self._timelapse_during_print = False # Reset for next print
  5041. # Include HMS errors for failure reason detection
  5042. hms_errors_data = (
  5043. [
  5044. {
  5045. "code": e.code,
  5046. "attr": e.attr,
  5047. "module": e.module,
  5048. "severity": e.severity,
  5049. # Carried so the queue's failure reason quotes the same
  5050. # sentence the status response and the broadcast do,
  5051. # rather than resolving the code a fourth time (#2926).
  5052. "description": e.description,
  5053. }
  5054. for e in self.state.hms_errors
  5055. ]
  5056. if self.state.hms_errors
  5057. else []
  5058. )
  5059. self.on_print_complete(
  5060. {
  5061. "status": status,
  5062. "filename": self._previous_gcode_file or current_file,
  5063. "subtask_name": self.state.subtask_name,
  5064. "raw_data": data,
  5065. "timelapse_was_active": timelapse_was_active,
  5066. "hms_errors": hms_errors_data,
  5067. "ams_mapping": self._captured_ams_mapping,
  5068. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5069. "last_progress": self._last_valid_progress,
  5070. "last_layer_num": self._last_valid_layer_num,
  5071. }
  5072. )
  5073. self._captured_ams_mapping = None
  5074. # Same lifecycle as the mapping above: it described *this* print.
  5075. # Leaving it set would hand the next print an answer about where a
  5076. # different file went, and a stale "internal storage" reading costs
  5077. # an archive that the FTPS sweep would have found (#2780).
  5078. self.state.current_project_url = None
  5079. self._previous_gcode_state = self.state.state
  5080. if current_file:
  5081. self._previous_gcode_file = current_file
  5082. if self.on_state_change:
  5083. self.on_state_change(self.state)
  5084. def _request_push_all(self):
  5085. """Request full status update from printer."""
  5086. if self._client:
  5087. message = {"pushing": {"command": "pushall"}}
  5088. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5089. def _probe_developer_mode(self):
  5090. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5091. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5092. For these, we detect developer mode by sending a harmless command and
  5093. checking whether the printer accepts or rejects it:
  5094. - result="success" → developer mode ON (commands accepted)
  5095. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5096. The probe re-sends the current external slot configuration so it's a no-op
  5097. when the command succeeds. If there's no external slot data yet, we send a
  5098. reset (empty filament) which is also safe.
  5099. """
  5100. if not self._client or not self.state.connected:
  5101. return
  5102. self._dev_mode_probed = True
  5103. self._dev_mode_probe_time = time.monotonic()
  5104. self._sequence_id += 1
  5105. seq = str(self._sequence_id)
  5106. self._dev_mode_probe_seq = seq
  5107. # Build probe command: re-send current external slot config (no-op on success)
  5108. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5109. current = vt_tray[0] if vt_tray else {}
  5110. command = {
  5111. "print": {
  5112. "command": "ams_filament_setting",
  5113. "ams_id": 255,
  5114. "tray_id": 0,
  5115. "slot_id": 0,
  5116. "tray_info_idx": current.get("tray_info_idx", ""),
  5117. "tray_type": current.get("tray_type", ""),
  5118. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5119. "tray_color": current.get("tray_color", "00000000"),
  5120. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5121. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5122. "sequence_id": seq,
  5123. }
  5124. }
  5125. setting_id = current.get("setting_id")
  5126. if setting_id:
  5127. command["print"]["setting_id"] = setting_id
  5128. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5129. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5130. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5131. """Reconcile developer_mode with the printer's own command-verification verdict.
  5132. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5133. control commands are being refused, so it outranks the probe in both
  5134. directions:
  5135. * present → developer_mode is definitively False, whatever the probe
  5136. concluded. The probe can only read the response to its own
  5137. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5138. instead, so the probe answers ENABLED while every print silently dies
  5139. (#2732).
  5140. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5141. probe, so a user who enables Developer Mode and restarts the printer
  5142. isn't stuck behind a verdict nothing would ever revisit.
  5143. A False that came from the probe or the ``fun`` bit is left alone — this
  5144. only ever unwinds its own latch.
  5145. """
  5146. if verify_failed:
  5147. if not self._dev_mode_from_hms:
  5148. logger.warning(
  5149. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5150. "rejecting control commands, so prints, temperature changes and filament "
  5151. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5152. self.serial_number,
  5153. HMS_MQTT_VERIFY_FAILED,
  5154. )
  5155. self._dev_mode_from_hms = True
  5156. self.state.developer_mode = False
  5157. return
  5158. if not self._dev_mode_from_hms:
  5159. return
  5160. logger.info(
  5161. "[%s] HMS %s cleared — re-probing developer mode",
  5162. self.serial_number,
  5163. HMS_MQTT_VERIFY_FAILED,
  5164. )
  5165. self._dev_mode_from_hms = False
  5166. self.state.developer_mode = None
  5167. self._dev_mode_probed = False
  5168. self._dev_mode_needs_probe = False
  5169. def _handle_dev_mode_probe_response(self, data: dict):
  5170. """Handle response to the developer mode probe command.
  5171. Sets developer_mode based on whether the printer accepted or rejected the command.
  5172. Three outcomes, not two. An explicit ``success`` proves commands are
  5173. accepted and an explicit verify-failure proves they are not, but anything
  5174. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5175. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5176. ``result`` at all, while refusing every control command and reporting
  5177. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5178. is what put ``developer_mode: pass`` in the support bundle of a printer
  5179. that had not accepted a command all day (#2732). Leaving it unknown makes
  5180. the connection diagnostic report ``skip``, which is the honest answer.
  5181. """
  5182. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5183. self._dev_mode_probe_failures = 0 # Reset on any response
  5184. result = data.get("result", "")
  5185. reason = data.get("reason", "")
  5186. if result == "failed" and "verify failed" in reason:
  5187. self.state.developer_mode = False
  5188. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5189. elif str(result).lower() == "success":
  5190. self.state.developer_mode = True
  5191. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5192. else:
  5193. # An HMS verdict already recorded here is real evidence; don't let an
  5194. # inconclusive probe response wipe it back to unknown.
  5195. if not self._dev_mode_from_hms:
  5196. self.state.developer_mode = None
  5197. logger.info(
  5198. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5199. "the printer neither confirmed nor refused the command",
  5200. self.serial_number,
  5201. result,
  5202. reason,
  5203. )
  5204. if self.on_state_change:
  5205. self.on_state_change(self.state)
  5206. def _request_version(self):
  5207. """Request firmware version info from printer."""
  5208. if self._client:
  5209. self._sequence_id += 1
  5210. message = {
  5211. "info": {
  5212. "sequence_id": str(self._sequence_id),
  5213. "command": "get_version",
  5214. }
  5215. }
  5216. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5217. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5218. def request_status_update(self) -> bool:
  5219. """Request a full status update from the printer (public API).
  5220. Sends both pushall and get_accessories commands to refresh all data
  5221. including nozzle hardware info.
  5222. Returns:
  5223. True if the request was sent, False if not connected.
  5224. """
  5225. if not self._client or not self.state.connected:
  5226. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5227. return False
  5228. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  5229. self._request_push_all()
  5230. # Note: get_accessories returns stale nozzle data on H2D.
  5231. # The correct nozzle data comes from push_status response.
  5232. return True
  5233. def _request_accessories(self):
  5234. """Request accessories info (nozzle type, etc.) from printer."""
  5235. if self._client:
  5236. self._sequence_id += 1
  5237. message = {
  5238. "system": {
  5239. "sequence_id": str(self._sequence_id),
  5240. "command": "get_accessories",
  5241. "accessory_type": "none",
  5242. }
  5243. }
  5244. logger.debug("[%s] Requesting accessories info", self.serial_number)
  5245. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5246. def _prime_kprofile_request(self):
  5247. """Send a priming K-profile request on connect.
  5248. Bambu printers often ignore the first K-profile request after connection,
  5249. so we send a dummy request on connect to 'prime' the system.
  5250. """
  5251. if self._client:
  5252. self._sequence_id += 1
  5253. command = {
  5254. "print": {
  5255. "command": "extrusion_cali_get",
  5256. "filament_id": "",
  5257. "nozzle_diameter": "0.4",
  5258. "sequence_id": str(self._sequence_id),
  5259. }
  5260. }
  5261. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  5262. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5263. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  5264. """Connect to the printer MQTT broker.
  5265. Args:
  5266. loop: The asyncio event loop to use for thread-safe callbacks.
  5267. If not provided, will try to get the running loop.
  5268. """
  5269. self._loop = loop
  5270. BambuMQTTClient._client_instance_counter += 1
  5271. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  5272. self._client = mqtt.Client(
  5273. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  5274. client_id=client_id,
  5275. protocol=mqtt.MQTTv311,
  5276. )
  5277. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  5278. # tracking (#1164). The default ceiling of 20 wedges sessions after
  5279. # ~16-20 cumulative commands; lifting it well above any realistic
  5280. # session count keeps QoS=1 working without changing wire-protocol
  5281. # behaviour across printer models.
  5282. self._client.max_inflight_messages_set(1000)
  5283. self._client.username_pw_set("bblp", self.access_code)
  5284. self._client.on_connect = self._on_connect
  5285. self._client.on_disconnect = self._on_disconnect
  5286. self._client.on_subscribe = self._on_subscribe
  5287. self._client.on_message = self._on_message
  5288. # TLS setup - Bambu uses self-signed certs
  5289. ssl_context = ssl.create_default_context()
  5290. ssl_context.check_hostname = False
  5291. ssl_context.verify_mode = ssl.CERT_NONE
  5292. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  5293. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  5294. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  5295. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  5296. # bare-metal installs whose build allows TLS 1.0.
  5297. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  5298. self._client.tls_set_context(ssl_context)
  5299. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  5300. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  5301. # Keepalive: paho sends PINGREQs at this interval, broker considers
  5302. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  5303. # real network loss (45s), not so aggressive that transient hiccups
  5304. # trigger false disconnects. Stale detection (60s no messages) handles
  5305. # the P1S/P1P firmware bug where the broker stops publishing but the
  5306. # TCP connection stays alive.
  5307. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  5308. self._client.loop_start()
  5309. def start_print(
  5310. self,
  5311. filename: str,
  5312. plate_id: int = 1,
  5313. ams_mapping: list[int] | None = None,
  5314. bed_levelling: str = "auto",
  5315. flow_cali: str = "auto",
  5316. vibration_cali: bool = True,
  5317. layer_inspect: bool = False,
  5318. timelapse: bool = False,
  5319. use_ams: bool = True,
  5320. nozzle_offset_cali: str = "auto",
  5321. nozzle_mapping: str | None = None,
  5322. nozzle_slot_extruders: str | None = None,
  5323. ):
  5324. """Start a print job on the printer.
  5325. The file should already be uploaded to the printer's root directory via FTP.
  5326. Args:
  5327. filename: Name of the uploaded file
  5328. plate_id: Plate number to print (default 1)
  5329. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  5330. Global tray ID = (ams_id * 4) + slot_id, external = 254
  5331. timelapse: Record timelapse video
  5332. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  5333. if the bed was levelled recently, matching BambuStudio).
  5334. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  5335. vibration_cali: Vibration compensation calibration
  5336. layer_inspect: First layer AI inspection
  5337. use_ams: Use AMS for automatic filament changes
  5338. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  5339. (dual-nozzle printers only — silently ignored on single-nozzle).
  5340. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  5341. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  5342. AND the printer is dual-nozzle, parsed and injected as the
  5343. `nozzle_mapping` array on the dispatched project_file so the
  5344. firmware honours the user's slicer pick instead of falling
  5345. back to "last matching nozzle" auto-pick. Silently ignored
  5346. on single-nozzle printers.
  5347. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  5348. MQTT extruder indices, derived from the 3MF when no
  5349. BambuStudio capture exists (#2800). Consulted only on
  5350. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  5351. not already supply one; resolved here into physical rack
  5352. positions using the live `device.nozzle` state. When it
  5353. cannot be resolved the field is omitted and the firmware
  5354. picks, as it did before this existed.
  5355. Returns True when the start command was published, False otherwise
  5356. (not connected, or the printer is already busy — see the run-state
  5357. guard below).
  5358. """
  5359. # Never dispatch project_file to a printer that is not idle (#2598).
  5360. # This is the single publish choke point for every dispatch path — the
  5361. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  5362. # forwarded job all funnel through here — so one guard covers them all.
  5363. # The firmware rejects a start while busy with 0500_4004 ("Device is
  5364. # busy and cannot start a new task"), and on an A1 mini that error
  5365. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  5366. # start targets; only the active-print states are refused. (A
  5367. # transport-level QoS-1 replay on reconnect would bypass this guard,
  5368. # but the dispatch/watchdog reconnect path hard-resets the client with a
  5369. # fresh client_id, so paho has no inflight project_file to replay there.)
  5370. if self.state.state in _ACTIVE_PRINT_STATES:
  5371. logger.warning(
  5372. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  5373. self.serial_number,
  5374. self.state.state,
  5375. filename,
  5376. )
  5377. return False
  5378. if self._client and self.state.connected:
  5379. # Bambu print command format — matches Bambu Studio's format.
  5380. # The calibration/leveling fields (timelapse, bed_leveling,
  5381. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  5382. # every model. An earlier revision integer-encoded them for the H2
  5383. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  5384. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  5385. # sends plain booleans, and the integer encoding made the H2S
  5386. # silently skip flow-dynamics calibration (#1478). use_ams is the
  5387. # one field that genuinely must stay boolean: H2D Pro firmware
  5388. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  5389. # what actually caused the wrong-extruder routing behind #1386.
  5390. # Dual-nozzle routing for external spool (254 = deputy/left,
  5391. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  5392. # H2 firmware family but is single-nozzle, despite sharing serial
  5393. # prefix "094" with H2D. Prefer runtime detection from
  5394. # device.extruder.info (set in _handle_push_status); fall back to
  5395. # model name for the brief window after connect before push data
  5396. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  5397. # as the primary signal.
  5398. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  5399. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  5400. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  5401. ams_mapping2 = []
  5402. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  5403. # ams_mapping and relies on ams_mapping2 for external spool details.
  5404. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  5405. # with 0700_8012 "Failed to get AMS mapping table".
  5406. flat_ams_mapping = []
  5407. if ams_mapping is not None:
  5408. for tray_id in ams_mapping:
  5409. # Ensure tray_id is an integer (may be string from JSON)
  5410. tray_id = int(tray_id) if tray_id is not None else -1
  5411. if tray_id == -1:
  5412. # Unmapped filament slot
  5413. flat_ams_mapping.append(-1)
  5414. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  5415. elif tray_id >= 254:
  5416. # External/virtual spool. BambuStudio convention:
  5417. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  5418. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  5419. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  5420. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  5421. # for external spool, but BambuStudio always sends ams_id=255
  5422. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  5423. # firmware to target AMS tray 0 instead of external spool, leading
  5424. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  5425. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  5426. flat_ams_mapping.append(-1)
  5427. ext_ams_id = tray_id if is_dual_nozzle else 255
  5428. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  5429. elif tray_id >= 128:
  5430. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  5431. flat_ams_mapping.append(tray_id)
  5432. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  5433. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  5434. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  5435. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  5436. # — both CONFIRMED against the firmware's own mapping
  5437. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  5438. _wire_ams, _wire_slot, _ = _a2l
  5439. flat_ams_mapping.append(_wire_slot)
  5440. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  5441. else:
  5442. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  5443. ams_id = tray_id // 4
  5444. slot_id = tray_id % 4
  5445. flat_ams_mapping.append(tray_id)
  5446. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  5447. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  5448. # printers — the mapping is authoritative about whether this print
  5449. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  5450. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  5451. # H2S falls through here now (#1386): it is single-nozzle and was
  5452. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  5453. # without an AMS attached.
  5454. #
  5455. # Two symmetric corrections:
  5456. #
  5457. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  5458. # use_ams=True even if it arrived False. A print sent to a Virtual
  5459. # Printer is sliced against the VP, which advertises no AMS, so the
  5460. # slicer sends use_ams=false and that gets stamped on the queue item
  5461. # — but at dispatch the scheduler colour-matches a real printer and
  5462. # resolves a real AMS slot. Without this, the stale False reaches the
  5463. # printer, which ignores the mapped slot and aborts at layer 0 on the
  5464. # empty external spool ("not enough filament"). Diagnosed by
  5465. # @Sawtaytoes (#2595, PR #2596).
  5466. #
  5467. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  5468. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  5469. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  5470. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  5471. # status-load race that persisted [-1] (#2589) — and treating it as
  5472. # external silently started the print against an empty feed. A genuine
  5473. # external selection is >=254; unresolved is -1; a loaded tray is
  5474. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  5475. # (or is recomputed upstream) instead of silently going external, and
  5476. # never gets force-enabled by (a) either.
  5477. if ams_mapping and not is_dual_nozzle:
  5478. has_real_tray = any(t is not None and 0 <= int(t) <= 253 for t in ams_mapping)
  5479. all_external = all(t is None or int(t) >= 254 for t in ams_mapping)
  5480. if has_real_tray and not use_ams:
  5481. use_ams = True
  5482. logger.info(
  5483. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  5484. self.serial_number,
  5485. )
  5486. elif use_ams and all_external:
  5487. use_ams = False
  5488. logger.info(
  5489. "[%s] All filament slots use external spool — setting use_ams=False",
  5490. self.serial_number,
  5491. )
  5492. # Unique per-submission identity fields. Hardcoded "0" values caused
  5493. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  5494. # continuations of the same job: the printer reuses gcode_start_time
  5495. # from the prior print with task_id=0, so observers latch onto a stale
  5496. # timestamp and report compounding durations on repeat replays (#1011).
  5497. # BambuStudio mints fresh IDs per submission; matching that behavior
  5498. # makes the printer emit a clean state-transition for each job.
  5499. # md5 is left empty — firmware historically accepts "" as "skip
  5500. # validation" (unlike Studio, we don't have the file's real md5 here
  5501. # without re-reading the upload, and sending a synthetic wrong digest
  5502. # risks activation of md5 verification on some firmwares).
  5503. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  5504. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  5505. # overflows and every submission ends up with the same task_id from
  5506. # the printer's perspective — the printer then treats a fresh dispatch
  5507. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  5508. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  5509. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  5510. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  5511. # Remember it so on_print_start can persist a restart-stable id on
  5512. # the archive even before the printer echoes subtask_id back (#1485).
  5513. self.last_dispatch_subtask_id = submission_id
  5514. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  5515. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  5516. # only if it wasn't done recently). The paired bool field is true
  5517. # only for the explicit "on" state — for "auto" the bool is false and
  5518. # the int carries the intent, exactly as BambuStudio's SelectMachine
  5519. # sends it. Unknown values fall back to auto.
  5520. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  5521. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  5522. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  5523. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  5524. command = {
  5525. "print": {
  5526. "sequence_id": "20000",
  5527. "command": "project_file",
  5528. "param": f"Metadata/plate_{plate_id}.gcode",
  5529. "url": f"ftp://{filename}",
  5530. "file": filename,
  5531. "md5": "",
  5532. "bed_type": "auto",
  5533. "timelapse": timelapse,
  5534. # bed_leveling stays a JSON bool (true only for "on") and
  5535. # auto_bed_leveling carries the tri-state int — the exact
  5536. # two-field shape BambuStudio sends. The int must stay a plain
  5537. # number, never quoted (#1478 boolean-family concern applies to
  5538. # the *_cali bools, not these companion ints).
  5539. "bed_leveling": bed_levelling == "on",
  5540. "auto_bed_leveling": bed_level_int,
  5541. "flow_cali": flow_cali == "on",
  5542. "vibration_cali": vibration_cali,
  5543. "layer_inspect": layer_inspect,
  5544. "use_ams": use_ams,
  5545. "cfg": "0",
  5546. # extrude_cali_flag gates flow-dynamics calibration:
  5547. # 0 = never, 1 = force every print, 2 = auto (run only if the
  5548. # filament wasn't calibrated recently). #1721 saw stage 8
  5549. # ("Calibrating dynamic flow") still queued when we send 2 —
  5550. # that is exactly the auto contract (the printer queues the
  5551. # stage and skips it at runtime if recent), not a bug, so 2 is
  5552. # the right wire value for "auto". off/on remain 0/1.
  5553. "extrude_cali_flag": flow_cali_int,
  5554. "extrude_cali_manual_mode": 0,
  5555. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  5556. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  5557. # again the auto contract, not a failure to suppress.
  5558. # BambuStudio exposes the toggle only for dual-nozzle
  5559. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  5560. # firmware never runs a calibration the head doesn't support.
  5561. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  5562. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  5563. "profile_id": "0",
  5564. "project_id": submission_id,
  5565. "subtask_id": submission_id,
  5566. "task_id": submission_id,
  5567. }
  5568. }
  5569. # P2S-specific parameter adjustments
  5570. # P2S printer doesn't support vibration calibration like X1/P1 series
  5571. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  5572. command["print"]["vibration_cali"] = False
  5573. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  5574. # Add AMS mapping if provided
  5575. if ams_mapping is not None:
  5576. command["print"]["ams_mapping"] = flat_ams_mapping
  5577. command["print"]["ams_mapping2"] = ams_mapping2
  5578. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  5579. # `nozzle_mapping` carries per-filament physical nozzle position
  5580. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  5581. # item; parse here so the wire ships an array, matching
  5582. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  5583. # defensively — single-nozzle firmwares would ignore the field
  5584. # but we err on the side of not emitting unrecognised fields. A
  5585. # parse failure is logged but never blocks the dispatch — the
  5586. # firmware will fall back to its auto-pick path, which is the
  5587. # pre-fix behaviour.
  5588. if is_dual_nozzle and nozzle_mapping:
  5589. try:
  5590. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  5591. except json.JSONDecodeError:
  5592. logger.warning(
  5593. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  5594. "project_file (firmware will auto-pick): %r",
  5595. self.serial_number,
  5596. nozzle_mapping,
  5597. )
  5598. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  5599. # never saw the job, so it can never override a real capture. The
  5600. # queue stores extruder indices per filament slot; the physical
  5601. # rack position they resolve to is only knowable here, because the
  5602. # mounted hotend can change between queueing and dispatch.
  5603. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  5604. try:
  5605. slot_extruders = json.loads(nozzle_slot_extruders)
  5606. except (json.JSONDecodeError, TypeError):
  5607. # TypeError covers a caller handing us the list itself
  5608. # rather than its JSON — the field is opaque by contract,
  5609. # and a print must not die over the difference.
  5610. slot_extruders = None
  5611. logger.warning(
  5612. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  5613. "omitting nozzle_mapping (firmware will auto-pick): %r",
  5614. self.serial_number,
  5615. nozzle_slot_extruders,
  5616. )
  5617. if isinstance(slot_extruders, list):
  5618. rack_nozzle_id = (
  5619. self.state.nozzle_rack_tar_id
  5620. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  5621. else self.state.nozzle_rack_src_id
  5622. )
  5623. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  5624. if resolved is None:
  5625. logger.info(
  5626. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  5627. "omitting nozzle_mapping so the firmware picks",
  5628. self.serial_number,
  5629. slot_extruders,
  5630. self.state.nozzle_rack_tar_id,
  5631. self.state.nozzle_rack_src_id,
  5632. )
  5633. else:
  5634. logger.info(
  5635. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  5636. self.serial_number,
  5637. slot_extruders,
  5638. rack_nozzle_id,
  5639. resolved,
  5640. )
  5641. command["print"]["nozzle_mapping"] = resolved
  5642. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  5643. # Remember this dispatch so its echo on the topic is recognised as
  5644. # ours rather than logged as a slicer's.
  5645. self._own_project_file_key = self._project_file_key(command["print"])
  5646. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5647. # Record what we dispatched so /cover can pick the right plate
  5648. # thumbnail even when the printer's gcode_file echo is just the
  5649. # 3MF filename without a plate path (#1166). Match the same
  5650. # subtask_name shape we send so the comparison in the cover route
  5651. # works against state.subtask_name reflected back via MQTT.
  5652. self.state.dispatched_plate_id = plate_id
  5653. self.state.dispatched_subtask = command["print"]["subtask_name"]
  5654. return True
  5655. else:
  5656. # Log why we couldn't send the command
  5657. if not self._client:
  5658. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  5659. elif not self.state.connected:
  5660. logger.error(
  5661. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  5662. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  5663. )
  5664. return False
  5665. def stop_print(self) -> bool:
  5666. """Stop the current print job."""
  5667. if self._client and self.state.connected:
  5668. command = {"print": {"command": "stop", "sequence_id": "0"}}
  5669. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5670. logger.info("[%s] Sent stop print command", self.serial_number)
  5671. return True
  5672. return False
  5673. def set_xcam_option(
  5674. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  5675. ) -> bool:
  5676. """Set an xcam (AI detection) option on the printer.
  5677. Args:
  5678. module_name: The xcam module to control (e.g., "spaghetti_detector",
  5679. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  5680. enabled: Whether to enable or disable the feature
  5681. print_halt: Whether to halt print on detection (only applies to some detectors)
  5682. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  5683. Returns:
  5684. True if command was sent, False if not connected
  5685. """
  5686. if not self._client or not self.state.connected:
  5687. return False
  5688. # auto_recovery_step_loss uses a different command format (print.print_option)
  5689. if module_name == "auto_recovery_step_loss":
  5690. return self._set_print_option("auto_recovery", enabled)
  5691. self._sequence_id += 1
  5692. # Build the xcam control command (exact OrcaSlicer format)
  5693. # Key findings from OrcaSlicer source:
  5694. # - Uses "xcam" wrapper (not "print")
  5695. # - print_halt is ALWAYS true (legacy protocol requirement)
  5696. # - Both "control" and "enable" are set to the same value
  5697. # - halt_print_sensitivity controls actual halt behavior
  5698. command = {
  5699. "xcam": {
  5700. "command": "xcam_control_set",
  5701. "sequence_id": str(self._sequence_id),
  5702. "module_name": module_name,
  5703. "control": enabled,
  5704. "enable": enabled, # old protocol compatibility
  5705. "print_halt": True, # ALWAYS true per OrcaSlicer
  5706. }
  5707. }
  5708. # Only add sensitivity if not "never_halt"
  5709. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  5710. # The module_name field determines which detector's sensitivity is being set
  5711. if sensitivity and sensitivity != "never_halt":
  5712. command["xcam"]["halt_print_sensitivity"] = sensitivity
  5713. command_json = json.dumps(command)
  5714. self._client.publish(self.topic_publish, command_json, qos=1)
  5715. logger.debug(
  5716. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  5717. )
  5718. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  5719. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  5720. # This prevents stale MQTT data from immediately overwriting our change
  5721. self._xcam_hold_start[module_name] = time.time()
  5722. # Update local state immediately for responsive UI
  5723. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  5724. # When spaghetti_detector sensitivity is changed, pileup also changes
  5725. if module_name == "spaghetti_detector":
  5726. self.state.print_options.spaghetti_detector = enabled
  5727. self.state.print_options.print_halt = print_halt
  5728. if sensitivity and sensitivity != "never_halt":
  5729. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  5730. self.state.print_options.halt_print_sensitivity = sensitivity
  5731. self.state.print_options.pileup_sensitivity = sensitivity
  5732. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  5733. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  5734. elif module_name == "first_layer_inspector":
  5735. self.state.print_options.first_layer_inspector = enabled
  5736. elif module_name == "printing_monitor":
  5737. self.state.print_options.printing_monitor = enabled
  5738. elif module_name == "buildplate_marker_detector":
  5739. self.state.print_options.buildplate_marker_detector = enabled
  5740. elif module_name == "allow_skip_parts":
  5741. self.state.print_options.allow_skip_parts = enabled
  5742. elif module_name == "pileup_detector":
  5743. self.state.print_options.pileup_detector = enabled
  5744. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  5745. elif module_name == "clump_detector":
  5746. self.state.print_options.nozzle_clumping_detector = enabled
  5747. if sensitivity and sensitivity != "never_halt":
  5748. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  5749. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  5750. elif module_name == "airprint_detector":
  5751. self.state.print_options.airprint_detector = enabled
  5752. if sensitivity and sensitivity != "never_halt":
  5753. self.state.print_options.airprint_sensitivity = sensitivity
  5754. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  5755. elif module_name == "auto_recovery_step_loss":
  5756. self.state.print_options.auto_recovery_step_loss = enabled
  5757. return True
  5758. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  5759. """Set a print option using the print.print_option command.
  5760. This is different from xcam_control_set and is used for options like:
  5761. - auto_recovery
  5762. - air_print_detect
  5763. - filament_tangle_detect
  5764. - nozzle_blob_detect
  5765. - sound_enable
  5766. Args:
  5767. option_name: The option to control (e.g., "auto_recovery")
  5768. enabled: Whether to enable or disable the option
  5769. Returns:
  5770. True if command was sent, False if not connected
  5771. """
  5772. if not self._client or not self.state.connected:
  5773. return False
  5774. self._sequence_id += 1
  5775. command = {
  5776. "print": {
  5777. "command": "print_option",
  5778. "sequence_id": str(self._sequence_id),
  5779. option_name: enabled,
  5780. }
  5781. }
  5782. command_json = json.dumps(command)
  5783. self._client.publish(self.topic_publish, command_json, qos=1)
  5784. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  5785. # Set hold timer
  5786. hold_key = f"print_option_{option_name}"
  5787. self._xcam_hold_start[hold_key] = time.time()
  5788. # Update local state immediately
  5789. if option_name == "auto_recovery":
  5790. self.state.print_options.auto_recovery_step_loss = enabled
  5791. elif option_name == "auto_switch_filament":
  5792. self.state.ams_filament_backup = enabled
  5793. return True
  5794. def set_ams_filament_backup(self, enabled: bool) -> bool:
  5795. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  5796. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  5797. shape from H2D capture 2026-06-20.
  5798. """
  5799. return self._set_print_option("auto_switch_filament", enabled)
  5800. def start_calibration(
  5801. self,
  5802. bed_leveling: bool = False,
  5803. vibration: bool = False,
  5804. motor_noise: bool = False,
  5805. nozzle_offset: bool = False,
  5806. high_temp_heatbed: bool = False,
  5807. ) -> bool:
  5808. """Start printer calibration with selected options.
  5809. Args:
  5810. bed_leveling: Run bed leveling calibration
  5811. vibration: Run vibration compensation calibration
  5812. motor_noise: Run motor noise cancellation calibration
  5813. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  5814. high_temp_heatbed: Run high-temperature heatbed calibration
  5815. Returns:
  5816. True if command was sent, False if not connected
  5817. """
  5818. if not self._client or not self.state.connected:
  5819. return False
  5820. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  5821. # Bit 0: xcam_cali (not exposed in UI)
  5822. # Bit 1: bed_leveling
  5823. # Bit 2: vibration
  5824. # Bit 3: motor_noise
  5825. # Bit 4: nozzle_cali
  5826. # Bit 5: bed_cali (high-temp heatbed)
  5827. # Bit 6: clumppos_cali (not exposed in UI)
  5828. option = 0
  5829. if bed_leveling:
  5830. option |= 1 << 1
  5831. if vibration:
  5832. option |= 1 << 2
  5833. if motor_noise:
  5834. option |= 1 << 3
  5835. if nozzle_offset:
  5836. option |= 1 << 4
  5837. if high_temp_heatbed:
  5838. option |= 1 << 5
  5839. if option == 0:
  5840. logger.warning("[%s] No calibration options selected", self.serial_number)
  5841. return False
  5842. self._sequence_id += 1
  5843. command = {
  5844. "print": {
  5845. "command": "calibration",
  5846. "sequence_id": str(self._sequence_id),
  5847. "option": option,
  5848. }
  5849. }
  5850. command_json = json.dumps(command)
  5851. self._client.publish(self.topic_publish, command_json, qos=1)
  5852. logger.info(
  5853. f"[{self.serial_number}] Starting calibration: "
  5854. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  5855. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  5856. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  5857. )
  5858. return True
  5859. def disconnect(self, timeout: float = 0):
  5860. """Disconnect from the printer."""
  5861. if self._client:
  5862. self._disconnection_event = threading.Event()
  5863. self._client.disconnect()
  5864. self._disconnection_event.wait(timeout=timeout)
  5865. self._client.loop_stop()
  5866. self._client = None
  5867. self.state.connected = False
  5868. def send_command(self, command: dict):
  5869. """Send a command to the printer."""
  5870. if self._client and self.state.connected:
  5871. # Log outgoing message if logging is enabled
  5872. if self._logging_enabled:
  5873. self._message_log.append(
  5874. MQTTLogEntry(
  5875. timestamp=datetime.now(timezone.utc).isoformat(),
  5876. topic=self.topic_publish,
  5877. direction="out",
  5878. payload=command,
  5879. )
  5880. )
  5881. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5882. def enable_logging(self, enabled: bool = True):
  5883. """Enable or disable MQTT message logging."""
  5884. self._logging_enabled = enabled
  5885. # Don't clear logs when stopping - user can manually clear with clear_logs()
  5886. def get_logs(self) -> list[MQTTLogEntry]:
  5887. """Get all logged MQTT messages."""
  5888. return list(self._message_log)
  5889. def clear_logs(self):
  5890. """Clear the message log."""
  5891. self._message_log.clear()
  5892. @property
  5893. def logging_enabled(self) -> bool:
  5894. """Check if logging is enabled."""
  5895. return self._logging_enabled
  5896. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  5897. """Register a handler invoked for every incoming MQTT message.
  5898. Used by the VP MQTT bridge to republish the printer's report pushes to
  5899. slicers connected to a virtual printer in non-proxy mode. Handlers run
  5900. on paho's network thread and must not block; exceptions are caught.
  5901. """
  5902. if handler not in self._raw_message_handlers:
  5903. self._raw_message_handlers.append(handler)
  5904. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  5905. """Unregister a previously-registered raw-message handler."""
  5906. try:
  5907. self._raw_message_handlers.remove(handler)
  5908. except ValueError:
  5909. pass
  5910. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  5911. """Publish a pre-formed payload directly to the printer's MQTT broker.
  5912. Used by the VP MQTT bridge to forward slicer-originated commands without
  5913. going through send_command's sequence-id mangling. Returns False if the
  5914. underlying paho client isn't ready.
  5915. """
  5916. if self._client is None:
  5917. return False
  5918. try:
  5919. info = self._client.publish(topic, payload, qos=qos)
  5920. return info.rc == mqtt.MQTT_ERR_SUCCESS
  5921. except Exception:
  5922. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  5923. return False
  5924. def send_drying_command(
  5925. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  5926. ):
  5927. """Send AMS drying start/stop command.
  5928. Args:
  5929. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  5930. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  5931. duration: Drying duration in hours
  5932. mode: 1=start, 0=stop
  5933. filament: Filament type string (e.g. "PLA", "PETG")
  5934. rotate_tray: Whether to rotate the spool during drying for even heat
  5935. """
  5936. if not self._client:
  5937. return False
  5938. self._sequence_id += 1
  5939. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  5940. # not actually support drying, but keep the translation consistent). The
  5941. # _drying_targets dict below stays keyed by the normalised id so the
  5942. # on_drying_complete callback matches the telemetry.
  5943. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  5944. command = {
  5945. "print": {
  5946. "sequence_id": str(self._sequence_id),
  5947. "command": "ams_filament_drying",
  5948. "ams_id": wire_ams_id,
  5949. "temp": temp,
  5950. "cooling_temp": 20 if mode == 1 else 0,
  5951. "duration": duration,
  5952. "humidity": 0,
  5953. "mode": mode,
  5954. "rotate_tray": rotate_tray,
  5955. "filament": filament,
  5956. "close_power_conflict": False,
  5957. }
  5958. }
  5959. # Log the full wire JSON at INFO so support bundles capture exactly
  5960. # what we sent — needed to diagnose silent rejections (#1447) where
  5961. # the printer ACKs the command but never starts/stops drying.
  5962. # Paired with the ams_filament_drying response-payload INFO log so
  5963. # both halves of the conversation land in the bundle by default.
  5964. wire_json = json.dumps(command)
  5965. self._client.publish(self.topic_publish, wire_json, qos=1)
  5966. logger.info(
  5967. "[%s] Sent ams_filament_drying: %s",
  5968. self.serial_number,
  5969. wire_json,
  5970. )
  5971. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  5972. # while drying. Bambu only echoes dry_time on subsequent pushes.
  5973. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  5974. # say how much of the requested time the firmware actually ran (#2770).
  5975. if mode == 1:
  5976. self._drying_targets[ams_id] = {
  5977. "filament": filament or "",
  5978. "temp": int(temp),
  5979. "duration_hours": int(duration),
  5980. }
  5981. self._drying_stops_sent.discard(ams_id)
  5982. else:
  5983. self._drying_targets.pop(ams_id, None)
  5984. # Remember that this cycle's end is ours, so the cycle-end log
  5985. # attributes it to Bambuddy instead of to the firmware (#2770). A
  5986. # stop always ends the cycle far short of its duration, which is
  5987. # otherwise indistinguishable from the firmware abandoning it.
  5988. self._drying_stops_sent.add(ams_id)
  5989. return True
  5990. @staticmethod
  5991. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  5992. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  5993. The printer reports ``nozzle_diameter`` **only on the response
  5994. envelope** — the per-filament entries carry just setting_id,
  5995. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  5996. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  5997. single-nozzle printers regardless of the installed nozzle (#1748),
  5998. which broke the K-Profiles display and, worse, the cali_idx cascade
  5999. in the inventory/Spoolman assign paths that matches on
  6000. nozzle_diameter. Fall back to the envelope value instead, and only
  6001. to "0.4" when the envelope has none either.
  6002. ``or`` rather than a dict default on purpose: it also covers an entry
  6003. that carries the key with an empty value, and stops ``str()`` turning
  6004. a missing envelope value into the literal "None".
  6005. """
  6006. profiles: list[KProfile] = []
  6007. for i, f in enumerate(filaments):
  6008. if not isinstance(f, dict):
  6009. continue
  6010. try:
  6011. profiles.append(
  6012. KProfile(
  6013. # cali_idx is the actual slot/calibration index from the printer
  6014. slot_id=f.get("cali_idx", i),
  6015. extruder_id=int(f.get("extruder_id", 0)),
  6016. nozzle_id=str(f.get("nozzle_id", "")),
  6017. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6018. filament_id=str(f.get("filament_id", "")),
  6019. name=str(f.get("name", "")),
  6020. k_value=str(f.get("k_value", "0.000000")),
  6021. n_coef=str(f.get("n_coef", "0.000000")),
  6022. ams_id=int(f.get("ams_id", 0)),
  6023. tray_id=int(f.get("tray_id", -1)),
  6024. setting_id=f.get("setting_id"),
  6025. )
  6026. )
  6027. except (ValueError, TypeError) as e:
  6028. # Skip malformed entries; the remaining profiles stay usable.
  6029. # Unsolicited broadcasts arrive constantly, so only a response
  6030. # someone is actually waiting on is worth a warning.
  6031. if log_errors:
  6032. logger.warning("Failed to parse K-profile: %s", e)
  6033. else:
  6034. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6035. return profiles
  6036. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6037. """File one calibration-table response under its nozzle diameter.
  6038. ``response_nozzle`` names the table the printer just sent, so that
  6039. bucket is replaced wholesale and every other one is left alone. When
  6040. the envelope carries no diameter, fall back to the diameters the parsed
  6041. profiles claim for themselves — and if there are none of those either,
  6042. keep what we have rather than dropping a table we cannot attribute.
  6043. ``state.kprofiles`` stays a flat list because that is what its readers
  6044. expect; the three assign paths already filter it by ``nozzle_diameter``
  6045. and were quietly finding nothing whenever the last response happened to
  6046. be for a different nozzle.
  6047. """
  6048. buckets: dict[str, list] = {}
  6049. if response_nozzle:
  6050. buckets[str(response_nozzle)] = list(profiles)
  6051. else:
  6052. for profile in profiles:
  6053. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6054. if not buckets:
  6055. return
  6056. self._kprofiles_by_nozzle.update(buckets)
  6057. self.state.kprofiles = [
  6058. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6059. ]
  6060. def _handle_kprofile_response(self, data: dict):
  6061. """Handle K-profile response from printer."""
  6062. response_nozzle = data.get("nozzle_diameter")
  6063. response_seq_id = str(data.get("sequence_id", ""))
  6064. filaments = data.get("filaments", [])
  6065. # Snapshot the map: the asyncio thread adds and removes entries while
  6066. # this MQTT callback thread walks it.
  6067. pending = dict(self._pending_kprofile_requests)
  6068. request = pending.get(response_seq_id)
  6069. if request is None and pending:
  6070. # Firmware that doesn't echo our sequence_id still has to be
  6071. # served, so fall back to the pre-#1748 rule of matching on the
  6072. # nozzle size. Only requests still waiting are eligible, and the
  6073. # sequence_id lookup above has already claimed any response that
  6074. # identifies itself, so this can no longer hand request A's
  6075. # answer to request B when both are in flight.
  6076. request = next(
  6077. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6078. None,
  6079. )
  6080. if pending:
  6081. logger.info(
  6082. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6083. self.serial_number,
  6084. response_nozzle,
  6085. response_seq_id or "?",
  6086. len(filaments),
  6087. request is not None,
  6088. )
  6089. if request is None and pending:
  6090. # A request is outstanding and this isn't its answer. The printer
  6091. # broadcasts extrusion_cali_get unsolicited, so letting this
  6092. # through would replace state.kprofiles with another nozzle's
  6093. # profiles while the caller is still waiting.
  6094. logger.debug(
  6095. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6096. self.serial_number,
  6097. response_nozzle,
  6098. response_seq_id or "?",
  6099. )
  6100. return
  6101. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6102. self._store_kprofiles(profiles, response_nozzle)
  6103. if request is None:
  6104. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6105. # nobody to wake. Worth a line — this is the printer answering
  6106. # somebody else (BambuStudio queries the same report topic), and
  6107. # until it was bucketed by nozzle it was also the quietest way for
  6108. # the AMS card's K values to change underneath us.
  6109. logger.debug(
  6110. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6111. self.serial_number,
  6112. response_nozzle or "?",
  6113. len(profiles),
  6114. )
  6115. return
  6116. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6117. request["profiles"] = profiles
  6118. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6119. # in a different thread than the event loop.
  6120. event = request["event"]
  6121. if self._loop and self._loop.is_running():
  6122. self._loop.call_soon_threadsafe(event.set)
  6123. else:
  6124. # Fallback for when loop is not available
  6125. event.set()
  6126. async def get_kprofiles(
  6127. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6128. ) -> list[KProfile]:
  6129. """Request K-profiles from the printer with retry logic.
  6130. Bambu printers sometimes ignore the first K-profile request, so we
  6131. implement retry logic to ensure reliable retrieval.
  6132. Args:
  6133. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6134. timeout: Timeout in seconds to wait for each response attempt
  6135. max_retries: Maximum number of retry attempts
  6136. Returns:
  6137. List of KProfile objects
  6138. """
  6139. if not self._client or not self.state.connected:
  6140. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6141. return []
  6142. # Capture current event loop for thread-safe callback
  6143. try:
  6144. self._loop = asyncio.get_running_loop()
  6145. except RuntimeError:
  6146. logger.warning("[%s] No running event loop", self.serial_number)
  6147. return []
  6148. for attempt in range(max_retries):
  6149. # Register this attempt under its own sequence_id so a concurrent
  6150. # request for a different nozzle size can't consume its response
  6151. # (#1748) — the pending map is keyed by exactly the id we send.
  6152. self._sequence_id += 1
  6153. seq_id = str(self._sequence_id)
  6154. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6155. self._pending_kprofile_requests[seq_id] = request
  6156. # Send the command with nozzle_diameter filter
  6157. command = {
  6158. "print": {
  6159. "command": "extrusion_cali_get",
  6160. "filament_id": "",
  6161. "nozzle_diameter": nozzle_diameter,
  6162. "sequence_id": seq_id,
  6163. }
  6164. }
  6165. logger.info(
  6166. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6167. )
  6168. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6169. # Wait for the response (the handler matches it back to this entry)
  6170. try:
  6171. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6172. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6173. profiles = request["profiles"] or []
  6174. logger.info(
  6175. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6176. )
  6177. return profiles
  6178. except TimeoutError:
  6179. logger.warning(
  6180. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  6181. )
  6182. if attempt < max_retries - 1:
  6183. # Brief delay before retry
  6184. await asyncio.sleep(0.5)
  6185. finally:
  6186. self._pending_kprofile_requests.pop(seq_id, None)
  6187. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  6188. return []
  6189. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  6190. """Publish a K-profile write and arm its ack slot.
  6191. Registration happens before the publish because the printer answers in
  6192. well under a second — measured at 70-150ms — which is comfortably
  6193. before an async caller gets back to awaiting.
  6194. """
  6195. self._pending_cali_acks[seq_id] = None
  6196. try:
  6197. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6198. except Exception:
  6199. self._pending_cali_acks.pop(seq_id, None)
  6200. raise
  6201. return True
  6202. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  6203. """Wait for the printer's verdict on a K-profile write.
  6204. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  6205. explicitly said ``result: "fail"`` — a timeout returns True with a
  6206. detail string, because "no answer" is not evidence of rejection and
  6207. older firmware may not answer at all. Callers that need certainty read
  6208. the calibration table back.
  6209. Polled rather than event-driven on purpose: the ack is filled in by the
  6210. MQTT callback thread, and polling a dict costs one lookup every 50ms
  6211. for at most a few hundred milliseconds, against the cross-thread
  6212. event plumbing it would otherwise take.
  6213. """
  6214. deadline = time.monotonic() + timeout
  6215. try:
  6216. while time.monotonic() < deadline:
  6217. ack = self._pending_cali_acks.get(seq_id)
  6218. if ack is not None:
  6219. result = str(ack.get("result", "")).lower()
  6220. reason = str(ack.get("reason", "") or "")
  6221. if result == "fail":
  6222. return (False, reason or "printer reported failure")
  6223. return (True, reason)
  6224. await asyncio.sleep(0.05)
  6225. finally:
  6226. self._pending_cali_acks.pop(seq_id, None)
  6227. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  6228. return (True, "no acknowledgement from printer")
  6229. def set_kprofile(
  6230. self,
  6231. filament_id: str,
  6232. name: str,
  6233. k_value: str,
  6234. nozzle_diameter: str = "0.4",
  6235. nozzle_id: str = "HS00-0.4",
  6236. extruder_id: int = 0,
  6237. setting_id: str | None = None,
  6238. slot_id: int = 0,
  6239. cali_idx: int | None = None,
  6240. ) -> str | None:
  6241. """Set/update a K-profile on the printer.
  6242. Args:
  6243. filament_id: Bambu filament identifier
  6244. name: Profile name
  6245. k_value: Pressure advance value (e.g., "0.020000")
  6246. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6247. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  6248. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6249. setting_id: Existing setting ID for updates, None for new
  6250. slot_id: Calibration index (cali_idx) for the profile
  6251. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  6252. Returns:
  6253. The sequence_id the command was sent under, so the caller can
  6254. await the printer's verdict via await_cali_ack. None if the
  6255. command could not be sent.
  6256. """
  6257. if not self._client or not self.state.connected:
  6258. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  6259. return None
  6260. self._sequence_id += 1
  6261. seq_id = str(self._sequence_id)
  6262. # Build the filament entry - printer uses cali_idx for profile identification
  6263. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  6264. # For edits, use the provided cali_idx or slot_id
  6265. if cali_idx is not None:
  6266. effective_cali_idx = cali_idx
  6267. else:
  6268. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6269. # Generate a setting_id for new profiles (required by printer)
  6270. # Format: "PF" + 17 random digits
  6271. import random
  6272. if not setting_id and slot_id == 0:
  6273. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6274. filament_entry = {
  6275. "ams_id": 0,
  6276. "cali_idx": effective_cali_idx,
  6277. "extruder_id": extruder_id,
  6278. "filament_id": filament_id,
  6279. "k_value": k_value,
  6280. "n_coef": "0.000000",
  6281. "name": name,
  6282. "nozzle_diameter": nozzle_diameter,
  6283. "nozzle_id": nozzle_id,
  6284. "setting_id": setting_id if setting_id else "",
  6285. # 0, not -1. Single-nozzle firmware validates this field and
  6286. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  6287. # applying the write anyway, so the rejection looked like noise.
  6288. # Measured on an X1C: flipping only this value turns the ack into
  6289. # `success` (#2718). BambuStudio always sends a real tray_id and
  6290. # defaults it to 0 for a manually entered profile.
  6291. "tray_id": 0,
  6292. }
  6293. command = {
  6294. "print": {
  6295. "command": "extrusion_cali_set",
  6296. "filaments": [filament_entry],
  6297. "nozzle_diameter": nozzle_diameter,
  6298. "sequence_id": seq_id,
  6299. }
  6300. }
  6301. command_json = json.dumps(command)
  6302. logger.info(
  6303. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  6304. )
  6305. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  6306. self._publish_cali_write(command, seq_id)
  6307. return seq_id
  6308. def set_kprofiles_batch(
  6309. self,
  6310. profiles: list[dict],
  6311. nozzle_diameter: str = "0.4",
  6312. ) -> str | None:
  6313. """Set multiple K-profiles in a single command (for dual-nozzle).
  6314. Args:
  6315. profiles: List of profile dicts, each with:
  6316. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  6317. nozzle_diameter: Common nozzle diameter for all profiles
  6318. Returns:
  6319. The sequence_id the command was sent under (see set_kprofile),
  6320. or None if it could not be sent.
  6321. """
  6322. if not self._client or not self.state.connected:
  6323. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  6324. return None
  6325. import random
  6326. self._sequence_id += 1
  6327. seq_id = str(self._sequence_id)
  6328. filament_entries = []
  6329. for p in profiles:
  6330. slot_id = p.get("slot_id", 0)
  6331. cali_idx = p.get("cali_idx")
  6332. if cali_idx is not None:
  6333. effective_cali_idx = cali_idx
  6334. else:
  6335. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6336. setting_id = p.get("setting_id")
  6337. if not setting_id and slot_id == 0:
  6338. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6339. filament_entries.append(
  6340. {
  6341. "ams_id": 0,
  6342. "cali_idx": effective_cali_idx,
  6343. "extruder_id": p.get("extruder_id", 0),
  6344. "filament_id": p.get("filament_id", ""),
  6345. "k_value": p.get("k_value", "0.020000"),
  6346. "n_coef": "0.000000",
  6347. "name": p.get("name", ""),
  6348. "nozzle_diameter": nozzle_diameter,
  6349. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  6350. "setting_id": setting_id if setting_id else "",
  6351. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  6352. # single-nozzle firmware even though the write lands (#2718).
  6353. "tray_id": 0,
  6354. }
  6355. )
  6356. command = {
  6357. "print": {
  6358. "command": "extrusion_cali_set",
  6359. "filaments": filament_entries,
  6360. "nozzle_diameter": nozzle_diameter,
  6361. "sequence_id": seq_id,
  6362. }
  6363. }
  6364. command_json = json.dumps(command)
  6365. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  6366. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  6367. self._publish_cali_write(command, seq_id)
  6368. return seq_id
  6369. def delete_kprofile(
  6370. self,
  6371. cali_idx: int,
  6372. filament_id: str,
  6373. nozzle_id: str,
  6374. nozzle_diameter: str = "0.4",
  6375. extruder_id: int = 0,
  6376. setting_id: str | None = None,
  6377. ) -> str | None:
  6378. """Delete a K-profile from the printer.
  6379. Args:
  6380. cali_idx: The calibration index (slot_id) of the profile to delete
  6381. filament_id: Bambu filament identifier
  6382. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  6383. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6384. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6385. setting_id: Unique setting identifier (for X1C series)
  6386. Returns:
  6387. The sequence_id the command was sent under (see set_kprofile),
  6388. or None if it could not be sent.
  6389. """
  6390. if not self._client or not self.state.connected:
  6391. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  6392. return None
  6393. self._sequence_id += 1
  6394. seq_id = str(self._sequence_id)
  6395. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  6396. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  6397. # Prefer runtime detection from device.extruder.info; fall back to
  6398. # model name. H2S is single-nozzle but shares serial prefix "094" with
  6399. # H2D, so a prefix-only check misclassified it (#1386).
  6400. from backend.app.utils.printer_models import is_dual_nozzle_model
  6401. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6402. if is_dual_nozzle:
  6403. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  6404. command = {
  6405. "print": {
  6406. "command": "extrusion_cali_del",
  6407. "sequence_id": seq_id,
  6408. "extruder_id": extruder_id,
  6409. "nozzle_id": nozzle_id,
  6410. "filament_id": filament_id,
  6411. "cali_idx": cali_idx,
  6412. "nozzle_diameter": nozzle_diameter,
  6413. }
  6414. }
  6415. else:
  6416. # X1C/P1/A1 format: include all fields like the set command
  6417. # The delete command structure should match what set uses
  6418. command = {
  6419. "print": {
  6420. "command": "extrusion_cali_del",
  6421. "sequence_id": seq_id,
  6422. "filament_id": filament_id,
  6423. "cali_idx": cali_idx,
  6424. "setting_id": setting_id if setting_id else "",
  6425. "nozzle_diameter": nozzle_diameter,
  6426. "nozzle_id": nozzle_id,
  6427. "extruder_id": extruder_id,
  6428. }
  6429. }
  6430. command_json = json.dumps(command)
  6431. logger.info(
  6432. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  6433. )
  6434. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  6435. # QoS 1 for reliable delivery (at least once)
  6436. self._publish_cali_write(command, seq_id)
  6437. return seq_id
  6438. # =========================================================================
  6439. # Printer Control Commands
  6440. # =========================================================================
  6441. def pause_print(self) -> bool:
  6442. """Pause the current print job."""
  6443. if not self._client or not self.state.connected:
  6444. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  6445. return False
  6446. command = {"print": {"command": "pause", "sequence_id": "0"}}
  6447. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6448. logger.info("[%s] Sent pause print command", self.serial_number)
  6449. return True
  6450. def resume_print(self) -> bool:
  6451. """Resume a paused print job."""
  6452. if not self._client or not self.state.connected:
  6453. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  6454. return False
  6455. command = {"print": {"command": "resume", "sequence_id": "0"}}
  6456. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6457. logger.info("[%s] Sent resume print command", self.serial_number)
  6458. return True
  6459. def clear_hms_errors(self) -> bool:
  6460. """Clear HMS/print errors on the printer and locally."""
  6461. if not self._client or not self.state.connected:
  6462. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  6463. return False
  6464. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  6465. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6466. self.state.hms_errors = []
  6467. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  6468. return True
  6469. def skip_objects(self, object_ids: list[int]) -> bool:
  6470. """Skip specific objects during a print.
  6471. This command tells the printer to skip printing the specified objects.
  6472. The object IDs come from the slice_info.config file in the 3MF.
  6473. Args:
  6474. object_ids: List of identify_id values from slice_info.config
  6475. Returns:
  6476. True if command was sent, False otherwise
  6477. """
  6478. if not self._client or not self.state.connected:
  6479. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  6480. return False
  6481. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  6482. logger.warning(
  6483. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  6484. )
  6485. return False
  6486. if not object_ids:
  6487. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  6488. return False
  6489. # Validate all IDs are integers
  6490. try:
  6491. obj_list = [int(oid) for oid in object_ids]
  6492. except (ValueError, TypeError) as e:
  6493. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  6494. return False
  6495. self._sequence_id += 1
  6496. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  6497. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6498. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  6499. # Track skipped objects in state
  6500. for oid in obj_list:
  6501. if oid not in self.state.skipped_objects:
  6502. self.state.skipped_objects.append(oid)
  6503. return True
  6504. def send_gcode(self, gcode: str) -> bool:
  6505. """Send G-code command(s) to the printer.
  6506. Multiple commands can be separated by newlines.
  6507. Args:
  6508. gcode: G-code command(s) to send
  6509. Returns:
  6510. True if command was sent, False otherwise
  6511. """
  6512. if not self._client or not self.state.connected:
  6513. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  6514. return False
  6515. self._sequence_id += 1
  6516. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  6517. # Use QoS 1 for reliable delivery (at least once)
  6518. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6519. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  6520. return True
  6521. def set_bed_temperature(self, target: int) -> bool:
  6522. """Set the bed target temperature.
  6523. Args:
  6524. target: Target temperature in Celsius (0 to turn off)
  6525. Returns:
  6526. True if command was sent, False otherwise
  6527. """
  6528. return self.send_gcode(f"M140 S{target}")
  6529. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  6530. """Set the nozzle target temperature.
  6531. Args:
  6532. target: Target temperature in Celsius (0 to turn off)
  6533. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  6534. Returns:
  6535. True if command was sent, False otherwise
  6536. """
  6537. # Use M104 for non-blocking
  6538. # Always use T parameter for H2D compatibility
  6539. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  6540. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  6541. # Track it locally so we can display it correctly
  6542. if result and nozzle == 1:
  6543. self.state.temperatures["nozzle_target"] = float(target)
  6544. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  6545. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  6546. return result
  6547. def set_chamber_temperature(self, target: int) -> bool:
  6548. """Set the chamber target temperature.
  6549. Args:
  6550. target: Target temperature in Celsius (0 to turn off heating)
  6551. Returns:
  6552. True if command was sent, False otherwise
  6553. """
  6554. # M141 sets chamber temperature
  6555. result = self.send_gcode(f"M141 S{target}")
  6556. # Track chamber target locally (MQTT reports encoded values that need filtering)
  6557. if result:
  6558. self.state.temperatures["chamber_target"] = float(target)
  6559. self.state.temperatures["_chamber_target_set_time"] = time.time()
  6560. # Update heating state immediately based on new target
  6561. current_temp = self.state.temperatures.get("chamber", 0)
  6562. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  6563. logger.info(
  6564. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  6565. )
  6566. return result
  6567. def set_print_speed(self, mode: int) -> bool:
  6568. """Set the print speed mode.
  6569. Args:
  6570. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  6571. Returns:
  6572. True if command was sent, False otherwise
  6573. """
  6574. if not self._client or not self.state.connected:
  6575. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  6576. return False
  6577. if mode not in (1, 2, 3, 4):
  6578. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  6579. return False
  6580. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  6581. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6582. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  6583. return True
  6584. def set_fan_speed(self, fan: int, speed: int) -> bool:
  6585. """Set fan speed.
  6586. Args:
  6587. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=left auxiliary).
  6588. Index 10 is the optional left auxiliary part cooling fan on P2S/X2D
  6589. (airduct part id 10); Bambu's official machine profiles drive it with
  6590. "M106 P10" in start/layer-change gcode.
  6591. speed: Speed 0-255 (0=off, 255=full)
  6592. Returns:
  6593. True if command was sent, False otherwise
  6594. """
  6595. if fan not in (1, 2, 3, 10):
  6596. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  6597. return False
  6598. speed = max(0, min(255, speed)) # Clamp to 0-255
  6599. return self.send_gcode(f"M106 P{fan} S{speed}")
  6600. def set_part_fan(self, speed: int) -> bool:
  6601. """Set part cooling fan speed (0-255)."""
  6602. return self.set_fan_speed(1, speed)
  6603. def set_aux_fan(self, speed: int) -> bool:
  6604. """Set auxiliary fan speed (0-255)."""
  6605. return self.set_fan_speed(2, speed)
  6606. def set_chamber_fan(self, speed: int) -> bool:
  6607. """Set chamber fan speed (0-255)."""
  6608. return self.set_fan_speed(3, speed)
  6609. def set_left_aux_fan(self, speed: int) -> bool:
  6610. """Set left auxiliary part cooling fan speed (0-255). P2S/X2D accessory."""
  6611. return self.set_fan_speed(10, speed)
  6612. def set_airduct_mode(self, mode: str) -> bool:
  6613. """Set air conditioning mode (cooling or heating).
  6614. Args:
  6615. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  6616. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  6617. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  6618. closes top exhaust flap
  6619. Returns:
  6620. True if command was sent, False otherwise
  6621. """
  6622. if not self._client or not self.state.connected:
  6623. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  6624. return False
  6625. self._sequence_id += 1
  6626. mode_id = 0 if mode == "cooling" else 1
  6627. command = {
  6628. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  6629. }
  6630. # Use QoS 1 for reliable delivery
  6631. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6632. logger.info(
  6633. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  6634. )
  6635. return True
  6636. def set_chamber_light(self, on: bool) -> bool:
  6637. """Turn chamber light on or off.
  6638. Args:
  6639. on: True to turn on, False to turn off
  6640. Returns:
  6641. True if command was sent, False otherwise
  6642. """
  6643. if not self._client or not self.state.connected:
  6644. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  6645. return False
  6646. mode = "on" if on else "off"
  6647. # Control both chamber lights (some printers like H2D have two)
  6648. for led_node in ["chamber_light", "chamber_light2"]:
  6649. self._sequence_id += 1
  6650. command = {
  6651. "system": {
  6652. "command": "ledctrl",
  6653. "led_node": led_node,
  6654. "led_mode": mode,
  6655. "led_on_time": 500,
  6656. "led_off_time": 500,
  6657. "loop_times": 0,
  6658. "interval_time": 0,
  6659. "sequence_id": str(self._sequence_id),
  6660. }
  6661. }
  6662. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6663. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  6664. return True
  6665. def select_extruder(self, extruder: int) -> bool:
  6666. """Select the active extruder for dual-nozzle printers (H2D).
  6667. Args:
  6668. extruder: Extruder index (0=right, 1=left for H2D)
  6669. Returns:
  6670. True if command was sent, False otherwise
  6671. """
  6672. if extruder not in (0, 1):
  6673. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  6674. return False
  6675. if not self._client or not self.state.connected:
  6676. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  6677. return False
  6678. # H2D extruder switching via select_extruder command
  6679. # Command format captured from OrcaSlicer:
  6680. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  6681. # extruder_index: 0 = RIGHT, 1 = LEFT
  6682. self._sequence_id += 1
  6683. command = {
  6684. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  6685. }
  6686. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6687. logger.info(
  6688. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  6689. )
  6690. return True
  6691. def home_axes(self, axes: str = "XYZ") -> bool:
  6692. """Run the printer's full auto-home sequence.
  6693. The ``axes`` argument is ignored: a bare ``G28`` is always sent so
  6694. Bambu firmware runs its safe multi-step routine (park toolhead →
  6695. home XY → home Z). Partial-axis variants like ``G28 Z`` skip the
  6696. toolhead-park step and can crash the bed into the toolhead on H2C
  6697. / H2D / H2S / X1 where Z-home moves the bed UP — see #1052.
  6698. """
  6699. return self.send_gcode("G28")
  6700. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  6701. """Move an axis by a relative distance.
  6702. Args:
  6703. axis: Axis to move ("X", "Y", or "Z")
  6704. distance: Distance to move in mm (positive or negative)
  6705. speed: Movement speed in mm/min
  6706. Returns:
  6707. True if command was sent, False otherwise
  6708. """
  6709. axis = axis.upper()
  6710. if axis not in ("X", "Y", "Z"):
  6711. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  6712. return False
  6713. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  6714. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  6715. return self.send_gcode(gcode)
  6716. def disable_motors(self) -> bool:
  6717. """Disable all stepper motors.
  6718. Warning: This will cause the printer to lose its position.
  6719. A homing operation will be required before printing.
  6720. Returns:
  6721. True if command was sent, False otherwise
  6722. """
  6723. return self.send_gcode("M18")
  6724. def enable_motors(self) -> bool:
  6725. """Enable all stepper motors.
  6726. Returns:
  6727. True if command was sent, False otherwise
  6728. """
  6729. return self.send_gcode("M17")
  6730. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  6731. """Load filament from a specific AMS tray.
  6732. Args:
  6733. tray_id: Global tray ID — 0..15 for AMS slots, 254 for external spool
  6734. (single-external printers and Ext-L on dual-nozzle H2D),
  6735. 255 for Ext-R on dual-nozzle H2D.
  6736. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  6737. Sent only when given, matching BambuStudio: ``extruder_id`` is
  6738. an optional field on ``ams_change_filament``
  6739. (``DeviceManager::command_ams_change_filament``) and Studio
  6740. omits it unless a Filament Track Switch is installed. Without a
  6741. switch the firmware derives the hotend from the AMS's own
  6742. extruder binding and an explicit value is redundant; *with* one
  6743. every AMS reports 0xE and is bound to a switch inlet instead, so
  6744. the firmware has nothing to derive from and the load silently
  6745. does nothing until we name the hotend.
  6746. Returns:
  6747. True if command was sent, False otherwise
  6748. """
  6749. if not self._client or not self.state.connected:
  6750. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  6751. return False
  6752. # Build the ams_change_filament command. Encoding differs by target type:
  6753. # - AMS slots (0..15): slot_id is the local slot, curr/tar_temp = -1.
  6754. # - External spool (tray_id=254): legacy capture from a single-extruder
  6755. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  6756. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  6757. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  6758. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  6759. self._sequence_id += 1
  6760. wire_target = tray_id
  6761. if tray_id == 255:
  6762. ams_id = 255
  6763. slot_id = 0 # extruder index for the right nozzle
  6764. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  6765. if right_temp < 180:
  6766. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  6767. curr_temp = right_temp
  6768. tar_temp = right_temp
  6769. elif tray_id == 254:
  6770. ams_id = 255
  6771. slot_id = 254
  6772. curr_temp = -1
  6773. tar_temp = -1
  6774. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  6775. # A2L AMS-Lite: physical unit 16 + local slot confirmed; the wire
  6776. # `target` (physical global 64-67) is extrapolated (no A2L load
  6777. # capture yet). See a2l_lite_wire_ids.
  6778. ams_id, slot_id, wire_target = _a2l
  6779. curr_temp = -1
  6780. tar_temp = -1
  6781. else:
  6782. ams_id = tray_id // 4
  6783. slot_id = tray_id % 4
  6784. curr_temp = -1
  6785. tar_temp = -1
  6786. command = {
  6787. "print": {
  6788. "command": "ams_change_filament",
  6789. "sequence_id": str(self._sequence_id),
  6790. "ams_id": ams_id,
  6791. "slot_id": slot_id,
  6792. "target": wire_target,
  6793. "curr_temp": curr_temp,
  6794. "tar_temp": tar_temp,
  6795. }
  6796. }
  6797. if extruder_id is not None:
  6798. command["print"]["extruder_id"] = int(extruder_id)
  6799. command_json = json.dumps(command)
  6800. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  6801. self._client.publish(self.topic_publish, command_json, qos=1)
  6802. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  6803. # Track this load request for H2D dual-nozzle disambiguation
  6804. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  6805. self._last_load_tray_id = tray_id
  6806. self.state.pending_tray_target = tray_id
  6807. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  6808. return True
  6809. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  6810. """Unload filament, optionally naming the slot to unload.
  6811. Args:
  6812. tray_id: Global tray ID of the slot being unloaded. When given, the
  6813. command is addressed to that slot's AMS and is only sent if an
  6814. extruder is actually fed from it — BambuStudio does the same
  6815. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  6816. nothing when none matches). When omitted, the pre-existing
  6817. behaviour is kept: unload whatever ``tray_now`` names.
  6818. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  6819. machine with both hotends loaded it names only one of them and an
  6820. unaddressed unload picks that one regardless of which slot the operator
  6821. clicked. Passing the slot is what makes the two hotends distinguishable.
  6822. Returns:
  6823. True if command was sent, False otherwise
  6824. """
  6825. if not self._client or not self.state.connected:
  6826. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  6827. return False
  6828. # Get the currently loaded tray info
  6829. tray_now = self.state.tray_now
  6830. source_tray = tray_now if tray_id is None else tray_id
  6831. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  6832. # Determine source ams_id for the unload command
  6833. if source_tray == 255 or source_tray == 254:
  6834. ams_id = 255 # No filament or external spool
  6835. elif (_a2l := a2l_lite_wire_ids(source_tray // 4, source_tray)) is not None:
  6836. ams_id = _a2l[0] # A2L AMS-Lite: normalised 6 -> physical 16
  6837. else:
  6838. ams_id = source_tray // 4 # Source AMS
  6839. # Refuse an addressed unload of a slot no hotend is holding — but only on
  6840. # a printer that has more than one hotend, which is the only case the
  6841. # check exists for. With one hotend there is nothing to disambiguate:
  6842. # tray_now already names the loaded slot exactly, and running the check
  6843. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  6844. # very likely does, but single-nozzle machines do report the block —
  6845. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  6846. # an X1C on the maintainer's own network sends `device.extruder` — and
  6847. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  6848. # would 409 every unload on every X1C, P1S and A1.
  6849. #
  6850. # Gated on the runtime flag rather than on len(extruder_slots), which is
  6851. # rebuilt from each payload's array and would flip the check off for any
  6852. # frame that carried a short one; and deliberately not on
  6853. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  6854. # one single-nozzle machine as dual (#1386) — the false positive there is
  6855. # exactly the case this gate exists to keep out.
  6856. #
  6857. # The external spool is excluded for a different reason: 254/255 are not
  6858. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  6859. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  6860. local_slot = _a2l[1] if (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None else tray_id % 4
  6861. holder = next(
  6862. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  6863. None,
  6864. )
  6865. if holder is None:
  6866. logger.info(
  6867. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  6868. self.serial_number,
  6869. ams_id,
  6870. local_slot,
  6871. )
  6872. return False
  6873. logger.info(
  6874. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  6875. )
  6876. # Command format from BambuStudio traffic capture:
  6877. # - No extruder_id field
  6878. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  6879. # - slot_id=255 and target=255 for unload
  6880. # Get current nozzle temperature for the unload command
  6881. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  6882. if nozzle_temp < 180:
  6883. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  6884. self._sequence_id += 1
  6885. command = {
  6886. "print": {
  6887. "command": "ams_change_filament",
  6888. "sequence_id": str(self._sequence_id),
  6889. "ams_id": ams_id,
  6890. "slot_id": 255, # 255 = unload marker
  6891. "target": 255, # 255 = unload destination
  6892. "curr_temp": nozzle_temp,
  6893. "tar_temp": nozzle_temp,
  6894. }
  6895. }
  6896. command_json = json.dumps(command)
  6897. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  6898. self._client.publish(self.topic_publish, command_json, qos=1)
  6899. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  6900. # Clear tracked load request since we're unloading
  6901. self._last_load_tray_id = None
  6902. self.state.pending_tray_target = None
  6903. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  6904. return True
  6905. def ams_control(self, action: str) -> bool:
  6906. """Control AMS operations.
  6907. Args:
  6908. action: "resume", "reset", or "pause"
  6909. Returns:
  6910. True if command was sent, False otherwise
  6911. """
  6912. if not self._client or not self.state.connected:
  6913. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  6914. return False
  6915. if action not in ("resume", "reset", "pause"):
  6916. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  6917. return False
  6918. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  6919. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6920. logger.info("[%s] AMS control: %s", self.serial_number, action)
  6921. return True
  6922. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  6923. """Trigger RFID re-read for a specific AMS tray.
  6924. Args:
  6925. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  6926. tray_id: Tray ID within the AMS (0-3)
  6927. Returns:
  6928. Tuple of (success, message)
  6929. """
  6930. if not self._client or not self.state.connected:
  6931. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  6932. return False, "Printer not connected"
  6933. # Check if filament is currently loaded (tray_now != 255)
  6934. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  6935. tray_now = self.state.tray_now
  6936. if tray_now != 255:
  6937. # Decode which tray is loaded for the message
  6938. if tray_now == 254:
  6939. loaded_tray = "external spool"
  6940. elif tray_now >= 0 and tray_now < 128:
  6941. loaded_ams = tray_now // 4
  6942. loaded_slot = tray_now % 4
  6943. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  6944. else:
  6945. loaded_tray = f"tray {tray_now}"
  6946. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  6947. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  6948. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  6949. wire_ams_id, wire_slot_id = ams_id, tray_id
  6950. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  6951. wire_ams_id, wire_slot_id, _ = _a2l
  6952. # Use ams_get_rfid command to trigger RFID re-read
  6953. # This command is used by Bambu Studio to re-read the RFID tag
  6954. command = {
  6955. "print": {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id, "sequence_id": "0"}
  6956. }
  6957. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6958. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  6959. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  6960. def ams_set_filament_setting(
  6961. self,
  6962. ams_id: int,
  6963. tray_id: int,
  6964. tray_info_idx: str,
  6965. tray_type: str,
  6966. tray_sub_brands: str,
  6967. tray_color: str,
  6968. nozzle_temp_min: int,
  6969. nozzle_temp_max: int,
  6970. setting_id: str = "",
  6971. ) -> bool:
  6972. """Set AMS tray filament settings (type, color, temperature).
  6973. Note: K value is set separately via extrusion_cali_sel command.
  6974. Args:
  6975. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  6976. tray_id: Tray ID within the AMS (0-3)
  6977. tray_info_idx: Filament ID short format (e.g., "GFL05")
  6978. tray_type: Filament type (e.g., "PLA", "PETG")
  6979. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  6980. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  6981. nozzle_temp_min: Minimum nozzle temperature
  6982. nozzle_temp_max: Maximum nozzle temperature
  6983. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  6984. Returns:
  6985. True if command was sent, False otherwise
  6986. """
  6987. if not self._client or not self.state.connected:
  6988. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  6989. return False
  6990. # Calculate mqtt IDs based on AMS type.
  6991. # External-spool convention verified against a BambuStudio→X1C packet capture
  6992. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  6993. # *global* tray index in `tray_id`, not a local position within the virtual
  6994. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  6995. # is what the original code was matching — but the request and response
  6996. # use different semantics for that field. Sending `tray_id: 0` is what
  6997. # the P1S in #1279 rejected with `result: "fail"`.
  6998. if ams_id == 255:
  6999. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7000. if len(vt_tray) > 1:
  7001. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7002. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7003. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7004. # captured Studio→H2D exchange confirms the correct value.
  7005. mqtt_ams_id = 254 + tray_id
  7006. mqtt_tray_id = 0
  7007. else:
  7008. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7009. mqtt_ams_id = 255
  7010. mqtt_tray_id = 254
  7011. slot_id = 0
  7012. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7013. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7014. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7015. mqtt_ams_id, slot_id, _ = _a2l
  7016. mqtt_tray_id = slot_id
  7017. elif ams_id <= 3:
  7018. mqtt_ams_id = ams_id
  7019. mqtt_tray_id = tray_id
  7020. slot_id = tray_id
  7021. else:
  7022. # AMS-HT: single tray per unit
  7023. mqtt_ams_id = ams_id
  7024. mqtt_tray_id = tray_id
  7025. slot_id = 0
  7026. command = {
  7027. "print": {
  7028. "command": "ams_filament_setting",
  7029. "ams_id": mqtt_ams_id,
  7030. "tray_id": mqtt_tray_id,
  7031. "slot_id": slot_id,
  7032. "tray_info_idx": tray_info_idx,
  7033. "tray_type": tray_type,
  7034. "tray_sub_brands": tray_sub_brands,
  7035. "tray_color": tray_color,
  7036. "nozzle_temp_min": nozzle_temp_min,
  7037. "nozzle_temp_max": nozzle_temp_max,
  7038. "sequence_id": "0",
  7039. }
  7040. }
  7041. # Include setting_id if provided (helps slicer show correct profile)
  7042. if setting_id:
  7043. command["print"]["setting_id"] = setting_id
  7044. command_json = json.dumps(command)
  7045. logger.info(
  7046. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  7047. )
  7048. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  7049. self._client.publish(self.topic_publish, command_json, qos=1)
  7050. self._last_ams_cmd_time = time.monotonic()
  7051. return True
  7052. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  7053. """Reset an AMS slot to empty/unconfigured state.
  7054. Args:
  7055. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7056. tray_id: Tray ID within the AMS (0-3)
  7057. Returns:
  7058. True if command was sent, False otherwise
  7059. """
  7060. if not self._client or not self.state.connected:
  7061. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  7062. return False
  7063. # Calculate mqtt IDs based on AMS type — same convention as
  7064. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  7065. if ams_id == 255:
  7066. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7067. if len(vt_tray) > 1:
  7068. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7069. mqtt_ams_id = 254 + tray_id
  7070. mqtt_tray_id = 0
  7071. else:
  7072. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7073. mqtt_ams_id = 255
  7074. mqtt_tray_id = 254
  7075. slot_id = 0
  7076. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7077. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  7078. mqtt_ams_id, slot_id, _ = _a2l
  7079. mqtt_tray_id = slot_id
  7080. elif ams_id <= 3:
  7081. mqtt_ams_id = ams_id
  7082. mqtt_tray_id = tray_id
  7083. slot_id = tray_id
  7084. else:
  7085. # AMS-HT: single tray per unit
  7086. mqtt_ams_id = ams_id
  7087. mqtt_tray_id = tray_id
  7088. slot_id = 0
  7089. command = {
  7090. "print": {
  7091. "command": "ams_filament_setting",
  7092. "ams_id": mqtt_ams_id,
  7093. "tray_id": mqtt_tray_id,
  7094. "slot_id": slot_id,
  7095. "tray_info_idx": "",
  7096. "tray_type": "",
  7097. "tray_sub_brands": "",
  7098. "tray_color": "00000000",
  7099. "nozzle_temp_min": 0,
  7100. "nozzle_temp_max": 0,
  7101. "sequence_id": "0",
  7102. }
  7103. }
  7104. command_json = json.dumps(command)
  7105. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  7106. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  7107. self._client.publish(self.topic_publish, command_json, qos=1)
  7108. self._last_ams_cmd_time = time.monotonic()
  7109. return True
  7110. def extrusion_cali_sel(
  7111. self,
  7112. ams_id: int,
  7113. tray_id: int,
  7114. cali_idx: int,
  7115. filament_id: str,
  7116. nozzle_diameter: str = "0.4",
  7117. ) -> bool:
  7118. """Set calibration profile (K value) for an AMS slot.
  7119. This command selects a K profile from the printer's calibration list.
  7120. Use cali_idx=-1 to use the default K value (0.020).
  7121. Note: Do NOT send setting_id in this command — BambuStudio never includes
  7122. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  7123. Args:
  7124. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7125. tray_id: Tray ID within the AMS (0-3)
  7126. cali_idx: Calibration profile index (-1 for default)
  7127. filament_id: Filament preset ID (same as tray_info_idx)
  7128. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7129. Returns:
  7130. True if command was sent, False otherwise
  7131. """
  7132. if not self._client or not self.state.connected:
  7133. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  7134. return False
  7135. # Calculate mqtt IDs based on AMS type.
  7136. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  7137. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  7138. if ams_id == 255:
  7139. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  7140. # ams_filament_setting which uses LOCAL tray_id=0).
  7141. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7142. if len(vt_tray) > 1:
  7143. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7144. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  7145. mqtt_ams_id = 254 + tray_id
  7146. mqtt_tray_id = 254 + tray_id
  7147. else:
  7148. # Single external slot (X1C, P1S, A1): global tray_id=254
  7149. mqtt_ams_id = 254
  7150. mqtt_tray_id = 254
  7151. slot_id = 0
  7152. elif ams_id <= 3:
  7153. mqtt_ams_id = ams_id
  7154. mqtt_tray_id = ams_id * 4 + tray_id
  7155. slot_id = tray_id
  7156. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7157. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  7158. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  7159. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  7160. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  7161. elif ams_id >= 128 and ams_id <= 135:
  7162. mqtt_ams_id = ams_id
  7163. mqtt_tray_id = tray_id
  7164. slot_id = 0
  7165. else:
  7166. mqtt_ams_id = ams_id
  7167. mqtt_tray_id = tray_id
  7168. slot_id = 0
  7169. command = {
  7170. "print": {
  7171. "command": "extrusion_cali_sel",
  7172. "cali_idx": cali_idx,
  7173. "filament_id": filament_id,
  7174. "nozzle_diameter": nozzle_diameter,
  7175. "ams_id": mqtt_ams_id,
  7176. "tray_id": mqtt_tray_id,
  7177. "slot_id": slot_id,
  7178. "sequence_id": "0",
  7179. }
  7180. }
  7181. command_json = json.dumps(command)
  7182. logger.info(
  7183. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  7184. )
  7185. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  7186. self._client.publish(self.topic_publish, command_json, qos=1)
  7187. return True
  7188. def extrusion_cali_set(
  7189. self,
  7190. tray_id: int,
  7191. k_value: float,
  7192. nozzle_diameter: str = "0.4",
  7193. nozzle_temp: int = 220,
  7194. filament_id: str = "",
  7195. setting_id: str = "",
  7196. name: str = "",
  7197. cali_idx: int = -1,
  7198. ) -> bool:
  7199. """Directly set K value (pressure advance) for a tray.
  7200. Uses the filaments array format required by current firmware.
  7201. Args:
  7202. tray_id: Global tray ID (ams_id * 4 + slot)
  7203. k_value: Pressure advance K value (e.g., 0.020)
  7204. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7205. nozzle_temp: Nozzle temperature for calibration reference
  7206. filament_id: Filament preset ID (e.g., "GFA02")
  7207. setting_id: Setting ID (e.g., "GFSA02_07")
  7208. name: Profile display name
  7209. cali_idx: Calibration index (-1 for new)
  7210. Returns:
  7211. True if command was sent, False otherwise
  7212. """
  7213. if not self._client or not self.state.connected:
  7214. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  7215. return False
  7216. # Was reusing the previous command's id — harmless while nothing
  7217. # correlated on it, but the printer echoes sequence_id back and the
  7218. # K-profile write path now matches acks by it (#2718).
  7219. self._sequence_id += 1
  7220. nozzle_id = f"HS00-{nozzle_diameter}"
  7221. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  7222. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  7223. # stays 0 (hardcoded, as for every other unit here).
  7224. wire_tray_id = tray_id
  7225. if 0 <= tray_id <= 253 and (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  7226. wire_tray_id = _a2l[2]
  7227. filament_entry = {
  7228. "ams_id": 0,
  7229. "cali_idx": cali_idx,
  7230. "extruder_id": 0,
  7231. "filament_id": filament_id,
  7232. "k_value": f"{k_value:.6f}",
  7233. "n_coef": "1.400000",
  7234. "name": name,
  7235. "nozzle_diameter": nozzle_diameter,
  7236. "nozzle_id": nozzle_id,
  7237. "setting_id": setting_id,
  7238. "tray_id": wire_tray_id,
  7239. }
  7240. command = {
  7241. "print": {
  7242. "command": "extrusion_cali_set",
  7243. "filaments": [filament_entry],
  7244. "nozzle_diameter": nozzle_diameter,
  7245. "sequence_id": str(self._sequence_id),
  7246. }
  7247. }
  7248. command_json = json.dumps(command)
  7249. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  7250. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  7251. self._client.publish(self.topic_publish, command_json, qos=1)
  7252. return True
  7253. def set_timelapse(self, enable: bool) -> bool:
  7254. """Enable or disable timelapse recording.
  7255. Args:
  7256. enable: True to enable, False to disable
  7257. Returns:
  7258. True if command was sent, False otherwise
  7259. """
  7260. if not self._client or not self.state.connected:
  7261. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  7262. return False
  7263. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  7264. # First send the timelapse setting
  7265. timelapse_cmd = {
  7266. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  7267. }
  7268. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  7269. # Request status update
  7270. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7271. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  7272. return True
  7273. def set_liveview(self, enable: bool) -> bool:
  7274. """Enable or disable live view / camera streaming.
  7275. Args:
  7276. enable: True to enable, False to disable
  7277. Returns:
  7278. True if command was sent, False otherwise
  7279. """
  7280. if not self._client or not self.state.connected:
  7281. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  7282. return False
  7283. command = {
  7284. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  7285. }
  7286. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7287. # Request status update
  7288. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  7289. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  7290. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  7291. return True
  7292. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  7293. """Dispatch the user's choice from the HMS-error modal as a printer command.
  7294. Args:
  7295. print_error: Canonical hex identifier for the fault — 8 chars for the
  7296. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  7297. (HMSError.full_code). Carried through unchanged from the route.
  7298. Converted to its DECIMAL string form for the `ignore` /
  7299. `idle_ignore` commands' `err` field, which is what the firmware
  7300. actually compares against the active fault. The pre-#1869
  7301. hex-string `err` was silently rejected because the firmware was
  7302. being asked to match `"05008051"` against int 0x05008051
  7303. (= 83918929 decimal) — see BambuStudio's
  7304. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  7305. `std::to_string(int m_error_code)`.
  7306. action: One of HMSAction's string values.
  7307. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  7308. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  7309. shapes; empty string is the no-job-id sentinel.
  7310. Returns False when the MQTT client is offline or when `action` is unknown
  7311. so the route surfaces it as a 4xx rather than a silent no-op.
  7312. """
  7313. if not self._client or not self.state.connected:
  7314. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  7315. return False
  7316. # Always re-push the full state after a command so the modal's underlying
  7317. # status query reflects the new error list (or absence) on the next tick.
  7318. def publish(payload: dict):
  7319. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  7320. self._client.publish(
  7321. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  7322. )
  7323. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  7324. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  7325. # every command_hms_* call). Our route hands us the hex string —
  7326. # convert. Falls back to the raw input if it's not parseable so the
  7327. # firmware can reject it and the route can surface 502 instead of us
  7328. # raising ValueError mid-dispatch.
  7329. try:
  7330. err_decimal = str(int(print_error, 16))
  7331. except ValueError:
  7332. err_decimal = print_error
  7333. def hms_resume():
  7334. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  7335. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  7336. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  7337. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  7338. # shape historically because it works, and changing it without a
  7339. # field test risks regressing a path that the user has confirmed.
  7340. publish(
  7341. {
  7342. "print": {
  7343. "command": "resume",
  7344. "param": "",
  7345. "sequence_id": "0",
  7346. }
  7347. }
  7348. )
  7349. def hms_stop():
  7350. # Same as hms_resume — plain shape, confirmed working by the user
  7351. # for "Stop Printing".
  7352. publish(
  7353. {
  7354. "print": {
  7355. "command": "stop",
  7356. "param": "",
  7357. "sequence_id": "0",
  7358. }
  7359. }
  7360. )
  7361. def hms_ignore_command():
  7362. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  7363. # what the "Ignore this and Resume" button actually publishes.
  7364. # Distinct from `idle_ignore`: this command has the firmware
  7365. # suppress the next re-check of the named fault AND resume the
  7366. # paused print in a single operation. The previous Bambuddy code
  7367. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  7368. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  7369. # the problem, re-check normally" so the firmware re-detected the
  7370. # wrong plate and re-paused with the same code (#1869).
  7371. #
  7372. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  7373. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  7374. # variant of "don't remind next time" lives on `idle_ignore`'s
  7375. # type=1, not as a separate ignore shape.
  7376. publish(
  7377. {
  7378. "print": {
  7379. "command": "ignore",
  7380. "err": err_decimal,
  7381. "param": "reserve",
  7382. "job_id": job_id or "",
  7383. "sequence_id": "0",
  7384. }
  7385. }
  7386. )
  7387. def hms_idle_ignore(persistent: bool = False):
  7388. # `idle_ignore` is BambuStudio's "dismiss this warning without
  7389. # resuming" command for non-pause warnings — what
  7390. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  7391. # type=0 dismisses once, type=1 suppresses the same warning
  7392. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  7393. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  7394. # NOT via the resume-bearing `ignore` command.
  7395. publish(
  7396. {
  7397. "print": {
  7398. "command": "idle_ignore",
  7399. "err": err_decimal,
  7400. "type": 1 if persistent else 0,
  7401. "sequence_id": "0",
  7402. }
  7403. }
  7404. )
  7405. def ams_control(param: str):
  7406. publish(
  7407. {
  7408. "print": {
  7409. "command": "ams_control",
  7410. "param": param,
  7411. "sequence_id": "0",
  7412. }
  7413. }
  7414. )
  7415. def clean_print_error():
  7416. # Matches the existing `clear_hms_errors` shape — Bambu does not
  7417. # expect `print_error` in the body; the command clears whatever
  7418. # error dialog is currently active on the printer.
  7419. publish(
  7420. {
  7421. "print": {
  7422. "command": "clean_print_error",
  7423. "sequence_id": "0",
  7424. }
  7425. }
  7426. )
  7427. def uiop_close():
  7428. # `err` is the 8-char hex short code (already a string from the
  7429. # frontend), uppercased for consistency with how BambuStudio sends it.
  7430. publish(
  7431. {
  7432. "system": {
  7433. "command": "uiop",
  7434. "name": "print_error",
  7435. "action": "close",
  7436. "source": 1,
  7437. "type": "dialog",
  7438. "err": print_error.upper(),
  7439. "sequence_id": "0",
  7440. }
  7441. }
  7442. )
  7443. match action:
  7444. case (
  7445. HMSAction.RESUME_PRINTING
  7446. | HMSAction.RESUME_PRINTING_DEFECTS
  7447. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  7448. | HMSAction.PROBLEM_SOLVED_RESUME
  7449. | HMSAction.FILAMENT_LOAD_RESUME
  7450. | HMSAction.PROCEED
  7451. ):
  7452. hms_resume()
  7453. case HMSAction.STOP_PRINTING:
  7454. hms_stop()
  7455. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  7456. # All three buttons map to BambuStudio's `command_hms_ignore`
  7457. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  7458. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  7459. # responsibility — the wire shape is identical.
  7460. hms_ignore_command()
  7461. case HMSAction.NO_REMINDER_NEXT_TIME:
  7462. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  7463. # `command_hms_idle_ignore` with type=0
  7464. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  7465. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  7466. # dismisses the dialog.
  7467. hms_idle_ignore(persistent=False)
  7468. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  7469. ams_control("done")
  7470. case (
  7471. HMSAction.RETRY_FILAMENT_EXTRUDED
  7472. | HMSAction.CONTINUE
  7473. | HMSAction.RETRY_PROBLEM_SOLVED
  7474. | HMSAction.DBL_CHECK_RETRY
  7475. ):
  7476. ams_control("resume")
  7477. case HMSAction.ABORT:
  7478. ams_control("abort")
  7479. case HMSAction.OK_BUTTON:
  7480. clean_print_error()
  7481. case HMSAction.DBL_CHECK_OK:
  7482. clean_print_error()
  7483. uiop_close()
  7484. case HMSAction.DBL_CHECK_RESUME:
  7485. # Plain resume — not HMS-aware, no err/job_id.
  7486. publish(
  7487. {
  7488. "print": {
  7489. "command": "resume",
  7490. "param": "",
  7491. "sequence_id": "0",
  7492. }
  7493. }
  7494. )
  7495. case HMSAction.REFRESH_NOZZLE:
  7496. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  7497. case HMSAction.TURN_OFF_FIRE_ALARM:
  7498. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  7499. case HMSAction.STOP_DRYING:
  7500. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  7501. case HMSAction.DISABLE_PURIFICATION:
  7502. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  7503. case (
  7504. HMSAction.CHECK_ASSISTANT
  7505. | HMSAction.JUMP_TO_LIVEVIEW
  7506. | HMSAction.OK_JUMP_RACK
  7507. | HMSAction.REMOVE_CLOSE_BTN
  7508. | HMSAction.LOAD_VIRTUAL_TRAY
  7509. | HMSAction.CANCLE
  7510. | HMSAction.DBL_CHECK_CANCEL
  7511. ):
  7512. # UI-only actions — the printer's own screen handles these; the
  7513. # modal still surfaces them so the user has parity with Studio.
  7514. pass
  7515. case _:
  7516. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  7517. return False
  7518. return True