bambu_mqtt.py 253 KB

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