bambu_mqtt.py 390 KB

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