bambu_mqtt.py 287 KB

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