bambu_mqtt.py 296 KB

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