bambu_mqtt.py 388 KB

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