bambu_mqtt.py 324 KB

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