bambu_mqtt.py 233 KB

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