bambu_mqtt.py 442 KB

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