bambu_mqtt.py 250 KB

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