bambu_mqtt.py 289 KB

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