bambu_mqtt.py 230 KB

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