bambu_mqtt.py 274 KB

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