bambu_mqtt.py 232 KB

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