bambu_mqtt.py 257 KB

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