bambu_mqtt.py 418 KB

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