bambu_mqtt.py 439 KB

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