prod2u_gui.py 212 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430
  1. #!/usr/bin/env python3
  2. """Shared interface for the two Prod2U products with full SET/GET command generation,
  3. detailed field decoding, universal frame inspection, and optional serial communication.
  4. """
  5. from __future__ import annotations
  6. from pathlib import Path
  7. import base64, datetime, json, math, os, queue, re, struct, subprocess, sys, threading, time, zipfile, zlib
  8. from typing import Any
  9. ROOT = Path(__file__).resolve().parents[1]
  10. sys.path.insert(0, str(Path(__file__).resolve().parent / "_vendor"))
  11. from hth_protocol import (
  12. FrameType,
  13. NackReason,
  14. MotorAction,
  15. DoneReason,
  16. Type,
  17. Status,
  18. encode_frame,
  19. decode_frame,
  20. crc16_ccitt_false,
  21. PREAMBLE,
  22. )
  23. from prod2u_status import state_6400, mrdimm_state, decode_temperature, diagnostic_6400_v2, diagnostic_mrdimm
  24. try:
  25. from tools.stream_receiver import StreamReceiver, TransactionTracker, SessionDiskLogger
  26. except ImportError:
  27. from stream_receiver import StreamReceiver, TransactionTracker, SessionDiskLogger
  28. # Optional pyserial for hardware communication
  29. try:
  30. import serial
  31. import serial.tools.list_ports
  32. HAVE_SERIAL = True
  33. except ImportError:
  34. HAVE_SERIAL = False
  35. ENDPOINTS = {"nothing": 0, "push_down": 1, "push_up": 2, "stop_clear": 255}
  36. HOST_BAUDRATES = (921600, 460800, 230400, 115200)
  37. FAN_GROUP_NAMES = {"Front": "新风 / 进风 (Front)", "Rear": "排风 / 出风 (Rear)"}
  38. PWM_FREQUENCY_HZ = 20
  39. PWM_PERIOD_MS = 50.0
  40. SOFTWARE_VERSION = (
  41. (ROOT / "VERSION").read_text(encoding="utf-8").strip()
  42. if (ROOT / "VERSION").is_file()
  43. else "3.1.0"
  44. )
  45. FRAME_TYPE_NAMES = {
  46. 0x01: "SET_ALL (下发全量控制)",
  47. 0x02: "GET_ALL (查询当前状态)",
  48. 0x03: "HEARTBEAT (心跳测试 Ping)",
  49. 0x51: "BEACON (单板自发心跳信标)",
  50. 0x52: "DIAGNOSTIC (温度采集诊断)",
  51. 0x81: "SET_ACK (设置确认已应用)",
  52. 0x82: "GET_ACK (查询确认已受理)",
  53. 0x83: "HEARTBEAT_ACK (主动心跳应答 Pong)",
  54. 0x42: "GET_DATA (全量状态数据)",
  55. 0x50: "MOTOR_DONE (电机动作完成事件)",
  56. 0xC0: "NACK (请求被拒绝)",
  57. }
  58. NACK_REASON_NAMES = {
  59. 0x01: "UNSUPPORTED (不支持的请求类型)",
  60. 0x02: "BAD_LENGTH (报文长度不匹配)",
  61. 0x03: "BAD_VALUE (参数值越界或非法)",
  62. 0x04: "QUEUE_FULL (电机队列已满)",
  63. 0x05: "BUSY (单板正忙)",
  64. }
  65. DONE_REASON_NAMES = {
  66. 0x00: "STEPS_DONE (脉冲步数正常发射完成)",
  67. 0x01: "LOWER_LIMIT (运动触发下限位阻断)",
  68. 0x02: "UPPER_LIMIT (运动触发上限位阻断)",
  69. 0x03: "BOTH_LIMITS (双向限位同时异常触发)",
  70. }
  71. # The PCB proves Axis0..11 <-> M1..M12. Mechanical front/rear/top roles
  72. # need a verified harness map and must not be invented by the GUI.
  73. MRDIMM_AXIS_NAMES = [f"Axis {index} (M{index + 1})" for index in range(12)]
  74. def parse_hex(text: str) -> bytes:
  75. value = re.sub(r"[\s:_\-]+", "", text)
  76. if not value or len(value) % 2 or not re.fullmatch(r"[0-9a-fA-F]+", value):
  77. raise ValueError("HEX 必须是偶数个十六进制字符(支持空格、冒号、连字符分隔)")
  78. return bytes.fromhex(value)
  79. def frame_hex(data: bytes) -> str:
  80. return data.hex(" ").upper()
  81. def status_rows(state: dict[str, Any], groups: list[tuple[str, int, int]]) -> tuple[list, list]:
  82. outputs = []
  83. temperatures = []
  84. for group, count, _ in groups:
  85. name = group.lower()
  86. duties = state.get(name, [])
  87. for n in range(count):
  88. val = duties[n] if n < len(duties) else 0
  89. outputs.append((f"{group}{n}", val))
  90. for name in ("bmc", "ct"):
  91. sensor = state.get(name, {})
  92. temps = sensor.get("temperature_c", [])
  93. for n, temp in enumerate(temps):
  94. condition = "无效" if temp is None else "有效"
  95. temperatures.append((f"{name.upper()}{n}", "未知" if temp is None else f"{temp} °C", condition))
  96. return outputs, temperatures
  97. def integer(value: Any, low: int, high: int, name: str) -> int:
  98. if isinstance(value, bool) or not isinstance(value, (str, int)):
  99. raise ValueError(f"{name} 必须是整数")
  100. try:
  101. n = int(value, 16 if str(value).lower().startswith("0x") else 10) if isinstance(value, str) else value
  102. except ValueError:
  103. raise ValueError(f"{name} 必须是整数")
  104. if not low <= n <= high:
  105. raise ValueError(f"{name} 必须在 {low}..{high}")
  106. return n
  107. class ZipAsset:
  108. def __init__(self, data: bytes):
  109. self._data = data
  110. def read_text(self, encoding: str = "utf-8") -> str:
  111. return self._data.decode(encoding)
  112. def read_bytes(self) -> bytes:
  113. return self._data
  114. def is_file(self) -> bool:
  115. return True
  116. class Model:
  117. def __init__(self, product: str):
  118. if product not in ("6400-front-rear", "mrdimm-chamber", "6400-v2"):
  119. raise ValueError("未知产品: " + product)
  120. self.product = product
  121. self.motor = (product == "mrdimm-chamber")
  122. self.folder = "mrdimm" if self.motor else ("6400-v2" if product == "6400-v2" else "6400")
  123. filename = "snapshot-layout.json" if self.motor else "manual-uart-contract.json"
  124. self.contract = json.loads(self.asset(filename).read_text(encoding="utf-8"))
  125. self.wire = self.contract["control"]["wire"] if self.motor else self.contract["wire"]
  126. self.outputs = self.contract["control"]["outputs"] if self.motor else self.contract["outputs"]
  127. self.board = "FCB V1.2" if self.motor else ("6400V2.0" if product == "6400-v2" else "FCB V1.1")
  128. try:
  129. self.metadata = json.loads(self.asset("gui-build-metadata.json").read_text(encoding="utf-8"))
  130. except (FileNotFoundError, ValueError):
  131. self.metadata = {
  132. "product": product,
  133. "commit": "source preview",
  134. "bitstream_sha256": None,
  135. "contract_sha256": self.contract.get("contract_sha256"),
  136. }
  137. if self.metadata.get("product") not in (None, product):
  138. raise ValueError("GUI 产品入口与嵌入构建信息不匹配")
  139. try:
  140. source_version = self.asset("VERSION").read_text().strip()
  141. except FileNotFoundError:
  142. source_version = "未标记"
  143. self.release_version = self.metadata.get("release_version", source_version)
  144. # The receipt describes the flashed BIT's build rate; the combo changes
  145. # only the PC UART and must match the selected firmware variant.
  146. self.host_baud = int(self.metadata.get("host_baud", 921600))
  147. if self.host_baud not in HOST_BAUDRATES:
  148. raise ValueError("构建信息中的 Host 波特率不受支持")
  149. def output_label(self, group: str, index: int) -> str:
  150. if self.product == "6400-v2" and group == "SSR":
  151. return ("SSR1 腔体1", "SSR2 腔体2+3 共用", "SSR4 腔体4")[index]
  152. if self.product == "6400-v2" and group in FAN_GROUP_NAMES:
  153. role = "新风/进风" if group == "Front" else "排风/出风"
  154. return f"腔室{index + 1} {role} ({group}{index})"
  155. return f"{group}{index}"
  156. def group_label(self, group: str) -> str:
  157. if self.product == "6400-v2":
  158. if group == "SSR":
  159. return "加热布 SSR(20 Hz,50 ms 周期,0..100%,SSR2 由腔体2+3共用)"
  160. return FAN_GROUP_NAMES.get(group, group)
  161. return group
  162. def asset(self, name: str) -> Any:
  163. if hasattr(sys, "_MEIPASS"):
  164. for root in (Path(sys._MEIPASS), Path(sys._MEIPASS) / "generated" / self.folder):
  165. if (root / name).is_file():
  166. return root / name
  167. for parent in Path(__file__).resolve().parents:
  168. if parent.is_file() and zipfile.is_zipfile(parent):
  169. with zipfile.ZipFile(parent) as z:
  170. preferred = f"generated/{self.folder}/{name}"
  171. for member in (preferred, name):
  172. if member in z.namelist():
  173. return ZipAsset(z.read(member))
  174. roots = [ROOT / "generated" / self.folder, ROOT / "contracts", ROOT / "tools", ROOT]
  175. for root in roots:
  176. if (root / name).is_file():
  177. return root / name
  178. raise FileNotFoundError(f"GUI asset missing: {name}")
  179. def groups(self) -> list[tuple[str, int, int]]:
  180. if self.motor:
  181. return [("FAN", 4, 20), ("PTC", 4, 0)]
  182. return [
  183. ("PTC", self.outputs["ptc_count"], self.outputs["default_ptc_percent"]),
  184. ("Front", self.outputs["front_fan_count"], self.outputs["default_front_percent"]),
  185. ("Rear", self.outputs["rear_fan_count"], self.outputs["default_rear_percent"]),
  186. ] + ([("SSR", self.outputs["ssr_count"], self.outputs["default_ssr_percent"])]
  187. if self.product == "6400-v2" else [])
  188. def set_all(
  189. self,
  190. values: list[Any],
  191. motor_slots: list[dict[str, Any]] | None = None,
  192. buzzer: int | bool = 0,
  193. ) -> bytes:
  194. expected_duties = sum(n for _, n, _ in self.groups())
  195. if len(values) != expected_duties:
  196. raise ValueError(f"需要 {expected_duties} 个输出值")
  197. duty_bytes = bytes(integer(v, 0, 100, "占空比") for v in values)
  198. buzzer_val = 1 if buzzer is True else (0 if buzzer is False else integer(buzzer, 0, 1, "蜂鸣器控制"))
  199. if not self.motor:
  200. if self.product == "6400-v2":
  201. return encode_frame(FrameType.SET_ALL, duty_bytes + bytes((buzzer_val,)))
  202. return encode_frame(FrameType.SET_ALL, duty_bytes)
  203. # MRDIMM v3.1.0: 4 FAN + 4 PTC + 12 axis slots (5 bytes each) + 1 buzzer byte = 69 bytes
  204. slots_payload = bytearray(60)
  205. if motor_slots:
  206. if len(motor_slots) > 12:
  207. raise ValueError("最多 12 个电机轴")
  208. for i, slot in enumerate(motor_slots):
  209. action = integer(slot.get("action", 0), 0, 255, f"轴{i}动作")
  210. steps = integer(slot.get("steps", 0), 0, 65535, f"轴{i}步数")
  211. half = integer(slot.get("half_period_us", 0), 0, 65535, f"轴{i}半周期")
  212. if action in (1, 2) and (steps == 0 or half == 0):
  213. raise ValueError(f"轴{i} PUSH 步数与半周期不能为0")
  214. slots_payload[i * 5] = action
  215. slots_payload[i * 5 + 1 : i * 5 + 3] = steps.to_bytes(2, "little")
  216. slots_payload[i * 5 + 3 : i * 5 + 5] = half.to_bytes(2, "little")
  217. return encode_frame(FrameType.SET_ALL, duty_bytes + bytes(slots_payload) + bytes((buzzer_val,)))
  218. def heartbeat(self, nonce: bytes | None = None) -> bytes:
  219. """Generate HEARTBEAT request frame. If nonce provided, payload is 4-byte nonce."""
  220. if nonce is not None:
  221. return encode_frame(FrameType.HEARTBEAT, nonce)
  222. return encode_frame(FrameType.HEARTBEAT)
  223. def get_all(self) -> bytes:
  224. """Generate golden GET_ALL request frame (A5 5A 02 00 6D 7B)."""
  225. return encode_frame(FrameType.GET_ALL)
  226. def checked_request(self, frame: bytes) -> Any:
  227. parsed = decode_frame(frame)
  228. if not parsed.crc_ok:
  229. raise ValueError("CRC 校验失败")
  230. allowed = {FrameType.SET_ALL, FrameType.GET_ALL, FrameType.HEARTBEAT}
  231. if parsed.frame_type not in allowed:
  232. raise ValueError("此产品不支持该请求类型;响应请在状态页解析")
  233. if parsed.frame_type == FrameType.SET_ALL:
  234. if self.motor:
  235. valid_lens = (68, 69)
  236. elif self.product == "6400-v2":
  237. valid_lens = (35, 36)
  238. else:
  239. valid_lens = (sum(count for _, count, _ in self.groups()),)
  240. if len(parsed.payload) not in valid_lens:
  241. raise ValueError(f"此产品 SET_ALL 载荷必须为 {valid_lens} 字节;请使用匹配版本的 GUI 和固件")
  242. return parsed
  243. def state(self, payload: bytes) -> dict[str, Any]:
  244. if self.motor:
  245. return mrdimm_state(payload, self.contract)
  246. valid_lens = (86, 88) if self.product == "6400-v2" else (83,)
  247. if len(payload) not in valid_lens:
  248. raise ValueError(f"{self.product} GET_DATA 载荷必须为 {valid_lens} 字节;请使用匹配版本的 GUI 和固件")
  249. return state_6400(payload, self.contract)
  250. def parse(self, data: bytes, raw_status: bool = False) -> list[dict[str, Any]]:
  251. if raw_status:
  252. return [{"kind": "status", "state": self.state(data)}]
  253. result = []
  254. offset = 0
  255. while offset < len(data):
  256. if data[offset : offset + 2] != PREAMBLE:
  257. raise ValueError("报文头不完整或未找到 A5 5A 同步头")
  258. if len(data) - offset < 6:
  259. raise ValueError("报文长度不足最小帧长 (6 字节)")
  260. frame_type = data[offset + 2]
  261. declared_len = data[offset + 3]
  262. frame_len = declared_len + 6
  263. if offset + frame_len > len(data):
  264. raise ValueError(f"报文数据不完整: 声明载荷 {declared_len} 字节,总长需 {frame_len} 字节,剩余 {len(data) - offset} 字节")
  265. frame_bytes = data[offset : offset + frame_len]
  266. frame = decode_frame(frame_bytes)
  267. offset += frame_len
  268. if not frame.crc_ok:
  269. raise ValueError("CRC 校验失败")
  270. kind = frame.frame_type
  271. p = frame.payload
  272. if kind == FrameType.GET_DATA:
  273. result.append({"kind": "status", "state": self.state(p)})
  274. elif kind == FrameType.DIAGNOSTIC and self.product == "6400-v2":
  275. result.append({"kind": "diagnostic", "diagnostic": diagnostic_6400_v2(p)})
  276. elif kind == FrameType.DIAGNOSTIC and self.motor:
  277. result.append({"kind": "diagnostic", "diagnostic": diagnostic_mrdimm(p)})
  278. elif kind == FrameType.SET_ACK:
  279. result.append({"kind": "ack", "type": "SET_ACK"})
  280. elif kind == FrameType.GET_ACK:
  281. result.append({"kind": "ack", "type": "GET_ACK"})
  282. elif kind == FrameType.HEARTBEAT_ACK:
  283. result.append({"kind": "ack", "type": "HEARTBEAT_ACK"})
  284. elif kind == FrameType.MOTOR_DONE:
  285. if len(p) != 4:
  286. raise ValueError("MOTOR_DONE 长度必须为 4 字节")
  287. axis = p[0]
  288. reason = p[1]
  289. steps = int.from_bytes(p[2:4], "little")
  290. reason_name = DoneReason(reason).name if reason in DoneReason._value2member_map_ else str(reason)
  291. result.append({"kind": "done", "axis": axis, "reason": reason_name, "steps_done": steps})
  292. elif kind == FrameType.NACK:
  293. if len(p) != 2:
  294. raise ValueError("NACK 长度必须为 2 字节")
  295. req = p[0]
  296. reason = p[1]
  297. reason_name = NackReason(reason).name if reason in NackReason._value2member_map_ else str(reason)
  298. result.append({"kind": "nack", "request_type": req, "reason": reason_name})
  299. else:
  300. result.append({"kind": "frame", "type": kind, "payload_hex": frame_hex(p)})
  301. if not result:
  302. raise ValueError("未提供报文")
  303. return result
  304. def explain(self, frame_bytes: bytes) -> dict[str, Any]:
  305. """Provide detailed, human-readable breakdown of any valid or partial frame."""
  306. if len(frame_bytes) < 6:
  307. raise ValueError("报文长度不足 6 字节最小帧长")
  308. if frame_bytes[:2] != PREAMBLE:
  309. raise ValueError("帧同步头必须为 A5 5A")
  310. ftype = frame_bytes[2]
  311. length = frame_bytes[3]
  312. if len(frame_bytes) < length + 6:
  313. raise ValueError(f"帧数据不完整: 声明载荷 {length} 字节,实际仅有 {len(frame_bytes) - 6} 字节")
  314. payload = frame_bytes[4 : 4 + length]
  315. crc_actual = int.from_bytes(frame_bytes[4 + length : 6 + length], "little")
  316. crc_calc = crc16_ccitt_false(frame_bytes[2 : 4 + length])
  317. crc_ok = (crc_actual == crc_calc)
  318. type_name = FRAME_TYPE_NAMES.get(ftype, f"未知类型 0x{ftype:02X}")
  319. explanation: dict[str, Any] = {
  320. "hex": frame_hex(frame_bytes[: 6 + length]),
  321. "preamble": "A5 5A (同步头)",
  322. "type": f"0x{ftype:02X} - {type_name}",
  323. "length": f"{length} 字节 (0x{length:02X})",
  324. "crc_hex": f"0x{frame_bytes[4+length]:02X} 0x{frame_bytes[5+length]:02X} (低字节在先)",
  325. "crc_ok": crc_ok,
  326. "crc_status": "PASS" if crc_ok else f"FAIL (计算值=0x{crc_calc:04X}, 报文值=0x{crc_actual:04X})",
  327. }
  328. # Detailed breakdown per frame type
  329. fields = []
  330. if ftype == 0x01: # SET_ALL
  331. explanation["summary"] = "上位机向单板下发全量输出/电机配置,成功后单板回复 SET_ACK (0x81) 并重载 30s 看门狗"
  332. if not self.motor:
  333. expected = sum(count for _, count, _ in self.groups())
  334. valid_lens = (expected, expected + 1) if self.product == "6400-v2" else (expected,)
  335. if length in valid_lens:
  336. offset = 0
  337. for group, count, _ in self.groups():
  338. for index in range(count):
  339. fields.append(f"{self.output_label(group, index)}: {payload[offset + index]} %")
  340. offset += count
  341. if self.product == "6400-v2":
  342. buz = payload[35] if length == 36 else 0
  343. fields.append(f"蜂鸣器 (CON146.1/H6): {'开启 (1)' if buz else '关闭 (0)'}")
  344. else:
  345. fields.append(f"警告: {self.product} SET_ALL 载荷长度应为 {valid_lens} 字节,当前为 {length} 字节")
  346. else:
  347. # MRDIMM: 69 bytes (or legacy 68): 4 FAN + 4 PTC + 12 axis slots [+ buzzer]
  348. if length in (68, 69):
  349. for i in range(4):
  350. fields.append(f"FAN{i}: {payload[i]} %")
  351. for i in range(4):
  352. fields.append(f"PTC{i}: {payload[4+i]} %")
  353. for i in range(12):
  354. act = payload[8 + i * 5]
  355. act_str = {0: "NOTHING", 1: "PUSH_DOWN", 2: "PUSH_UP", 255: "STOP_CLEAR"}.get(act, f"0x{act:02X}")
  356. st = int.from_bytes(payload[9 + i * 5 : 11 + i * 5], "little")
  357. hp = int.from_bytes(payload[11 + i * 5 : 13 + i * 5], "little")
  358. speed = f"{500000 / hp:.1f} Hz" if hp > 0 else "N/A"
  359. ax_name = MRDIMM_AXIS_NAMES[i] if i < len(MRDIMM_AXIS_NAMES) else f"Axis{i}"
  360. fields.append(f"{ax_name}: 动作={act_str}, 步数={st}, 半周期={hp} us (频率={speed})")
  361. buz = payload[68] if length == 69 else 0
  362. fields.append(f"蜂鸣器 (CON146.1/H6): {'开启 (1)' if buz else '关闭 (0)'}")
  363. else:
  364. fields.append(f"警告: MRDIMM SET_ALL 载荷长度应为 68 或 69 字节,当前为 {length} 字节")
  365. elif ftype == 0x02: # GET_ALL
  366. explanation["summary"] = "上位机向单板查询当前全量状态与温度;单板先回复 GET_ACK (0x82),紧接着回复 GET_DATA (0x42)"
  367. fields.append("无载荷 (0 字节)")
  368. elif ftype == 0x03: # HEARTBEAT
  369. explanation["summary"] = "上位机向单板发送独立心跳检测请求 (PING),单板立即应答 0x83 并重载看门狗"
  370. if len(payload) == 4:
  371. fields.append(f"Nonce 随机验证码: 0x{payload.hex().upper()} (4 字节)")
  372. else:
  373. fields.append("零载荷心跳探测帧 (0 字节)")
  374. elif ftype == 0x51: # BEACON
  375. explanation["summary"] = "MRDIMM 周期性自发信标 (BEACON 0x51);证明板端发送可达,不喂看门狗,不占用事务请求槽"
  376. fields.append("零载荷自发信标帧 (0 字节)")
  377. elif ftype == 0x52 and self.product == "6400-v2":
  378. diagnostic = diagnostic_6400_v2(payload)
  379. explanation["summary"] = diagnostic_summary(diagnostic)
  380. fields.extend(f"{key}: {value}" for key, value in diagnostic.items())
  381. elif ftype == 0x52 and self.motor:
  382. diagnostic = diagnostic_mrdimm(payload)
  383. explanation["summary"] = diagnostic_summary(diagnostic)
  384. fields.extend(f"{key}: {value}" for key, value in diagnostic.items())
  385. elif ftype == 0x81: # SET_ACK
  386. explanation["summary"] = "单板确认已应用 SET_ALL 配置;30 秒硬件看门狗已成功重载"
  387. fields.append("无载荷 (0 字节)")
  388. elif ftype == 0x82: # GET_ACK
  389. explanation["summary"] = "单板确认已受理 GET_ALL 查询请求,随后立即发送 GET_DATA"
  390. fields.append("无载荷 (0 字节)")
  391. elif ftype == 0x83: # HEARTBEAT_ACK
  392. explanation["summary"] = "单板回复主动心跳应答 (PONG 0x83),重载看门狗"
  393. if len(payload) == 4:
  394. fields.append(f"Nonce 验证码回显: 0x{payload.hex().upper()} (4 字节)")
  395. else:
  396. fields.append("零载荷心跳确认帧 (0 字节)")
  397. elif ftype == 0x42: # GET_DATA
  398. explanation["summary"] = "全量状态、温度与限位;0x42 可为自动遥测,仅 GET_ACK 后的数据完成当前查询"
  399. state = self.state(payload)
  400. if not self.motor:
  401. ptc_duties = state.get("ptc", [])
  402. fields.append(f"PTC 生效占空比 (共 24 路):")
  403. for chunk_idx in range(0, len(ptc_duties), 8):
  404. chunk = ptc_duties[chunk_idx : chunk_idx + 8]
  405. chunk_str = " | ".join(f"PTC{chunk_idx+j:02d}: {val}%" for j, val in enumerate(chunk))
  406. fields.append(f" {chunk_str}")
  407. for group in ("Front", "Rear", "SSR"):
  408. for index, value in enumerate(state.get(group.lower(), [])):
  409. fields.append(f"{self.output_label(group, index)}: {value}%")
  410. if self.product == "6400-v2":
  411. fields.append(f"高温罩开关 (CON165.3/F7): {'按下 (高电平=1)' if state.get('hood_switch') else '未按下/默认 (低电平=0)'}")
  412. fields.append(f"蜂鸣器状态 (CON146.1/H6): {'开启 (1)' if state.get('buzzer') else '关闭 (0)'}")
  413. else:
  414. fields.append(f"FAN 生效占空比 (4路): {state.get('fan', [])}")
  415. fields.append(f"PTC 生效占空比 (4路): {state.get('ptc', [])}")
  416. fields.append(f"下限位掩码 (Lower Limit): 0x{state.get('lower_limit_mask', 0):04X}")
  417. fields.append(f"上限位掩码 (Upper Limit): 0x{state.get('upper_limit_mask', 0):04X}")
  418. fields.append(f"高温罩开关 (CON140.3/L3): {'按下 (高电平=1)' if state.get('hood_switch') else '未按下/默认 (低电平=0)'}")
  419. fields.append(f"蜂鸣器状态 (CON146.1/H6): {'开启 (1)' if state.get('buzzer') else '关闭 (0)'}")
  420. bmc_temps = state.get("bmc", {}).get("temperature_c", [])
  421. ct_temps = state.get("ct", {}).get("temperature_c", [])
  422. fields.append(f"BMC 24通道温度 (°C): {[f'{t}°C' if t is not None else '--(无效/未采样)' for t in bmc_temps]}")
  423. fields.append(f"CT7428 27通道温度 (°C): {[f'{t}°C' if t is not None else '--(无效/未采样)' for t in ct_temps]}")
  424. elif ftype == 0x50: # MOTOR_DONE
  425. axis = payload[0] if len(payload) > 0 else 0
  426. reason = payload[1] if len(payload) > 1 else 0
  427. steps = int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else 0
  428. r_name = DONE_REASON_NAMES.get(reason, f"未知 0x{reason:02X}")
  429. ax_label = MRDIMM_AXIS_NAMES[axis] if axis < len(MRDIMM_AXIS_NAMES) else f"Axis{axis}"
  430. explanation["summary"] = f"MRDIMM 电机 {ax_label} 运动段结束事件: {r_name},实际输出 {steps} 步"
  431. fields.append(f"轴号: {ax_label}")
  432. fields.append(f"完成原因: 0x{reason:02X} - {r_name}")
  433. fields.append(f"实际发射脉冲步数: {steps}")
  434. elif ftype == 0xC0: # NACK
  435. req = payload[0] if len(payload) > 0 else 0
  436. reason = payload[1] if len(payload) > 1 else 0
  437. req_name = FRAME_TYPE_NAMES.get(req, f"0x{req:02X}")
  438. r_name = NACK_REASON_NAMES.get(reason, f"0x{reason:02X}")
  439. explanation["summary"] = f"请求被单板拒绝 (NACK)!原请求: {req_name},拒绝原因: {r_name}"
  440. fields.append(f"原请求类型: 0x{req:02X} ({req_name})")
  441. fields.append(f"拒绝原因码: 0x{reason:02X} ({r_name})")
  442. explanation["fields"] = fields
  443. return explanation
  444. def diagnostic_summary(d: dict[str, Any]) -> str:
  445. if not d["supported"]:
  446. return f"未支持的诊断格式/板型: {d['format']}/{d['board_id']:02X};原始帧已保留"
  447. if d.get("format") == 2:
  448. axes = d.get("active_axes", [])
  449. axes_str = ",".join(f"M{i+1}" for i in axes) if axes else "全部空闲"
  450. flags = "/".join(name for name, active in (
  451. ("看门狗超时", d.get("watchdog_expired")),
  452. ("蜂鸣器开启", d.get("buzzer_on")),
  453. ) if active) or "无"
  454. return (f"MRDIMM 固件 {d['firmware_version']} | 输出有效={int(bool(d.get('duty_bank_valid')))} | "
  455. f"运行中电机: {axes_str} (0x{d.get('motor_active_mask', 0):03X}) | 标志: {flags}")
  456. seen = "已完成采样" if d["sample_seen"] else "尚无采样完成"
  457. valid = int(d["valid_temperature_mask"]).bit_count()
  458. flags = "/".join(name for name, active in (
  459. ("BMC失败", d["bmc_failed"]), ("BMC帧错", d["bmc_framing_error_seen"]),
  460. ("温度队列溢出", d["temperature_queue_overflow"]),
  461. ("看门狗超时", d["watchdog_expired"]),
  462. ("蜂鸣器开启", d.get("buzzer_on", False))) if active) or "无"
  463. sample = (f"温度 {d['temperature_c']} °C" if d["is_temperature"] else "状态寄存器(非温度)")
  464. return (f"固件 {d['firmware_version']} | CT {seen},读数可解码 {valid}/9,轮次 {d['scan_round']} | "
  465. f"SCL/SDA={int(d['scl_high'])}/{int(d['sda_high'])},忙={int(d['i2c_busy'])}\n"
  466. f"通道 {d['last_channel']},地址 0x{d['device_address']:02X},寄存器 0x{d['register']:02X},"
  467. f"结果 {d['error_name']},原始值 0x{d['raw_temperature']:04X},{sample}\n"
  468. f"BMC有效 {d['bmc_valid_count']}/24 | 历次结果掩码 0x{d['observed_result_mask']:02X} | 标志: {flags}")
  469. # ---------------------------------------------------------------------------
  470. # Configurable Chamber Mapping & Temperature Curve / Image Engine
  471. # ---------------------------------------------------------------------------
  472. CHAMBER_IDS = (1, 2, 3, 4)
  473. DEFAULT_CHAMBER_MAPPING: dict[int, dict[str, Any]] = {
  474. 1: {"name": "腔体 1", "bmc": [0, 1, 2, 3, 4, 5], "ct": [1, 2]},
  475. 2: {"name": "腔体 2", "bmc": [6, 7, 8, 9, 10, 11], "ct": [3, 4]},
  476. 3: {"name": "腔体 3", "bmc": [12, 13, 14, 15, 16, 17], "ct": [5, 6]},
  477. 4: {"name": "腔体 4", "bmc": [18, 19, 20, 21, 22, 23], "ct": [7, 8]},
  478. }
  479. CT_CHANNEL_HINTS: dict[int, str] = {
  480. 0: "U6本地",
  481. 1: "CON53/腔1进",
  482. 2: "CON55/腔1出",
  483. 3: "CON56/腔2进",
  484. 4: "CON57/腔2出",
  485. 5: "CON79/腔3进",
  486. 6: "CON80/腔3出",
  487. 7: "CON81/腔4进",
  488. 8: "CON82/腔4出",
  489. 9: "U24本地",
  490. 18: "U25本地",
  491. }
  492. BMC_CHANNEL_HINTS: dict[int, str] = {
  493. i: f"CPU{i // 12}_DIMM{i % 12}" for i in range(24)
  494. }
  495. # Distinct palettes for Memory (BMC) and Sensor (CT) curves
  496. BMC_CURVE_COLORS = (
  497. "#1976D2", "#0288D1", "#0097A7", "#5C6BC0", "#7B1FA2", "#3949AB",
  498. "#1E88E5", "#00ACC1", "#8E24AA", "#5E35B1", "#039BE5", "#303F9F",
  499. )
  500. BMC_AVG_COLOR = "#0D47A1"
  501. BMC_MAX_COLOR = "#6A1B9A"
  502. CT_CURVE_COLORS = (
  503. "#D32F2F", "#E65100", "#2E7D32", "#C2185B", "#F57C00", "#388E3C",
  504. "#B71C1C", "#BF360C", "#1B5E20",
  505. )
  506. CT_AVG_COLOR = "#B71C1C"
  507. def ct_channel_label(index: int, short: bool = False) -> str:
  508. hint = CT_CHANNEL_HINTS.get(index)
  509. if not hint:
  510. return f"CT{index}"
  511. if short:
  512. short_hint = hint.split("/")[-1]
  513. return f"CT{index}({short_hint})"
  514. return f"CT{index}({hint})"
  515. def bmc_channel_label(index: int, short: bool = True) -> str:
  516. if short:
  517. return f"BMC{index}"
  518. hint = BMC_CHANNEL_HINTS.get(index, "")
  519. return f"BMC{index}({hint})" if hint else f"BMC{index}"
  520. def parse_channel_spec(spec: Any, max_index: int, label: str = "通道") -> list[int]:
  521. """Parse flexible channel expressions like '0-5', '1,2', 'BMC0..BMC5', 'CT1,CT2' or list[int]."""
  522. if spec is None:
  523. return []
  524. if isinstance(spec, (list, tuple)):
  525. raw_items = list(spec)
  526. result: list[int] = []
  527. seen: set[int] = set()
  528. for item in raw_items:
  529. idx = integer(item, 0, max_index, label)
  530. if idx not in seen:
  531. seen.add(idx)
  532. result.append(idx)
  533. return result
  534. if not isinstance(spec, str):
  535. raise ValueError(f"{label} 配置格式无效")
  536. cleaned = spec.strip()
  537. if not cleaned or cleaned.lower() in ("none", "null", "无", "-"):
  538. return []
  539. # Normalize prefixes and separators
  540. cleaned = re.sub(r"(?i)\b(bmc|ct|ch|sensor|mem)", "", cleaned)
  541. cleaned = cleaned.replace("..", "-").replace("~", "-").replace("~", "-").replace("—", "-")
  542. tokens = [t.strip() for t in re.split(r"[,;,;\s/]+", cleaned) if t.strip()]
  543. result = []
  544. seen = set()
  545. for tok in tokens:
  546. if "-" in tok:
  547. parts = [p.strip() for p in tok.split("-") if p.strip()]
  548. if len(parts) != 2:
  549. raise ValueError(f"{label} 范围表达式无效: '{tok}'")
  550. start = integer(parts[0], 0, max_index, label)
  551. end = integer(parts[1], 0, max_index, label)
  552. step = 1 if end >= start else -1
  553. for idx in range(start, end + step, step):
  554. if idx not in seen:
  555. seen.add(idx)
  556. result.append(idx)
  557. else:
  558. idx = integer(tok, 0, max_index, label)
  559. if idx not in seen:
  560. seen.add(idx)
  561. result.append(idx)
  562. return result
  563. def format_channel_spec(channels: list[int]) -> str:
  564. """Format a channel list into compact string form (e.g., [0,1,2,3,4,5] -> '0-5', [1,2] -> '1,2')."""
  565. if not channels:
  566. return ""
  567. parts: list[str] = []
  568. i = 0
  569. n = len(channels)
  570. while i < n:
  571. j = i
  572. while j + 1 < n and channels[j + 1] == channels[j] + 1:
  573. j += 1
  574. if j - i >= 2:
  575. parts.append(f"{channels[i]}-{channels[j]}")
  576. elif j - i == 1:
  577. parts.append(f"{channels[i]},{channels[j]}")
  578. else:
  579. parts.append(str(channels[i]))
  580. i = j + 1
  581. return ",".join(parts)
  582. class ChamberMappingConfig:
  583. """Manages per-chamber Memory (BMC 0..23) and Sensor (CT 0..26) channel mapping with defaults and persistence."""
  584. def __init__(self, product: str = "6400-v2", chambers: dict[int, dict[str, Any]] | None = None):
  585. self.product = product
  586. self.chambers: dict[int, dict[str, Any]] = {}
  587. base = DEFAULT_CHAMBER_MAPPING
  588. for cid in CHAMBER_IDS:
  589. src = (chambers or {}).get(cid) or (chambers or {}).get(str(cid)) or base[cid]
  590. name = str(src.get("name", base[cid]["name"])).strip() or base[cid]["name"]
  591. bmc_list = parse_channel_spec(src.get("bmc", base[cid]["bmc"]), 23, f"腔体{cid} 内存(BMC)通道")
  592. ct_list = parse_channel_spec(src.get("ct", base[cid]["ct"]), 26, f"腔体{cid} Sensor(CT)通道")
  593. self.chambers[cid] = {"name": name, "bmc": bmc_list, "ct": ct_list}
  594. @classmethod
  595. def default(cls, product: str = "6400-v2") -> "ChamberMappingConfig":
  596. return cls(product=product)
  597. def reset_to_default(self) -> None:
  598. for cid in CHAMBER_IDS:
  599. base = DEFAULT_CHAMBER_MAPPING[cid]
  600. self.chambers[cid] = {
  601. "name": base["name"],
  602. "bmc": list(base["bmc"]),
  603. "ct": list(base["ct"]),
  604. }
  605. def set_chamber(self, chamber_id: int, bmc_spec: Any, ct_spec: Any, name: str | None = None) -> None:
  606. if chamber_id not in CHAMBER_IDS:
  607. raise ValueError(f"腔体编号必须为 1..4,当前为 {chamber_id}")
  608. bmc_list = parse_channel_spec(bmc_spec, 23, f"腔体{chamber_id} 内存(BMC)通道")
  609. ct_list = parse_channel_spec(ct_spec, 26, f"腔体{chamber_id} Sensor(CT)通道")
  610. cur_name = (name.strip() if isinstance(name, str) and name.strip() else self.chambers[chamber_id]["name"])
  611. self.chambers[chamber_id] = {"name": cur_name, "bmc": bmc_list, "ct": ct_list}
  612. def swap_pairs(self, *, swap_bmc: bool = False, swap_ct: bool = True) -> None:
  613. """Swap Chamber 1<->3 and Chamber 2<->4 channel mappings for field harness pair matching."""
  614. for a, b in ((1, 3), (2, 4)):
  615. if swap_bmc:
  616. self.chambers[a]["bmc"], self.chambers[b]["bmc"] = (
  617. list(self.chambers[b]["bmc"]),
  618. list(self.chambers[a]["bmc"]),
  619. )
  620. if swap_ct:
  621. self.chambers[a]["ct"], self.chambers[b]["ct"] = (
  622. list(self.chambers[b]["ct"]),
  623. list(self.chambers[a]["ct"]),
  624. )
  625. def to_dict(self) -> dict[str, Any]:
  626. return {
  627. "schema": "prod2u-chamber-mapping-v1",
  628. "product": self.product,
  629. "chambers": {
  630. str(cid): {
  631. "name": self.chambers[cid]["name"],
  632. "bmc": list(self.chambers[cid]["bmc"]),
  633. "bmc_spec": format_channel_spec(self.chambers[cid]["bmc"]),
  634. "ct": list(self.chambers[cid]["ct"]),
  635. "ct_spec": format_channel_spec(self.chambers[cid]["ct"]),
  636. }
  637. for cid in CHAMBER_IDS
  638. },
  639. }
  640. @classmethod
  641. def from_dict(cls, data: dict[str, Any], product: str | None = None) -> "ChamberMappingConfig":
  642. if not isinstance(data, dict):
  643. raise ValueError("映射配置必须为 JSON 对象")
  644. prod = product or data.get("product", "6400-v2")
  645. raw_chambers = data.get("chambers", data)
  646. if not isinstance(raw_chambers, dict):
  647. raise ValueError("映射配置缺少 chambers 字段")
  648. return cls(product=prod, chambers=raw_chambers)
  649. def save(self, path: Path) -> Path:
  650. target = Path(path)
  651. target.parent.mkdir(parents=True, exist_ok=True)
  652. target.write_text(json.dumps(self.to_dict(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  653. return target
  654. @classmethod
  655. def load(cls, path: Path, product: str | None = None) -> "ChamberMappingConfig":
  656. data = json.loads(Path(path).read_text(encoding="utf-8"))
  657. return cls.from_dict(data, product=product)
  658. @staticmethod
  659. def default_config_path(product: str) -> Path:
  660. base_dir = Path(os.environ.get("PROD2U_CONFIG_DIR", Path.home() / ".prod2u"))
  661. return base_dir / f"chamber_mapping_{product}.json"
  662. def extract_chamber_temperatures(
  663. self,
  664. state: dict[str, Any],
  665. chamber_id: int,
  666. *,
  667. ignore_zero_ct: bool = False,
  668. ) -> dict[str, Any]:
  669. if chamber_id not in CHAMBER_IDS:
  670. raise ValueError(f"无效腔体编号: {chamber_id}")
  671. cfg = self.chambers[chamber_id]
  672. bmc_all = state.get("bmc", {}).get("temperature_c", [])
  673. ct_all = state.get("ct", {}).get("temperature_c", [])
  674. bmc_items: list[tuple[int, str, int | None]] = []
  675. bmc_valid: list[int] = []
  676. for idx in cfg["bmc"]:
  677. val = bmc_all[idx] if idx < len(bmc_all) else None
  678. if val is not None and not (0 <= val <= 254):
  679. val = None
  680. bmc_items.append((idx, bmc_channel_label(idx), val))
  681. if val is not None:
  682. bmc_valid.append(int(val))
  683. ct_items: list[tuple[int, str, int | None]] = []
  684. ct_valid: list[int] = []
  685. for idx in cfg["ct"]:
  686. val = ct_all[idx] if idx < len(ct_all) else None
  687. if val is not None and not (0 <= val <= 254):
  688. val = None
  689. if ignore_zero_ct and val == 0:
  690. val = None
  691. ct_items.append((idx, ct_channel_label(idx, short=True), val))
  692. if val is not None:
  693. ct_valid.append(int(val))
  694. return {
  695. "chamber_id": chamber_id,
  696. "name": cfg["name"],
  697. "bmc_channels": list(cfg["bmc"]),
  698. "ct_channels": list(cfg["ct"]),
  699. "bmc_items": bmc_items,
  700. "ct_items": ct_items,
  701. "bmc_valid": bmc_valid,
  702. "ct_valid": ct_valid,
  703. "bmc_avg": (sum(bmc_valid) / len(bmc_valid)) if bmc_valid else None,
  704. "bmc_min": min(bmc_valid) if bmc_valid else None,
  705. "bmc_max": max(bmc_valid) if bmc_valid else None,
  706. "ct_avg": (sum(ct_valid) / len(ct_valid)) if ct_valid else None,
  707. "ct_min": min(ct_valid) if ct_valid else None,
  708. "ct_max": max(ct_valid) if ct_valid else None,
  709. }
  710. def format_realtime_summary(self, state: dict[str, Any], *, ignore_zero_ct: bool = False) -> str:
  711. parts = []
  712. for cid in CHAMBER_IDS:
  713. info = self.extract_chamber_temperatures(state, cid, ignore_zero_ct=ignore_zero_ct)
  714. if info["bmc_avg"] is not None:
  715. bmc_str = f"内存均{info['bmc_avg']:.1f}°C({info['bmc_min']}~{info['bmc_max']}°C)"
  716. else:
  717. bmc_str = "内存:--"
  718. ct_parts = [f"CT{idx}={val}°C" if val is not None else f"CT{idx}=--"
  719. for idx, _, val in info["ct_items"]]
  720. ct_str = "/".join(ct_parts) if ct_parts else "Sensor:未映射"
  721. parts.append(f"腔{cid}[{bmc_str} | {ct_str}]")
  722. return " ".join(parts)
  723. class TemperatureCurveStore:
  724. """Stores raw 24-BMC + 27-CT time-series samples so chamber mapping changes re-project history dynamically."""
  725. def __init__(self, max_capacity: int = 7200):
  726. self.max_capacity = max_capacity
  727. self.samples: list[dict[str, Any]] = []
  728. self._lock = threading.Lock()
  729. def clear(self) -> None:
  730. with self._lock:
  731. self.samples.clear()
  732. def __len__(self) -> int:
  733. with self._lock:
  734. return len(self.samples)
  735. @staticmethod
  736. def _normalize_temp_list(values: list[Any], count: int) -> list[int | None]:
  737. out: list[int | None] = []
  738. for i in range(count):
  739. if i < len(values):
  740. v = values[i]
  741. if v is None or v == 255 or isinstance(v, bool):
  742. out.append(None)
  743. else:
  744. try:
  745. iv = int(v)
  746. out.append(iv if 0 <= iv <= 254 else None)
  747. except (ValueError, TypeError):
  748. out.append(None)
  749. else:
  750. out.append(None)
  751. return out
  752. def record_raw_arrays(
  753. self,
  754. bmc: list[Any],
  755. ct: list[Any],
  756. *,
  757. timestamp: float | None = None,
  758. time_label: str | None = None,
  759. source: str = "GET_DATA",
  760. ) -> dict[str, Any]:
  761. ts = time.time() if timestamp is None else float(timestamp)
  762. t_lbl = time_label or datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S")
  763. sample = {
  764. "timestamp": ts,
  765. "time_label": t_lbl,
  766. "bmc": self._normalize_temp_list(bmc, 24),
  767. "ct": self._normalize_temp_list(ct, 27),
  768. "source": source,
  769. }
  770. with self._lock:
  771. self.samples.append(sample)
  772. if len(self.samples) > self.max_capacity:
  773. del self.samples[: len(self.samples) - self.max_capacity]
  774. return sample
  775. def record_state(
  776. self,
  777. state: dict[str, Any],
  778. *,
  779. timestamp: float | None = None,
  780. time_label: str | None = None,
  781. source: str = "GET_DATA",
  782. ) -> dict[str, Any]:
  783. bmc = state.get("bmc", {}).get("temperature_c", [])
  784. ct = state.get("ct", {}).get("temperature_c", [])
  785. return self.record_raw_arrays(bmc, ct, timestamp=timestamp, time_label=time_label, source=source)
  786. def snapshot(self, max_points: int = 0) -> list[dict[str, Any]]:
  787. with self._lock:
  788. if max_points and max_points > 0:
  789. return list(self.samples[-max_points:])
  790. return list(self.samples)
  791. def chamber_series(
  792. self,
  793. mapping: ChamberMappingConfig,
  794. chamber_id: int,
  795. *,
  796. max_points: int = 0,
  797. ignore_zero_ct: bool = False,
  798. ) -> dict[str, Any]:
  799. if chamber_id not in CHAMBER_IDS:
  800. raise ValueError(f"无效腔体编号: {chamber_id}")
  801. cfg = mapping.chambers[chamber_id]
  802. pts = self.snapshot(max_points=max_points)
  803. t0 = pts[0]["timestamp"] if pts else 0.0
  804. elapsed = [round(p["timestamp"] - t0, 2) for p in pts]
  805. time_labels = [p["time_label"] for p in pts]
  806. bmc_series: dict[int, list[int | None]] = {ch: [] for ch in cfg["bmc"]}
  807. ct_series: dict[int, list[int | None]] = {ch: [] for ch in cfg["ct"]}
  808. bmc_avg: list[float | None] = []
  809. bmc_max: list[int | None] = []
  810. bmc_min: list[int | None] = []
  811. ct_avg: list[float | None] = []
  812. for p in pts:
  813. b_vals = []
  814. for ch in cfg["bmc"]:
  815. v = p["bmc"][ch] if ch < len(p["bmc"]) else None
  816. bmc_series[ch].append(v)
  817. if v is not None:
  818. b_vals.append(v)
  819. bmc_avg.append(round(sum(b_vals) / len(b_vals), 2) if b_vals else None)
  820. bmc_max.append(max(b_vals) if b_vals else None)
  821. bmc_min.append(min(b_vals) if b_vals else None)
  822. c_vals = []
  823. for ch in cfg["ct"]:
  824. v = p["ct"][ch] if ch < len(p["ct"]) else None
  825. if ignore_zero_ct and v == 0:
  826. v = None
  827. ct_series[ch].append(v)
  828. if v is not None:
  829. c_vals.append(v)
  830. ct_avg.append(round(sum(c_vals) / len(c_vals), 2) if c_vals else None)
  831. u6_local = [p["ct"][0] if p["ct"] else None for p in pts]
  832. return {
  833. "chamber_id": chamber_id,
  834. "name": cfg["name"],
  835. "bmc_channels": list(cfg["bmc"]),
  836. "ct_channels": list(cfg["ct"]),
  837. "sample_count": len(pts),
  838. "elapsed": elapsed,
  839. "time_labels": time_labels,
  840. "bmc_series": bmc_series,
  841. "ct_series": ct_series,
  842. "bmc_avg": bmc_avg,
  843. "bmc_max": bmc_max,
  844. "bmc_min": bmc_min,
  845. "ct_avg": ct_avg,
  846. "u6_local": u6_local,
  847. }
  848. def load_from_log_file(self, path: Path, model: Model | None = None) -> int:
  849. """Import temperature samples from pwm_scope JSONL logs, GUI session logs, or hex dumps."""
  850. text = Path(path).read_text(encoding="utf-8", errors="replace")
  851. imported = 0
  852. base_ts = time.time()
  853. for line_idx, raw_line in enumerate(text.splitlines()):
  854. line = raw_line.strip()
  855. if not line:
  856. continue
  857. # 1. Try JSONL (pwm_scope.py or structured event log)
  858. if line.startswith("{") and line.endswith("}"):
  859. try:
  860. rec = json.loads(line)
  861. ev = rec.get("event")
  862. t_str = str(rec.get("time", ""))
  863. t_lbl = t_str[11:19] if len(t_str) >= 19 and "T" in t_str else f"#{imported + 1}"
  864. ts = base_ts + float(rec.get("elapsed", imported))
  865. if ev == "CYCLE" and ("ct" in rec or "bmc" in rec):
  866. bmc_arr = list(rec.get("bmc", [255] * 24))
  867. ct_arr = list(rec.get("ct", [])) + list(rec.get("ct_reserved", []))
  868. self.record_raw_arrays(bmc_arr, ct_arr, timestamp=ts, time_label=t_lbl, source="PWM_SCOPE")
  869. imported += 1
  870. continue
  871. hex_field = rec.get("hex", "")
  872. if hex_field and rec.get("type") in ("42", 0x42, None):
  873. raw_bytes = parse_hex(hex_field)
  874. if len(raw_bytes) >= 6 and raw_bytes[:2] == PREAMBLE and raw_bytes[2] == FrameType.GET_DATA:
  875. imported += self._import_get_data_frame(raw_bytes, model, ts, t_lbl)
  876. continue
  877. except Exception:
  878. pass
  879. # 2. Try GUI session log line: [HH:MM:SS.mmm] [RX...] A5 5A 42 ...
  880. m = re.search(r"\[(\d{2}:\d{2}:\d{2})(?:\.\d+)?\]\s*\[[^\]]+\]\s*([0-9A-Fa-f][0-9A-Fa-f\s]+)", line)
  881. if m:
  882. t_lbl = m.group(1)
  883. hex_part = m.group(2).strip()
  884. try:
  885. raw_bytes = parse_hex(hex_part)
  886. imported += self._import_get_data_stream(raw_bytes, model, base_ts + imported, t_lbl)
  887. continue
  888. except Exception:
  889. pass
  890. # 3. Raw hex line containing A5 5A 42
  891. if "A5" in line.upper() and "5A" in line.upper():
  892. try:
  893. raw_bytes = parse_hex(line)
  894. imported += self._import_get_data_stream(raw_bytes, model, base_ts + imported, f"#{imported + 1}")
  895. except Exception:
  896. pass
  897. return imported
  898. def _import_get_data_frame(self, frame_bytes: bytes, model: Model | None, ts: float, t_lbl: str) -> int:
  899. f = decode_frame(frame_bytes)
  900. if not f.crc_ok or f.frame_type != FrameType.GET_DATA:
  901. return 0
  902. p = f.payload
  903. if model is not None:
  904. try:
  905. st = model.state(p)
  906. self.record_state(st, timestamp=ts, time_label=t_lbl, source="LOG_FRAME")
  907. return 1
  908. except Exception:
  909. pass
  910. # Fallback payload layout detection (86/83 bytes for 6400, 63 bytes for MRDIMM)
  911. if len(p) in (83, 86):
  912. self.record_raw_arrays(list(p[32:56]), list(p[56:83]), timestamp=ts, time_label=t_lbl, source="LOG_6400")
  913. return 1
  914. if len(p) == 63:
  915. self.record_raw_arrays(list(p[8:32]), list(p[32:59]), timestamp=ts, time_label=t_lbl, source="LOG_MRDIMM")
  916. return 1
  917. return 0
  918. def _import_get_data_stream(self, data: bytes, model: Model | None, ts: float, t_lbl: str) -> int:
  919. count = 0
  920. pos = 0
  921. while pos + 6 <= len(data):
  922. idx = data.find(PREAMBLE, pos)
  923. if idx < 0 or idx + 4 > len(data):
  924. break
  925. length = data[idx + 3]
  926. end = idx + 6 + length
  927. if end > len(data):
  928. break
  929. count += self._import_get_data_frame(data[idx:end], model, ts + count * 0.1, t_lbl)
  930. pos = end
  931. return count
  932. def format_duration_mmss(seconds: float | None) -> str:
  933. """Format duration in seconds into 'XX.Xs (MM:SS)' or '--' if None."""
  934. if seconds is None:
  935. return "--"
  936. sec = max(0.0, float(seconds))
  937. mins = int(sec // 60)
  938. rem = int(round(sec - mins * 60))
  939. if rem == 60:
  940. mins += 1
  941. rem = 0
  942. return f"{sec:.1f}s ({mins:02d}:{rem:02d})"
  943. class ThermalTestSession:
  944. """High-temperature hood 4-chamber thermal test session & reach-time analyzer.
  945. Supports:
  946. - Independent expected target temperature per chamber (Chambers 1..4, default 70°C)
  947. - Overall pass minimum temperature across all 4 chambers of the high-temperature hood (default 70°C)
  948. - Independent calculation of time-to-target for each chamber's Sensor (CT) temperature and Memory (BMC) temperature
  949. - Continuous data recording: after any chamber reaches its target temperature first, data recording
  950. continues uninterrupted for all 4 chambers (tracking post_target_samples, peak temperatures, and full curves)
  951. - Fan speed & fan intervention timing / reference temperature tracking to analyze heating time relationships
  952. - Local & remote backend (192.168.2.25) synchronization and JSON/CSV report export
  953. """
  954. def __init__(
  955. self,
  956. product: str = "6400-v2",
  957. *,
  958. test_name: str = "6400V2.0 高温罩四腔升温测试",
  959. overall_pass_min_temp_c: float = 70.0,
  960. chamber_target_temp_c: dict[int, float] | None = None,
  961. bmc_eval_mode: str = "avg",
  962. ct_eval_mode: str = "avg",
  963. ptc_duty_percent: int = 100,
  964. ssr_duty_percent: int = 100,
  965. initial_fan_duty_percent: int = 0,
  966. active_fan_duty_percent: int = 50,
  967. fan_intervention_mode: str = "time_s",
  968. fan_intervention_time_s: float = 120.0,
  969. fan_intervention_ref_temp_c: float = 55.0,
  970. fan_intervention_ref_source: str = "ct",
  971. backend_url: str = "http://192.168.2.25:8766",
  972. ):
  973. self.session_id = datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
  974. self.product = product
  975. self.test_name = str(test_name).strip() or "高温罩四腔升温测试"
  976. self.overall_pass_min_temp_c = float(overall_pass_min_temp_c)
  977. self.chamber_target_temp_c: dict[int, float] = {}
  978. for cid in CHAMBER_IDS:
  979. raw_t = (chamber_target_temp_c or {}).get(cid, (chamber_target_temp_c or {}).get(str(cid), 70.0))
  980. self.chamber_target_temp_c[cid] = float(raw_t)
  981. self.bmc_eval_mode = bmc_eval_mode if bmc_eval_mode in ("avg", "max", "min") else "avg"
  982. self.ct_eval_mode = ct_eval_mode if ct_eval_mode in ("avg", "max", "min") else "avg"
  983. # Fan & Heating experiment parameters
  984. self.ptc_duty_percent = max(0, min(100, int(ptc_duty_percent)))
  985. self.ssr_duty_percent = max(0, min(100, int(ssr_duty_percent)))
  986. self.initial_fan_duty_percent = max(0, min(100, int(initial_fan_duty_percent)))
  987. self.active_fan_duty_percent = max(0, min(100, int(active_fan_duty_percent)))
  988. self.fan_intervention_mode = (
  989. fan_intervention_mode
  990. if fan_intervention_mode in ("immediate", "time_s", "ref_temp_c", "manual")
  991. else "time_s"
  992. )
  993. self.fan_intervention_time_s = max(0.0, float(fan_intervention_time_s))
  994. self.fan_intervention_ref_temp_c = float(fan_intervention_ref_temp_c)
  995. self.fan_intervention_ref_source = (
  996. fan_intervention_ref_source if fan_intervention_ref_source in ("ct", "bmc", "any") else "ct"
  997. )
  998. self.backend_url = str(backend_url).rstrip("/")
  999. self.active = False
  1000. self.start_timestamp: float | None = None
  1001. self.stop_timestamp: float | None = None
  1002. self.sample_count = 0
  1003. self.fan_intervened = False
  1004. self.fan_intervened_elapsed_s: float | None = None
  1005. self.fan_intervened_temp_c: float | None = None
  1006. self.fan_intervened_reason: str = ""
  1007. self.current_fan_duty_percent: int = self.initial_fan_duty_percent
  1008. self.chamber_stats: dict[int, dict[str, Any]] = {}
  1009. self.first_reached_chamber_id: int | None = None
  1010. self.first_reached_kind: str | None = None
  1011. self.first_reached_elapsed_s: float | None = None
  1012. self.reset_stats()
  1013. def set_targets(
  1014. self,
  1015. overall_pass_min_temp_c: float,
  1016. chamber_targets: dict[int, float] | None = None,
  1017. ) -> None:
  1018. self.overall_pass_min_temp_c = float(overall_pass_min_temp_c)
  1019. if chamber_targets:
  1020. for cid in CHAMBER_IDS:
  1021. if cid in chamber_targets or str(cid) in chamber_targets:
  1022. val = chamber_targets.get(cid, chamber_targets.get(str(cid)))
  1023. self.chamber_target_temp_c[cid] = float(val)
  1024. for cid in CHAMBER_IDS:
  1025. if cid in self.chamber_stats:
  1026. self.chamber_stats[cid]["target_temp_c"] = self.chamber_target_temp_c[cid]
  1027. self.chamber_stats[cid]["pass_min_temp_c"] = self.overall_pass_min_temp_c
  1028. self.chamber_stats[cid]["effective_target_c"] = max(
  1029. self.chamber_target_temp_c[cid], self.overall_pass_min_temp_c
  1030. )
  1031. def reset_stats(self) -> None:
  1032. self.sample_count = 0
  1033. self.first_reached_chamber_id = None
  1034. self.first_reached_kind = None
  1035. self.first_reached_elapsed_s = None
  1036. self.fan_intervened = (self.fan_intervention_mode == "immediate")
  1037. self.fan_intervened_elapsed_s = 0.0 if self.fan_intervened else None
  1038. self.fan_intervened_temp_c = None
  1039. self.fan_intervened_reason = "0s 立即介入" if self.fan_intervened else ""
  1040. self.current_fan_duty_percent = (
  1041. self.active_fan_duty_percent if self.fan_intervened else self.initial_fan_duty_percent
  1042. )
  1043. self.chamber_stats = {}
  1044. for cid in CHAMBER_IDS:
  1045. t_c = self.chamber_target_temp_c.get(cid, 70.0)
  1046. p_c = self.overall_pass_min_temp_c
  1047. self.chamber_stats[cid] = {
  1048. "chamber_id": cid,
  1049. "target_temp_c": t_c,
  1050. "pass_min_temp_c": p_c,
  1051. "effective_target_c": max(t_c, p_c),
  1052. # Sensor (CT) metrics
  1053. "sensor_initial_c": None,
  1054. "sensor_current_c": None,
  1055. "sensor_peak_c": None,
  1056. "sensor_reached_target": False,
  1057. "sensor_time_to_target_s": None,
  1058. "sensor_reached_pass_min": False,
  1059. "sensor_time_to_pass_min_s": None,
  1060. "sensor_reached": False,
  1061. "sensor_reached_at_label": None,
  1062. "sensor_reached_temp_c": None,
  1063. "sensor_post_target_samples": 0,
  1064. # Memory (BMC) metrics
  1065. "memory_initial_c": None,
  1066. "memory_current_c": None,
  1067. "memory_peak_c": None,
  1068. "memory_reached_target": False,
  1069. "memory_time_to_target_s": None,
  1070. "memory_reached_pass_min": False,
  1071. "memory_time_to_pass_min_s": None,
  1072. "memory_reached": False,
  1073. "memory_reached_at_label": None,
  1074. "memory_reached_temp_c": None,
  1075. "memory_post_target_samples": 0,
  1076. # Combined chamber status
  1077. "both_reached": False,
  1078. "chamber_time_to_target_s": None,
  1079. "post_target_samples": 0,
  1080. }
  1081. def start(self, start_timestamp: float | None = None) -> None:
  1082. self.session_id = datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
  1083. self.reset_stats()
  1084. self.start_timestamp = time.time() if start_timestamp is None else float(start_timestamp)
  1085. self.stop_timestamp = None
  1086. self.active = True
  1087. def stop(self, stop_timestamp: float | None = None) -> None:
  1088. if self.active:
  1089. self.stop_timestamp = time.time() if stop_timestamp is None else float(stop_timestamp)
  1090. self.active = False
  1091. def _select_metric(self, info: dict[str, Any], prefix: str, mode: str) -> float | None:
  1092. val = info.get(f"{prefix}_{mode}")
  1093. if val is None and mode != "avg":
  1094. val = info.get(f"{prefix}_avg")
  1095. return float(val) if val is not None else None
  1096. def process_sample(
  1097. self,
  1098. sample: dict[str, Any],
  1099. mapping: ChamberMappingConfig,
  1100. *,
  1101. ignore_zero_ct: bool = False,
  1102. ) -> dict[str, Any]:
  1103. """Process one raw temperature sample; continues recording even after any/all chambers reach target."""
  1104. ts = float(sample.get("timestamp", time.time()))
  1105. t_lbl = str(sample.get("time_label", datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S")))
  1106. if self.start_timestamp is None:
  1107. self.start_timestamp = ts
  1108. elapsed_s = max(0.0, round(ts - self.start_timestamp, 2))
  1109. self.sample_count += 1
  1110. fake_state = {
  1111. "bmc": {"temperature_c": sample.get("bmc", [])},
  1112. "ct": {"temperature_c": sample.get("ct", [])},
  1113. }
  1114. max_ct_now: float | None = None
  1115. max_bmc_now: float | None = None
  1116. for cid in CHAMBER_IDS:
  1117. info = mapping.extract_chamber_temperatures(fake_state, cid, ignore_zero_ct=ignore_zero_ct)
  1118. st = self.chamber_stats[cid]
  1119. target_c = st["target_temp_c"]
  1120. pass_min_c = st["pass_min_temp_c"]
  1121. eff_c = max(target_c, pass_min_c)
  1122. s_val = self._select_metric(info, "ct", self.ct_eval_mode)
  1123. m_val = self._select_metric(info, "bmc", self.bmc_eval_mode)
  1124. if s_val is not None:
  1125. max_ct_now = s_val if max_ct_now is None else max(max_ct_now, s_val)
  1126. if st["sensor_initial_c"] is None:
  1127. st["sensor_initial_c"] = round(s_val, 2)
  1128. st["sensor_current_c"] = round(s_val, 2)
  1129. st["sensor_peak_c"] = round(s_val if st["sensor_peak_c"] is None else max(st["sensor_peak_c"], s_val), 2)
  1130. if st["sensor_reached"]:
  1131. st["sensor_post_target_samples"] += 1
  1132. else:
  1133. if not st["sensor_reached_target"] and s_val >= target_c:
  1134. st["sensor_reached_target"] = True
  1135. st["sensor_time_to_target_s"] = elapsed_s
  1136. if not st["sensor_reached_pass_min"] and s_val >= pass_min_c:
  1137. st["sensor_reached_pass_min"] = True
  1138. st["sensor_time_to_pass_min_s"] = elapsed_s
  1139. if s_val >= eff_c:
  1140. st["sensor_reached"] = True
  1141. if st["sensor_time_to_target_s"] is None:
  1142. st["sensor_time_to_target_s"] = elapsed_s
  1143. st["sensor_reached_at_label"] = t_lbl
  1144. st["sensor_reached_temp_c"] = round(s_val, 2)
  1145. if self.first_reached_chamber_id is None:
  1146. self.first_reached_chamber_id = cid
  1147. self.first_reached_kind = "sensor"
  1148. self.first_reached_elapsed_s = elapsed_s
  1149. if m_val is not None:
  1150. max_bmc_now = m_val if max_bmc_now is None else max(max_bmc_now, m_val)
  1151. if st["memory_initial_c"] is None:
  1152. st["memory_initial_c"] = round(m_val, 2)
  1153. st["memory_current_c"] = round(m_val, 2)
  1154. st["memory_peak_c"] = round(m_val if st["memory_peak_c"] is None else max(st["memory_peak_c"], m_val), 2)
  1155. if st["memory_reached"]:
  1156. st["memory_post_target_samples"] += 1
  1157. else:
  1158. if not st["memory_reached_target"] and m_val >= target_c:
  1159. st["memory_reached_target"] = True
  1160. st["memory_time_to_target_s"] = elapsed_s
  1161. if not st["memory_reached_pass_min"] and m_val >= pass_min_c:
  1162. st["memory_reached_pass_min"] = True
  1163. st["memory_time_to_pass_min_s"] = elapsed_s
  1164. if m_val >= eff_c:
  1165. st["memory_reached"] = True
  1166. if st["memory_time_to_target_s"] is None:
  1167. st["memory_time_to_target_s"] = elapsed_s
  1168. st["memory_reached_at_label"] = t_lbl
  1169. st["memory_reached_temp_c"] = round(m_val, 2)
  1170. if self.first_reached_chamber_id is None:
  1171. self.first_reached_chamber_id = cid
  1172. self.first_reached_kind = "memory"
  1173. self.first_reached_elapsed_s = elapsed_s
  1174. was_any_reached = st["sensor_reached"] or st["memory_reached"]
  1175. st["both_reached"] = bool(st["sensor_reached"] and st["memory_reached"])
  1176. if st["both_reached"] and st["chamber_time_to_target_s"] is None:
  1177. st["chamber_time_to_target_s"] = max(
  1178. float(st["sensor_time_to_target_s"] or 0.0),
  1179. float(st["memory_time_to_target_s"] or 0.0),
  1180. )
  1181. if was_any_reached:
  1182. st["post_target_samples"] = max(st["sensor_post_target_samples"], st["memory_post_target_samples"])
  1183. # Check fan intervention trigger
  1184. fan_switched_now = False
  1185. if not self.fan_intervened and self.fan_intervention_mode != "manual":
  1186. if self.fan_intervention_mode == "immediate":
  1187. self.fan_intervened = True
  1188. self.fan_intervened_elapsed_s = elapsed_s
  1189. self.fan_intervened_temp_c = max_ct_now if max_ct_now is not None else max_bmc_now
  1190. self.fan_intervened_reason = "立即介入 (0s)"
  1191. self.current_fan_duty_percent = self.active_fan_duty_percent
  1192. fan_switched_now = True
  1193. elif self.fan_intervention_mode == "time_s" and elapsed_s >= self.fan_intervention_time_s:
  1194. self.fan_intervened = True
  1195. self.fan_intervened_elapsed_s = elapsed_s
  1196. self.fan_intervened_temp_c = max_ct_now if max_ct_now is not None else max_bmc_now
  1197. self.fan_intervened_reason = f"达到设定介入时间 {self.fan_intervention_time_s:.1f}s (实测 {elapsed_s:.1f}s)"
  1198. self.current_fan_duty_percent = self.active_fan_duty_percent
  1199. fan_switched_now = True
  1200. elif self.fan_intervention_mode == "ref_temp_c":
  1201. ref_candidates: list[float] = []
  1202. if self.fan_intervention_ref_source in ("ct", "any") and max_ct_now is not None:
  1203. ref_candidates.append(max_ct_now)
  1204. if self.fan_intervention_ref_source in ("bmc", "any") and max_bmc_now is not None:
  1205. ref_candidates.append(max_bmc_now)
  1206. ref_now = max(ref_candidates) if ref_candidates else None
  1207. if ref_now is not None and ref_now >= self.fan_intervention_ref_temp_c:
  1208. self.fan_intervened = True
  1209. self.fan_intervened_elapsed_s = elapsed_s
  1210. self.fan_intervened_temp_c = round(ref_now, 2)
  1211. self.fan_intervened_reason = (
  1212. f"参考温度达到 {ref_now:.1f}°C >= 阈值 {self.fan_intervention_ref_temp_c:.1f}°C (@ {elapsed_s:.1f}s)"
  1213. )
  1214. self.current_fan_duty_percent = self.active_fan_duty_percent
  1215. fan_switched_now = True
  1216. return {
  1217. "elapsed_s": elapsed_s,
  1218. "fan_switched_now": fan_switched_now,
  1219. "current_fan_duty_percent": self.current_fan_duty_percent,
  1220. }
  1221. def evaluate_from_store(
  1222. self,
  1223. store: TemperatureCurveStore,
  1224. mapping: ChamberMappingConfig,
  1225. *,
  1226. ignore_zero_ct: bool = False,
  1227. ) -> dict[str, Any]:
  1228. """Re-evaluate the entire TemperatureCurveStore history from start to end."""
  1229. pts = store.snapshot()
  1230. was_active = self.active
  1231. self.reset_stats()
  1232. self.active = was_active
  1233. if pts:
  1234. self.start_timestamp = float(pts[0]["timestamp"])
  1235. for p in pts:
  1236. self.process_sample(p, mapping, ignore_zero_ct=ignore_zero_ct)
  1237. if not self.active:
  1238. self.stop_timestamp = float(pts[-1]["timestamp"])
  1239. return self.summary()
  1240. def build_set_values(self, model: Model) -> list[int]:
  1241. """Build SET_ALL channel duty array for the current test phase (initial vs post-intervention fan speed)."""
  1242. fan_d = self.current_fan_duty_percent
  1243. ptc_d = self.ptc_duty_percent
  1244. ssr_d = self.ssr_duty_percent
  1245. if model.motor:
  1246. return [fan_d] * 4 + [ptc_d] * 4
  1247. if model.product == "6400-v2":
  1248. return [ptc_d] * 24 + [fan_d] * 8 + [ssr_d] * 3
  1249. return [ptc_d] * 24 + [fan_d] * 8
  1250. def summary(self) -> dict[str, Any]:
  1251. """Return structured summary of all 4 chambers and overall high-temperature hood pass status."""
  1252. sensor_all_reached = all(self.chamber_stats[c]["sensor_reached"] for c in CHAMBER_IDS)
  1253. memory_all_reached = all(self.chamber_stats[c]["memory_reached"] for c in CHAMBER_IDS)
  1254. both_all_reached = sensor_all_reached and memory_all_reached
  1255. s_times = [
  1256. float(self.chamber_stats[c]["sensor_time_to_target_s"])
  1257. for c in CHAMBER_IDS
  1258. if self.chamber_stats[c]["sensor_time_to_target_s"] is not None
  1259. ]
  1260. m_times = [
  1261. float(self.chamber_stats[c]["memory_time_to_target_s"])
  1262. for c in CHAMBER_IDS
  1263. if self.chamber_stats[c]["memory_time_to_target_s"] is not None
  1264. ]
  1265. hood_sensor_time_s = max(s_times) if len(s_times) == 4 else None
  1266. hood_memory_time_s = max(m_times) if len(m_times) == 4 else None
  1267. hood_total_time_s = (
  1268. max(hood_sensor_time_s, hood_memory_time_s)
  1269. if (hood_sensor_time_s is not None and hood_memory_time_s is not None)
  1270. else (hood_sensor_time_s if hood_sensor_time_s is not None else hood_memory_time_s)
  1271. )
  1272. elapsed_total = 0.0
  1273. if self.start_timestamp is not None:
  1274. end_ts = self.stop_timestamp if self.stop_timestamp is not None else time.time()
  1275. elapsed_total = max(0.0, round(end_ts - self.start_timestamp, 2))
  1276. total_post_target_samples = sum(self.chamber_stats[c]["post_target_samples"] for c in CHAMBER_IDS)
  1277. return {
  1278. "schema": "prod2u-thermal-test-report-v1",
  1279. "session_id": self.session_id,
  1280. "product": self.product,
  1281. "test_name": self.test_name,
  1282. "active": self.active,
  1283. "sample_count": self.sample_count,
  1284. "elapsed_total_s": elapsed_total,
  1285. "overall_pass_min_temp_c": self.overall_pass_min_temp_c,
  1286. "chamber_target_temp_c": dict(self.chamber_target_temp_c),
  1287. "bmc_eval_mode": self.bmc_eval_mode,
  1288. "ct_eval_mode": self.ct_eval_mode,
  1289. "experiment_params": {
  1290. "ptc_duty_percent": self.ptc_duty_percent,
  1291. "ssr_duty_percent": self.ssr_duty_percent,
  1292. "initial_fan_duty_percent": self.initial_fan_duty_percent,
  1293. "active_fan_duty_percent": self.active_fan_duty_percent,
  1294. "fan_intervention_mode": self.fan_intervention_mode,
  1295. "fan_intervention_time_s": self.fan_intervention_time_s,
  1296. "fan_intervention_ref_temp_c": self.fan_intervention_ref_temp_c,
  1297. "fan_intervention_ref_source": self.fan_intervention_ref_source,
  1298. "fan_intervened": self.fan_intervened,
  1299. "fan_intervened_elapsed_s": self.fan_intervened_elapsed_s,
  1300. "fan_intervened_temp_c": self.fan_intervened_temp_c,
  1301. "fan_intervened_reason": self.fan_intervened_reason,
  1302. "current_fan_duty_percent": self.current_fan_duty_percent,
  1303. },
  1304. "first_reached": {
  1305. "chamber_id": self.first_reached_chamber_id,
  1306. "kind": self.first_reached_kind,
  1307. "elapsed_s": self.first_reached_elapsed_s,
  1308. "continuous_recording_active": True,
  1309. "total_post_target_samples": total_post_target_samples,
  1310. },
  1311. "hood_summary": {
  1312. "sensor_all_4_reached": sensor_all_reached,
  1313. "memory_all_4_reached": memory_all_reached,
  1314. "hood_all_reached": both_all_reached,
  1315. "sensor_reached_count": len(s_times),
  1316. "memory_reached_count": len(m_times),
  1317. "hood_sensor_reach_time_s": hood_sensor_time_s,
  1318. "hood_memory_reach_time_s": hood_memory_time_s,
  1319. "hood_total_reach_time_s": hood_total_time_s,
  1320. },
  1321. "chambers": {str(cid): dict(self.chamber_stats[cid]) for cid in CHAMBER_IDS},
  1322. }
  1323. def export_summary_csv(self) -> str:
  1324. """Export reach-time and experiment parameter summary as CSV."""
  1325. rep = self.summary()
  1326. exp = rep["experiment_params"]
  1327. headers = [
  1328. "session_id",
  1329. "test_name",
  1330. "chamber",
  1331. "target_temp_c",
  1332. "overall_pass_min_temp_c",
  1333. "sensor_initial_c",
  1334. "sensor_current_c",
  1335. "sensor_peak_c",
  1336. "sensor_reached",
  1337. "sensor_time_to_target_s",
  1338. "sensor_time_mmss",
  1339. "memory_initial_c",
  1340. "memory_current_c",
  1341. "memory_peak_c",
  1342. "memory_reached",
  1343. "memory_time_to_target_s",
  1344. "memory_time_mmss",
  1345. "post_target_samples",
  1346. "ptc_duty_pct",
  1347. "ssr_duty_pct",
  1348. "initial_fan_pct",
  1349. "active_fan_pct",
  1350. "fan_intervention_mode",
  1351. "fan_intervened_elapsed_s",
  1352. "fan_intervened_temp_c",
  1353. ]
  1354. rows = [",".join(headers)]
  1355. for cid in CHAMBER_IDS:
  1356. st = self.chamber_stats[cid]
  1357. row = [
  1358. self.session_id,
  1359. self.test_name.replace(",", ";"),
  1360. f"腔体{cid}",
  1361. f"{st['target_temp_c']:.1f}",
  1362. f"{st['pass_min_temp_c']:.1f}",
  1363. "" if st["sensor_initial_c"] is None else f"{st['sensor_initial_c']:.1f}",
  1364. "" if st["sensor_current_c"] is None else f"{st['sensor_current_c']:.1f}",
  1365. "" if st["sensor_peak_c"] is None else f"{st['sensor_peak_c']:.1f}",
  1366. "PASS" if st["sensor_reached"] else "PENDING",
  1367. "" if st["sensor_time_to_target_s"] is None else f"{st['sensor_time_to_target_s']:.2f}",
  1368. format_duration_mmss(st["sensor_time_to_target_s"]),
  1369. "" if st["memory_initial_c"] is None else f"{st['memory_initial_c']:.1f}",
  1370. "" if st["memory_current_c"] is None else f"{st['memory_current_c']:.1f}",
  1371. "" if st["memory_peak_c"] is None else f"{st['memory_peak_c']:.1f}",
  1372. "PASS" if st["memory_reached"] else "PENDING",
  1373. "" if st["memory_time_to_target_s"] is None else f"{st['memory_time_to_target_s']:.2f}",
  1374. format_duration_mmss(st["memory_time_to_target_s"]),
  1375. str(st["post_target_samples"]),
  1376. str(exp["ptc_duty_percent"]),
  1377. str(exp["ssr_duty_percent"]),
  1378. str(exp["initial_fan_duty_percent"]),
  1379. str(exp["active_fan_duty_percent"]),
  1380. str(exp["fan_intervention_mode"]),
  1381. "" if exp["fan_intervened_elapsed_s"] is None else f"{exp['fan_intervened_elapsed_s']:.2f}",
  1382. "" if exp["fan_intervened_temp_c"] is None else f"{exp['fan_intervened_temp_c']:.1f}",
  1383. ]
  1384. rows.append(",".join(row))
  1385. hs = rep["hood_summary"]
  1386. rows.append(
  1387. ",".join([
  1388. self.session_id,
  1389. self.test_name.replace(",", ";"),
  1390. "高温罩四腔整体",
  1391. f"{max(self.chamber_target_temp_c.values()):.1f}",
  1392. f"{self.overall_pass_min_temp_c:.1f}",
  1393. "",
  1394. "",
  1395. "",
  1396. "PASS" if hs["sensor_all_4_reached"] else f"{hs['sensor_reached_count']}/4",
  1397. "" if hs["hood_sensor_reach_time_s"] is None else f"{hs['hood_sensor_reach_time_s']:.2f}",
  1398. format_duration_mmss(hs["hood_sensor_reach_time_s"]),
  1399. "",
  1400. "",
  1401. "",
  1402. "PASS" if hs["memory_all_4_reached"] else f"{hs['memory_reached_count']}/4",
  1403. "" if hs["hood_memory_reach_time_s"] is None else f"{hs['hood_memory_reach_time_s']:.2f}",
  1404. format_duration_mmss(hs["hood_memory_reach_time_s"]),
  1405. str(rep["first_reached"]["total_post_target_samples"]),
  1406. str(exp["ptc_duty_percent"]),
  1407. str(exp["ssr_duty_percent"]),
  1408. str(exp["initial_fan_duty_percent"]),
  1409. str(exp["active_fan_duty_percent"]),
  1410. str(exp["fan_intervention_mode"]),
  1411. "" if exp["fan_intervened_elapsed_s"] is None else f"{exp['fan_intervened_elapsed_s']:.2f}",
  1412. "" if exp["fan_intervened_temp_c"] is None else f"{exp['fan_intervened_temp_c']:.1f}",
  1413. ])
  1414. )
  1415. return "\n".join(rows) + "\n"
  1416. def sync_to_backend(
  1417. self,
  1418. store: TemperatureCurveStore,
  1419. mapping: ChamberMappingConfig,
  1420. *,
  1421. backend_url: str | None = None,
  1422. timeout: float = 5.0,
  1423. ) -> dict[str, Any]:
  1424. """Push this thermal test session (summary + curve samples + mapping) to the 192.168.2.25 backend."""
  1425. import urllib.request
  1426. url = (backend_url or self.backend_url).rstrip("/") + "/api/runs"
  1427. payload = {
  1428. "report": self.summary(),
  1429. "mapping": mapping.to_dict(),
  1430. "samples": store.snapshot(),
  1431. }
  1432. body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
  1433. req = urllib.request.Request(
  1434. url,
  1435. data=body,
  1436. headers={"Content-Type": "application/json; charset=utf-8"},
  1437. method="POST",
  1438. )
  1439. with urllib.request.urlopen(req, timeout=timeout) as resp:
  1440. return json.loads(resp.read().decode("utf-8"))
  1441. # Embedded 16px bitmap font (ASCII 8x16 + Chinese UI characters 16x16) for dependency-free PNG rendering
  1442. _FONT16_B85 = (
  1443. 'c-nPYe{dUBeqTu&`6=F5D=8!^Tb5R2?Kq&|wXHZZk+o{;9=bNYrfu4~ch`1lTszmMAP5)4MM&Z>pnw5Ea~'
  1444. 'A;tLNQ0UONiUcK?n(GivRFTGgHsp{oxs|gQq06Gs8^vM`mvS*dhIX-|my-0Q()iU48Z0_rCA@zQ5j+gUH-'
  1445. '1mxDy1m8=Wylyy6_lW?`5wn5wFFBXU6H@`e|kg^nxBcZ~Na`{w;w~!|USUvDVc4_Ibpx)#4woz0sw8?x{e'
  1446. 'dK@sd$p)h)^>ZumhSsFP7sinz(x>&wS(hS`YZ?`xU0ar17G}ZAz6?Jd+|=r>g?uCyF&+wHD@Q;FYaWFWRk'
  1447. 'sj*E$qs^+W4&yHOBTmGv~RRD7o}IaR!WYO;`|r~x{m5WR{;${K_=UvRrSLWyjlKv_c;D;##WxeIy9ibLBG'
  1448. '4i8UG7K?5-W$l8tP|yL`Kn+71PU(fh)PX5`#N8C-?m)p3DrF@sxeBStDTW$hqH1o|*WJzOu{rKp$D+!yRN'
  1449. '{){mva%9rJPYqF*l1`@usb>6umF!!flb<vc=Nqh@h~h<)ooa9XasXr@#L7r=RH$YQXwEV1<&&)bM1X`1$7'
  1450. ')_4{-}Q#i*1MN40QK&PG6;mW4Mlr=_GI7KgeLVpNtv8aP~blukdw^~@bPFeTZeNEke;IL-(m4OzzDHdsOl'
  1451. '=W>Ygk|{lqWuv{pK{~%9ecz-#uq0K<#YM_CZ`Ti)?PGn`?7`j6KGd|_q&@nKmD&yKKX>Qz60%n!-o$aJ$n'
  1452. 'EB_K1H<^))rMy4qN@eJBJ7RcuQCXX{XIWc|6Vi9%C|zd%t7dNv<!yT=xFKV312`7*Np(werVLTkjog7)(R'
  1453. 'Q<Ia!sbn%lS$_@fC!c)!>1V~_!w*kV);OXjQ^`;WOv+lczd_d25#Tkt|1Q-%n7yPjO?(d)TWVY(WPKlg&~'
  1454. '+7@nFzew?F81}!W2USyON0dJG7D`2U;W3-`^6eZaRq0$*QzIe%(v&sX`kp?){b!|9}Hh7Xlx$me%T+S{Sp'
  1455. 'h366t>P8BfH6;hP-k5-T<8~}?dTC7QQT8SA7Wld3(Mr{eat&n$+gZ7A%lXl#6kRL#F3~~8nOPu&8jzDNjC'
  1456. 'hd9Wa}M&)^u?+B@_AfaiaNw`MlL}wDIB4!f1x9OdGk|xQPzEwwQj`wZRuN9J8Ppr6Au^egOMEM0b5_zv_S'
  1457. '(7@}M;#O{Euo@vx23^I;ZE9-@K6(nQ!&;SVXw62VsC5y}DsJJPVPhbap!tXMp9gtBs!1yX{69kHhU2xWaf'
  1458. 'g@y?xl*>BEk8J57uB!Gr9);zg2A0K45$XU|zLCG|%RwIHxSaJn#pVE2unk5nc32Ni@jvGpW>j;e9lE1-Yj'
  1459. 'y<8zc(zcWKqPhpMV!JDCT|cE0?3>0!*`?PfoP{N<=|*>#iE0YHnRniAXW;x4zHb#xdA;m-xS><J{L?5tBU'
  1460. 'uX!`L+ZsYoL%9S0ZAjnGz`?<p90CeKX7GY~`%iem#(9GhOni(;?^|obK4MEQ{5Cb$RVnhspiJzAq<G$gNI'
  1461. 'Tb_@I0XIpn?MOp;U>5k1yvf{B=8gPdMg13K`%5hAs}HLA;%?Ny-@n<Kt;3l8-i>-IT__6^%Q#+oPx_h(6J'
  1462. 'UR8;z$rd(un<J#DM9Nk+@F4SJ^ej=dN)N7exb%U}q4j)4TuYY>ir0%2Hq(AMY|2|;IDjZ!lQW-QXo=#0e!'
  1463. '&<DpFG7(>uREWyUO{)W+5)kz2dKGBPPT38_0|_$eReJ$+apvn((3}ia=EdW!AQy)esXJAt>PC{O3O;<#o?'
  1464. 'F_Zx9eTzpgyc;by44Hin>Jrx^&8RlQc=Un^H+E?KU4M`8b~;O5&WjOhK2QwLpAY09cnPaU;@*6s!g-5|SF'
  1465. 'h;V#?CB$CHyKh-Jw<w5zd=~sb7p#1>~`q$=gQhKYYF01u{eZGBx%$B_oQ%s9#0DWYy9pNMMfw(_DbmPd4&'
  1466. 'F43t51jX%_wfPV&%4BHrAy78yrz^MG6u<E!%qVCXDbYM?TNRTmUz&R<&v(nO9#EHP)dbV?CFWq%>{PS7?B'
  1467. '8p(ZDxv-CA-4{i3OHJ`JP;;i^GEf!dD90)o!ASZ0YUY19dL8g(Q|Bq{~jVUDNku9?;ypDd^ZMtAMWC%$5I'
  1468. '!obYXmBB-)WFn*rw5O*oGLWy#2t#JmLIG56gdPyr5?0V|I7KA4D2S4ZAQm!tZJH>O5}EZW1IiA?tGE?6FY'
  1469. 'prT>DaR@qFTa&mt+Pq_@ONsA^>{&b-SlDmrlXbcuX=zX+Aukn0Cy#Q1GXj(IMrvy+NCNdjmj2d$;8gbeaV'
  1470. '=O@`oRa*76$`4#^}U_u)ko#$o%G;^`(87dc7hvgxCpf*q&(udWgsM1()?b*lHrxi=3t=|yz6T2gk2M3B6s'
  1471. '7j_#3yh#s>q3teS-=BDViEWvfZk{U87wBzdmRE04L#SMd$Lt<wWL~$Tm~ZB$nB&Tt>F1aEJ&Ho8Rx>_!j?'
  1472. '>ET*wM)huWF-FAbmyo`1777BESg5{bAh&;LiO3Ys$uavrV?sCyYfzhr{DFglrT@EQz^ArdDF;Yl0L?)mqd'
  1473. 'VOfG0fx%fbF&lX6oCt*WRGDUx&JFC4I;?N2xoRERM95o5vAlHzvFMwNEaQvd|Fnax#uhRRv>k_g!4CGML_'
  1474. 'lm2^klhJ#IOnws__?2Hx=M3Z(XxyCz7peoBQH@yVn#{!AlKLIOos!GvS;|1;KSGk;>cO#cQv;(p;9?_agN'
  1475. 'IDSKo2gdhu=N!|RF^G#5c@4pe{w_lC&^l5YSp(sy{?v;;PdIG>*6L-#UyP8Ty=M{eYyljC^+GUX_i?UDl#'
  1476. 'U9Q3t_BpJ5{z{x2IMI3K)-wSDI1g)YhuY~KFW9T;=DK^ZVo*(a^+ru!`Z!hf`KHUE+d(dfV#|(9;#>O998'
  1477. 'Ofud$>^v@`9o_Lz32D;5xj60FiHqD-?dH>{v8$RS8#uyW~y=^|c<)EzZ1I>PMR>s$)$8>%o@&6#%75JuzE'
  1478. 'EYnj-sJUxgO)3d=_3#Ck?oK2Tbhg?|iVzIJjy$lm2|1xhOi4!q(7O$p&>1mYVrcf1JVvn8UD{e2LYdy3Wi'
  1479. 'nZih~bundSr>sj%xhe2aRe?N=Z)1Wjdu{DO?rCJH|IkU6P7^ckWV)LxG8bRSJ-cA?iV#hlK5v0W@dZxIhS'
  1480. 'rkN}C8@L33Cw1aJZ?W7C57(vgk4?V$3unN{WGcX+mvZKoTKWnWE8h&SDid54wq&EOvxL|=i6;B1{*MFlgP'
  1481. 'E=Hb<;}he0Q%sUEmcn`SOxIhrc<ra4nP-Koe7J9KDX5n)uCmz27zcnU6N~Z4ME4(gT(UYa=bjeG`KjZs<J'
  1482. 'Hiqf8fn)(Y~ApaL-<4%H#<8iQhVnR@W0Qd6d8uCr?%S&~&$<|QW6K5m@LfP+K&&}vqa<rVMw)Mfy&;sNs='
  1483. '%xw;*ZsicWXv5(?vNI<E%Na6doq!!Bq=eLE2BBh+sx-ZRe4@E5OgC6;IZB(CHfQ1?CGHYeO3k!k**Dm>R~'
  1484. '<PS<!`HkGHlR?EV+VN=*_6);5L-w3vpfn!B?hPQXIz`C$b<O)Dk0eJI+JE5W36BY7BcSvwD1yTjCaIF_ej'
  1485. '90^@<~V0LgKbt8HnK|j4!PXM8yNS4zhH%1V2?5U==U>HOLj+nlg+s+JK8amnkMHJG;$}=xAKM0yZPUC_`5'
  1486. 'X^X#j2J<Vl8K;q7zm2KYQ8S%L8D6u>5mu^6qJ^8t~~p$9eTKc8Q_aNv~tAM<Ok(|>7U**y#;%Ejt#d@T9g'
  1487. '*G-(uVK+t6YHT6~rk5%h1(p8S03xUU+3!S<MHU99_zz@aS@2zrY}x&YYaqgAm2_jIUMG<{WHMXZYkg5GJw'
  1488. 'On~JpzJpuMz@hGg4;a3KKEpR5VoyIQ+ol4RsOf&l0s{-%7eWS9SCC-+Ir$2L>=3;PAmOx@@5pEi${M+#L1'
  1489. '7zKJ92j;=%;q!#|u5V{&au3H?5hynf}aZCZ16iv<0q=AiF0*gq)W413~)92=KG8kSgyi3kW)K>Xv<rwV{F'
  1490. 'F>MXfS!n8DvptqXwiS5LjPgYV~Iq@EgbSbG<+HUqjo2vFM^^U_`0>=YKSgAhOtT1k$1~OCA)?J&%l;+|Q#'
  1491. 'AK3_vLg4GJ+aYPPi*^_imqgni!#kEE7gx$WwNA+7|ygm(>cCzpEHfQW#tvS3~{EBG;@%qSe9z>2|y=H>-#'
  1492. '~+)XV^wa3B-O1yl=k?AEjab&8}JF-efTh5#*sY`^n!{=7Ek9}DOG*pB)0#d&eeKR<-ZJo)qWrIDQ~AnR>7'
  1493. '6`UJ58Ks~z>+5mc#BVsYX)ajtRateoa`IxMtTjkARV5H^Le+5fj_Qu;w_o;jws!*P)sJnE;4wVtci?H=3z'
  1494. '5vo_?_8ybz^oT+S6-~v7XuuQc1!lD|D%QW^`dk<_9?dB|0dm!Zuu_PD-hgRFce4B~sY|<Pkk$y9l7y-)fC'
  1495. '?bWRskp}&qbn73~2s8>$eHC>Pd%M#27t)tsa$_e=>eU>0Zue^QPHm61K{6)>|+TR5q%^WpGOb8)D5Ut>}U'
  1496. 'HeKE098gISag{YsGAacBK<v6st2n8I{RkJcD95Bq8n0)5tZp|LvT#<@S%Zv6YMz$<{ULwDFs#Z$~ikrL1B'
  1497. 'b+MO+HkVb6-s^CIpzU?Z{eE4%7}ir_cG{tf$k_V3z%8{9WQ>)Ssx-8%-L3-2(Qx{Qs)WjM(o=>o%RH#eT~'
  1498. 'pBX%Z`EKRIS+==R^CaD7y61P-x6He9ZZ0I>c4pViT@YATfBZp9`ET0$14*Q2jCJPVUI0CQwz+%N3^GoZB1'
  1499. '?${vgYa7BZ$NXu{aKu6D25!uxx?CTU13A(y)pkJBTTvcs*W<gO=2J^~&g4&*`2EJ##&YsY3vIx^WaBjK?y'
  1500. 'uy`gjjDqlelEhp=-%BHFp)^7C~J1Huq(NfUd!{5PsuWnMhl~HBq7n=kEbq;`@d#YJvIk>?LmRIdr&Db7mZ'
  1501. 'j)Az+kS_u7KF-RpcHLA&7%vvdi+<dS&Hpm?RMG$1fZ8bS|1LZ3AP#OR!_3BHW68N0mO<3xNp%6hy}!ppi_'
  1502. ';5GYvOMWwAP1-Btae`4AuHci%|D))+u<yvqujl;NxRR7hno{axlR<u>y+B?7xo0L@;!^?b&fxQEtu(HRUF'
  1503. 't8c%^>Vl+9`aGwLXM&*0a9^UYPa-PO+o8x>edpr(vbJ|3hP5-tG)47v<_t5Hh#9Xa75K62KplZ%T{D}?BT'
  1504. ')FQo;}9$UBn!n+c{@x8{7*@EmpCvp0&M2N=MRhQ>i#AxF^Gbo4c~ri!46vBjZw9G<Pj0(<JX(PAZ8$P7P;'
  1505. 'AegmKnr<;*ZDvRaea?<E4OXV$a=gJ-BL>WO(GLXj%!lq`o@~9FteXxxmP#lU^c@$^&p?xMsYNRF^K2b9ti'
  1506. '3MZ680>~YEnfZ+NI<KX-(~t9+>3UAA8#G^o)Owg5b4&QU=^#Llp)*k$;F=Xc3$B|O+`kUg5lPl`gzki*=E'
  1507. '_gvlc*4pKG4bV5Pc2#={(bVe>*<hzm*_3%|9Q#~H{fW<{u=JS0j+h$FFy^YA_peC>_XE#6XMi{dN^OUZ0Z'
  1508. '2ET)VvG#VEMU~<7usM8ccZGwcAd;u*kvtXGd}tm)Z?Z}(Y;IBF6WW+o)%IzoR?#Z`X1~~vDmZJ`<9=DoM;'
  1509. '4+NMpf;K3kJkMk0;7l`>wHV5+_R#0XU!>6v;qYvbb?ksA3#nJI5+9@L!MV;+_1_t3f4*AEo<?Zpg0)I>#K'
  1510. 'r2l3w{JYv#1QMYQt&|>f;faV(K;{kIc@4Vrh_|Zg{*~xd_=sezeJbWXJdV24PhCP|u1eqXvwJPEI%>J3gO'
  1511. 'u|fZbnV_}!=+Q{+l|{7v~i;LW&0NT&Ayqwnbb@ULCjQOXQ3Ce;$pD8N4R4ea&f(*mYgQj1Q+=7xt8dgm*z'
  1512. 'K5Z=T(CMw5A!SGBA%&f~INKHum`PRTyAdv<ho=d3on$@F3icL06NLNr8VN%Wd{fH5M{b5T*Mr?_nt#17Gu'
  1513. '19d!b!Mw0X?E>nA5|V+~$wNhjx7$sw!c`KLhzUDJu~THA*I0Z~!TUY1i#|&A&9=%ZaP#XWb{4G<z(P1-f!'
  1514. 'oZ)TyQRUzAGM1hPYuKK`*mq*#?o0EW<u{?5No}21_#r^nFaP*B@gWE^(l;74{k~<8DZbo%ToKED$S36T6o'
  1515. '?Gwu5v;vORmVW>0HnQ4F?Kh2I|`J^`Mi*@yF?9)zjF^mO3Neu;m;@L)s&I`Q8??lS)8XHP$>1aCoEe#U&^'
  1516. '{1G|bK0_l_`pLvDyzt#9;@P+*!34*XXh$m*sI=aIw0tHfHc#i5P72<!r_j;WP=t(C}-qF4q6Oo+Kgw$V|r'
  1517. ')0LF3m?oMu~+E|UoI*ARlvH}@?F+Wv)dNIAq>8}w4+|CUjshxCvg#!k{>^yodYor$Ozm7-q&=#}?aq{BHy'
  1518. 'r~7Y&b9fFtaxzlq)V5`)e8lT-KG%9YA&zeu_b&yiu=}Y77PcHr-XV7Y=oi&y=t1wt@Q#^^N*99<%JgBiam'
  1519. 'Je1ozT>srUrW-`pI#boqKmeD*L}n<>tvZ{Z~X>M-nF>=veFjP@=Uhw+Y`+IRwpo)BjQu{cnj-(97%ozT>1'
  1520. '@fE0B3wOe}#b3=Ue3YTNw{~vZP_jm'
  1521. )
  1522. _FONT16_CACHE: dict[str, tuple[int, bytes]] | None = None
  1523. def _get_font16() -> dict[str, tuple[int, bytes]]:
  1524. global _FONT16_CACHE
  1525. if _FONT16_CACHE is not None:
  1526. return _FONT16_CACHE
  1527. raw = zlib.decompress(base64.b85decode(_FONT16_B85))
  1528. table: dict[str, tuple[int, bytes]] = {}
  1529. pos = 0
  1530. while pos < len(raw):
  1531. cb_len = raw[pos]
  1532. w = raw[pos + 1]
  1533. pos += 2
  1534. ch = raw[pos : pos + cb_len].decode("utf-8")
  1535. pos += cb_len
  1536. byte_len = 16 if w == 8 else 32
  1537. bits = raw[pos : pos + byte_len]
  1538. pos += byte_len
  1539. table[ch] = (w, bits)
  1540. _FONT16_CACHE = table
  1541. return table
  1542. def _hex_rgb(hex_color: str) -> tuple[int, int, int]:
  1543. c = hex_color.lstrip("#")
  1544. return (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16))
  1545. class _PurePngCanvas:
  1546. """Lightweight pure-Python RGB rasterizer + PNG encoder for dependency-free curve image printing."""
  1547. def __init__(self, width: int, height: int, bg: tuple[int, int, int] = (248, 250, 252)):
  1548. self.width = int(width)
  1549. self.height = int(height)
  1550. self.buf = bytearray(bytes(bg) * (self.width * self.height))
  1551. self.font = _get_font16()
  1552. def set_px(self, x: int, y: int, rgb: tuple[int, int, int]) -> None:
  1553. if 0 <= x < self.width and 0 <= y < self.height:
  1554. off = (y * self.width + x) * 3
  1555. self.buf[off] = rgb[0]
  1556. self.buf[off + 1] = rgb[1]
  1557. self.buf[off + 2] = rgb[2]
  1558. def fill_rect(self, x0: int, y0: int, x1: int, y1: int, rgb: tuple[int, int, int]) -> None:
  1559. xa = max(0, min(x0, x1))
  1560. xb = min(self.width - 1, max(x0, x1))
  1561. ya = max(0, min(y0, y1))
  1562. yb = min(self.height - 1, max(y0, y1))
  1563. if xa > xb or ya > yb:
  1564. return
  1565. row_bytes = bytes(rgb) * (xb - xa + 1)
  1566. w3 = self.width * 3
  1567. start_x = xa * 3
  1568. end_x = (xb + 1) * 3
  1569. for y in range(ya, yb + 1):
  1570. base = y * w3
  1571. self.buf[base + start_x : base + end_x] = row_bytes
  1572. def draw_rect(self, x0: int, y0: int, x1: int, y1: int, rgb: tuple[int, int, int], thickness: int = 1) -> None:
  1573. for t in range(thickness):
  1574. self.fill_rect(x0 + t, y0 + t, x1 - t, y0 + t, rgb)
  1575. self.fill_rect(x0 + t, y1 - t, x1 - t, y1 - t, rgb)
  1576. self.fill_rect(x0 + t, y0 + t, x0 + t, y1 - t, rgb)
  1577. self.fill_rect(x1 - t, y0 + t, x1 - t, y1 - t, rgb)
  1578. def draw_line(
  1579. self,
  1580. x0: int,
  1581. y0: int,
  1582. x1: int,
  1583. y1: int,
  1584. rgb: tuple[int, int, int],
  1585. thickness: int = 1,
  1586. dashed: bool = False,
  1587. ) -> None:
  1588. dx = abs(x1 - x0)
  1589. dy = -abs(y1 - y0)
  1590. sx = 1 if x0 < x1 else -1
  1591. sy = 1 if y0 < y1 else -1
  1592. err = dx + dy
  1593. step = 0
  1594. r = max(0, thickness - 1)
  1595. while True:
  1596. if not dashed or (step // 6) % 2 == 0:
  1597. if r == 0:
  1598. self.set_px(x0, y0, rgb)
  1599. else:
  1600. self.fill_rect(x0 - r // 2, y0 - r // 2, x0 + (r + 1) // 2, y0 + (r + 1) // 2, rgb)
  1601. if x0 == x1 and y0 == y1:
  1602. break
  1603. e2 = 2 * err
  1604. if e2 >= dy:
  1605. err += dy
  1606. x0 += sx
  1607. if e2 <= dx:
  1608. err += dx
  1609. y0 += sy
  1610. step += 1
  1611. def draw_marker(self, cx: int, cy: int, rgb: tuple[int, int, int], radius: int = 3, diamond: bool = False) -> None:
  1612. for dy in range(-radius, radius + 1):
  1613. for dx in range(-radius, radius + 1):
  1614. if diamond:
  1615. if abs(dx) + abs(dy) <= radius + 1:
  1616. self.set_px(cx + dx, cy + dy, rgb)
  1617. else:
  1618. if dx * dx + dy * dy <= radius * radius + 1:
  1619. self.set_px(cx + dx, cy + dy, rgb)
  1620. def text_width(self, text: str) -> int:
  1621. total = 0
  1622. for ch in str(text):
  1623. g = self.font.get(ch)
  1624. total += g[0] if g else (8 if ord(ch) < 128 else 16)
  1625. return total
  1626. def draw_text(self, x: int, y: int, text: str, rgb: tuple[int, int, int], align: str = "left") -> None:
  1627. s = str(text)
  1628. w_total = self.text_width(s)
  1629. cur_x = x
  1630. if align == "center":
  1631. cur_x = x - w_total // 2
  1632. elif align == "right":
  1633. cur_x = x - w_total
  1634. for ch in s:
  1635. g = self.font.get(ch)
  1636. if g is None:
  1637. g = self.font.get("?")
  1638. if g is None:
  1639. cur_x += 8
  1640. continue
  1641. gw, bits = g
  1642. if gw == 8:
  1643. for row in range(16):
  1644. b = bits[row]
  1645. if not b:
  1646. continue
  1647. py = y + row
  1648. for col in range(8):
  1649. if b & (1 << (7 - col)):
  1650. self.set_px(cur_x + col, py, rgb)
  1651. else:
  1652. for row in range(16):
  1653. b = (bits[row * 2] << 8) | bits[row * 2 + 1]
  1654. if not b:
  1655. continue
  1656. py = y + row
  1657. for col in range(16):
  1658. if b & (1 << (15 - col)):
  1659. self.set_px(cur_x + col, py, rgb)
  1660. cur_x += gw
  1661. def to_png_bytes(self) -> bytes:
  1662. w, h = self.width, self.height
  1663. stride = w * 3
  1664. raw_rows = bytearray((stride + 1) * h)
  1665. for y in range(h):
  1666. dst = y * (stride + 1)
  1667. raw_rows[dst] = 0 # Filter type 0 (None)
  1668. src = y * stride
  1669. raw_rows[dst + 1 : dst + 1 + stride] = self.buf[src : src + stride]
  1670. def chunk(tag: bytes, data: bytes) -> bytes:
  1671. crc = zlib.crc32(tag + data) & 0xFFFFFFFF
  1672. return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
  1673. ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
  1674. idat = zlib.compress(bytes(raw_rows), 6)
  1675. return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")
  1676. def _compute_chamber_plot_traces(
  1677. series: dict[str, Any],
  1678. mode: str = "detail_and_avg",
  1679. ) -> list[dict[str, Any]]:
  1680. """Build ordered curve traces for one chamber: Memory (BMC) and Sensor (CT) curves."""
  1681. traces: list[dict[str, Any]] = []
  1682. if mode in ("detail_and_avg", "detail_only"):
  1683. for idx, ch in enumerate(series["bmc_channels"]):
  1684. vals = series["bmc_series"].get(ch, [])
  1685. if any(v is not None for v in vals):
  1686. traces.append({
  1687. "label": f"BMC{ch}",
  1688. "values": vals,
  1689. "color": BMC_CURVE_COLORS[idx % len(BMC_CURVE_COLORS)],
  1690. "width": 1,
  1691. "dashed": False,
  1692. "diamond": False,
  1693. "kind": "bmc",
  1694. })
  1695. if mode in ("detail_and_avg", "avg_only"):
  1696. if any(v is not None for v in series["bmc_avg"]):
  1697. traces.append({
  1698. "label": "内存均温",
  1699. "values": series["bmc_avg"],
  1700. "color": BMC_AVG_COLOR,
  1701. "width": 2,
  1702. "dashed": False,
  1703. "diamond": False,
  1704. "kind": "bmc_avg",
  1705. })
  1706. if mode == "avg_only" and any(v is not None for v in series["bmc_max"]):
  1707. traces.append({
  1708. "label": "内存最高",
  1709. "values": series["bmc_max"],
  1710. "color": BMC_MAX_COLOR,
  1711. "width": 1,
  1712. "dashed": True,
  1713. "diamond": False,
  1714. "kind": "bmc_max",
  1715. })
  1716. # Sensor (CT) traces are always drawn prominently so memory vs sensor comparison is clear
  1717. for idx, ch in enumerate(series["ct_channels"]):
  1718. vals = series["ct_series"].get(ch, [])
  1719. if any(v is not None for v in vals) or mode != "avg_only":
  1720. traces.append({
  1721. "label": ct_channel_label(ch, short=True),
  1722. "values": vals,
  1723. "color": CT_CURVE_COLORS[idx % len(CT_CURVE_COLORS)],
  1724. "width": 2,
  1725. "dashed": True,
  1726. "diamond": True,
  1727. "kind": "ct",
  1728. })
  1729. if mode == "avg_only" and len(series["ct_channels"]) > 1 and any(v is not None for v in series["ct_avg"]):
  1730. traces.append({
  1731. "label": "Sensor均温",
  1732. "values": series["ct_avg"],
  1733. "color": CT_AVG_COLOR,
  1734. "width": 2,
  1735. "dashed": False,
  1736. "diamond": True,
  1737. "kind": "ct_avg",
  1738. })
  1739. return traces
  1740. def _y_axis_bounds(traces: list[dict[str, Any]], target_temp_c: float | None = None) -> tuple[float, float]:
  1741. vals = [float(v) for tr in traces for v in tr["values"] if v is not None]
  1742. if target_temp_c is not None:
  1743. vals.append(float(target_temp_c))
  1744. if not vals:
  1745. return (0.0, 100.0)
  1746. lo = min(vals)
  1747. hi = max(vals)
  1748. span = max(8.0, hi - lo)
  1749. y_min = max(0.0, math.floor((lo - span * 0.15) / 5.0) * 5.0)
  1750. y_max = min(255.0, math.ceil((hi + span * 0.15) / 5.0) * 5.0)
  1751. if y_max - y_min < 10.0:
  1752. y_max = min(255.0, y_min + 10.0)
  1753. return (y_min, y_max)
  1754. def render_chamber_curves_png(
  1755. store: TemperatureCurveStore,
  1756. mapping: ChamberMappingConfig,
  1757. *,
  1758. product: str = "6400-v2",
  1759. board: str = "6400V2.0",
  1760. mode: str = "detail_and_avg",
  1761. max_points: int = 0,
  1762. ignore_zero_ct: bool = False,
  1763. thermal_session: ThermalTestSession | None = None,
  1764. width: int = 1600,
  1765. height: int = 1080,
  1766. ) -> bytes:
  1767. """Render all 4 chambers' Memory (BMC) and Sensor (CT) temperature curves into a high-resolution PNG."""
  1768. canvas = _PurePngCanvas(width, height, bg=(244, 247, 251))
  1769. # Header bar
  1770. canvas.fill_rect(0, 0, width - 1, 54, (21, 50, 89))
  1771. now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  1772. pts_all = store.snapshot(max_points=max_points)
  1773. u6_str = "--"
  1774. if pts_all and pts_all[-1]["ct"] and pts_all[-1]["ct"][0] is not None:
  1775. u6_str = f"{pts_all[-1]['ct'][0]}°C"
  1776. title = f"{board} ({product}) — 四腔体内存温度(BMC)与Sensor温度(CT)曲线图"
  1777. sub = f"导出时间: {now_str} | 采样点数: {len(pts_all)} | U6本地(CT0): {u6_str}"
  1778. if thermal_session is not None:
  1779. rep = thermal_session.summary()
  1780. hs = rep["hood_summary"]
  1781. sub += (
  1782. f" | 高温罩通过温度>={thermal_session.overall_pass_min_temp_c:.0f}°C "
  1783. f"| Sensor达标:{hs['sensor_reached_count']}/4({format_duration_mmss(hs['hood_sensor_reach_time_s'])}) "
  1784. f"内存达标:{hs['memory_reached_count']}/4({format_duration_mmss(hs['hood_memory_reach_time_s'])})"
  1785. )
  1786. canvas.draw_text(20, 10, title, (255, 255, 255))
  1787. canvas.draw_text(20, 31, sub, (205, 224, 247))
  1788. pad_x = 16
  1789. pad_y = 66
  1790. cell_w = (width - pad_x * 3) // 2
  1791. cell_h = (height - pad_y - pad_x * 2) // 2
  1792. for idx, cid in enumerate(CHAMBER_IDS):
  1793. col = idx % 2
  1794. row = idx // 2
  1795. cx0 = pad_x + col * (cell_w + pad_x)
  1796. cy0 = pad_y + row * (cell_h + pad_x)
  1797. cx1 = cx0 + cell_w
  1798. cy1 = cy0 + cell_h
  1799. # Card background & border
  1800. canvas.fill_rect(cx0, cy0, cx1, cy1, (255, 255, 255))
  1801. canvas.draw_rect(cx0, cy0, cx1, cy1, (203, 213, 225), thickness=2)
  1802. canvas.fill_rect(cx0 + 2, cy0 + 2, cx1 - 2, cy0 + 46, (238, 243, 249))
  1803. series = store.chamber_series(mapping, cid, max_points=max_points, ignore_zero_ct=ignore_zero_ct)
  1804. bmc_spec = format_channel_spec(series["bmc_channels"]) or "无"
  1805. ct_spec = format_channel_spec(series["ct_channels"]) or "无"
  1806. ch_target_c: float | None = None
  1807. reach_badge = ""
  1808. if thermal_session is not None:
  1809. st_c = thermal_session.chamber_stats.get(cid, {})
  1810. ch_target_c = float(st_c.get("effective_target_c", 70.0))
  1811. s_t = format_duration_mmss(st_c.get("sensor_time_to_target_s"))
  1812. m_t = format_duration_mmss(st_c.get("memory_time_to_target_s"))
  1813. reach_badge = f" [目标{ch_target_c:.0f}°C | Sensor达标:{s_t} | 内存达标:{m_t}]"
  1814. hdr_left = f"{series['name']} [内存BMC: {bmc_spec} | Sensor CT: {ct_spec}]{reach_badge}"
  1815. canvas.draw_text(cx0 + 12, cy0 + 7, hdr_left, (15, 39, 71))
  1816. # Latest reading summary
  1817. latest_b = next((v for v in reversed(series["bmc_avg"]) if v is not None), None)
  1818. latest_c_parts = []
  1819. for ch in series["ct_channels"]:
  1820. v_list = series["ct_series"].get(ch, [])
  1821. v_last = next((v for v in reversed(v_list) if v is not None), None)
  1822. latest_c_parts.append(f"CT{ch}:{v_last}°C" if v_last is not None else f"CT{ch}:--")
  1823. stat_line = (
  1824. f"当前内存均温: {latest_b:.1f}°C" if latest_b is not None else "当前内存均温: --(无有效数据)"
  1825. ) + " | Sensor: " + (", ".join(latest_c_parts) if latest_c_parts else "无")
  1826. canvas.draw_text(cx0 + 12, cy0 + 26, stat_line, (65, 85, 110))
  1827. # Plot box
  1828. px0 = cx0 + 54
  1829. py0 = cy0 + 58
  1830. px1 = cx1 - 182
  1831. py1 = cy1 - 36
  1832. pw = max(40, px1 - px0)
  1833. ph = max(40, py1 - py0)
  1834. canvas.fill_rect(px0, py0, px1, py1, (252, 253, 255))
  1835. canvas.draw_rect(px0, py0, px1, py1, (180, 194, 210), thickness=1)
  1836. traces = _compute_chamber_plot_traces(series, mode=mode)
  1837. y_min, y_max = _y_axis_bounds(traces, target_temp_c=ch_target_c)
  1838. # Horizontal grid lines & Y labels
  1839. for step_i in range(6):
  1840. frac = step_i / 5.0
  1841. val_y = y_min + (y_max - y_min) * frac
  1842. gy = int(round(py1 - frac * ph))
  1843. if 0 < step_i < 5:
  1844. canvas.draw_line(px0 + 1, gy, px1 - 1, gy, (226, 232, 240), thickness=1, dashed=True)
  1845. canvas.draw_text(px0 - 6, gy - 8, f"{int(round(val_y))}°C", (90, 105, 120), align="right")
  1846. # Draw target temperature line if configured
  1847. if ch_target_c is not None and y_min <= ch_target_c <= y_max:
  1848. ty = int(round(py1 - ((ch_target_c - y_min) / max(1e-6, y_max - y_min)) * ph))
  1849. canvas.draw_line(px0 + 1, ty, px1 - 1, ty, (217, 119, 6), thickness=2, dashed=True)
  1850. canvas.draw_text(px1 - 6, max(py0 + 2, ty - 16), f"目标 {ch_target_c:.0f}°C", (180, 83, 9), align="right")
  1851. # X axis labels & vertical grid
  1852. n_pts = series["sample_count"]
  1853. elapsed = series["elapsed"]
  1854. t_span = max(1.0, (elapsed[-1] - elapsed[0]) if len(elapsed) >= 2 else 1.0)
  1855. for step_x in range(5):
  1856. fx = step_x / 4.0
  1857. gx = int(round(px0 + fx * pw))
  1858. if 0 < step_x < 4:
  1859. canvas.draw_line(gx, py0 + 1, gx, py1 - 1, (232, 237, 243), thickness=1, dashed=True)
  1860. if n_pts >= 2:
  1861. idx_pt = min(n_pts - 1, int(round(fx * (n_pts - 1))))
  1862. lbl_x = f"{elapsed[idx_pt]:.0f}s"
  1863. elif n_pts == 1 and step_x == 2:
  1864. lbl_x = series["time_labels"][0]
  1865. else:
  1866. lbl_x = f"{int(fx * 60)}s" if n_pts == 0 else ""
  1867. if lbl_x:
  1868. canvas.draw_text(gx, py1 + 8, lbl_x, (90, 105, 120), align="center")
  1869. # Draw curves
  1870. has_any_point = False
  1871. for tr in traces:
  1872. rgb = _hex_rgb(tr["color"])
  1873. pts_xy: list[tuple[int, int]] = []
  1874. vals = tr["values"]
  1875. for i, v in enumerate(vals):
  1876. if v is None:
  1877. continue
  1878. if n_pts <= 1:
  1879. x = px0 + pw // 2
  1880. else:
  1881. x = int(round(px0 + ((elapsed[i] - elapsed[0]) / t_span) * pw)) if elapsed[-1] > elapsed[0] else int(round(px0 + (i / (n_pts - 1)) * pw))
  1882. y = int(round(py1 - ((float(v) - y_min) / max(1e-6, y_max - y_min)) * ph))
  1883. y = max(py0 + 1, min(py1 - 1, y))
  1884. pts_xy.append((x, y))
  1885. if pts_xy:
  1886. has_any_point = True
  1887. for k in range(len(pts_xy) - 1):
  1888. canvas.draw_line(
  1889. pts_xy[k][0],
  1890. pts_xy[k][1],
  1891. pts_xy[k + 1][0],
  1892. pts_xy[k + 1][1],
  1893. rgb,
  1894. thickness=tr["width"],
  1895. dashed=tr["dashed"],
  1896. )
  1897. marker_stride = max(1, len(pts_xy) // 20)
  1898. for k, (mx, my) in enumerate(pts_xy):
  1899. if k == 0 or k == len(pts_xy) - 1 or k % marker_stride == 0:
  1900. canvas.draw_marker(mx, my, rgb, radius=3 if tr["width"] >= 2 else 2, diamond=tr["diamond"])
  1901. if not has_any_point:
  1902. canvas.draw_text(
  1903. px0 + pw // 2,
  1904. py0 + ph // 2 - 8,
  1905. "等待 0x42 温度数据或导入日志生成曲线...",
  1906. (140, 155, 175),
  1907. align="center",
  1908. )
  1909. # Right-side Legend panel
  1910. lx0 = px1 + 10
  1911. ly = py0 + 2
  1912. canvas.draw_text(lx0, ly, "图例 / 最新值", (40, 60, 85))
  1913. ly += 20
  1914. for tr in traces[:14]:
  1915. rgb = _hex_rgb(tr["color"])
  1916. last_v = next((v for v in reversed(tr["values"]) if v is not None), None)
  1917. v_txt = f"{last_v:.1f}°C" if isinstance(last_v, float) else (f"{last_v}°C" if last_v is not None else "--")
  1918. canvas.draw_line(lx0, ly + 8, lx0 + 16, ly + 8, rgb, thickness=max(2, tr["width"]), dashed=tr["dashed"])
  1919. canvas.draw_marker(lx0 + 8, ly + 8, rgb, radius=2, diamond=tr["diamond"])
  1920. canvas.draw_text(lx0 + 20, ly, f"{tr['label']}:{v_txt}", rgb)
  1921. ly += 18
  1922. if ly + 18 > py1:
  1923. break
  1924. return canvas.to_png_bytes()
  1925. def render_chamber_curves_svg(
  1926. store: TemperatureCurveStore,
  1927. mapping: ChamberMappingConfig,
  1928. *,
  1929. product: str = "6400-v2",
  1930. board: str = "6400V2.0",
  1931. mode: str = "detail_and_avg",
  1932. max_points: int = 0,
  1933. ignore_zero_ct: bool = False,
  1934. thermal_session: ThermalTestSession | None = None,
  1935. width: int = 1600,
  1936. height: int = 1080,
  1937. ) -> str:
  1938. """Render all 4 chambers' Memory (BMC) and Sensor (CT) temperature curves into a vector SVG."""
  1939. def esc(s: Any) -> str:
  1940. return (
  1941. str(s)
  1942. .replace("&", "&amp;")
  1943. .replace("<", "&lt;")
  1944. .replace(">", "&gt;")
  1945. .replace('"', "&quot;")
  1946. )
  1947. now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  1948. pts_all = store.snapshot(max_points=max_points)
  1949. u6_str = f"{pts_all[-1]['ct'][0]}°C" if (pts_all and pts_all[-1]["ct"] and pts_all[-1]["ct"][0] is not None) else "--"
  1950. sub_extra = ""
  1951. if thermal_session is not None:
  1952. rep = thermal_session.summary()
  1953. hs = rep["hood_summary"]
  1954. sub_extra = (
  1955. f" | 高温罩通过温度>={thermal_session.overall_pass_min_temp_c:.0f}°C "
  1956. f"| Sensor达标:{hs['sensor_reached_count']}/4({format_duration_mmss(hs['hood_sensor_reach_time_s'])}) "
  1957. f"内存达标:{hs['memory_reached_count']}/4({format_duration_mmss(hs['hood_memory_reach_time_s'])})"
  1958. )
  1959. lines = [
  1960. f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" font-family="Microsoft YaHei, Noto Sans CJK SC, Consolas, sans-serif">',
  1961. f' <rect width="{width}" height="{height}" fill="#F4F7FB"/>',
  1962. f' <rect width="{width}" height="54" fill="#153259"/>',
  1963. f' <text x="20" y="24" fill="#FFFFFF" font-size="16" font-weight="bold">{esc(board)} ({esc(product)}) — 四腔体内存温度(BMC)与Sensor温度(CT)曲线图</text>',
  1964. f' <text x="20" y="45" fill="#CDE0F7" font-size="12">导出时间: {esc(now_str)} | 采样点数: {len(pts_all)} | U6本地(CT0): {esc(u6_str)}{esc(sub_extra)}</text>',
  1965. ]
  1966. pad_x = 16
  1967. pad_y = 66
  1968. cell_w = (width - pad_x * 3) // 2
  1969. cell_h = (height - pad_y - pad_x * 2) // 2
  1970. for idx, cid in enumerate(CHAMBER_IDS):
  1971. col = idx % 2
  1972. row = idx // 2
  1973. cx0 = pad_x + col * (cell_w + pad_x)
  1974. cy0 = pad_y + row * (cell_h + pad_x)
  1975. series = store.chamber_series(mapping, cid, max_points=max_points, ignore_zero_ct=ignore_zero_ct)
  1976. bmc_spec = format_channel_spec(series["bmc_channels"]) or "无"
  1977. ct_spec = format_channel_spec(series["ct_channels"]) or "无"
  1978. ch_target_c: float | None = None
  1979. reach_badge = ""
  1980. if thermal_session is not None:
  1981. st_c = thermal_session.chamber_stats.get(cid, {})
  1982. ch_target_c = float(st_c.get("effective_target_c", 70.0))
  1983. s_t = format_duration_mmss(st_c.get("sensor_time_to_target_s"))
  1984. m_t = format_duration_mmss(st_c.get("memory_time_to_target_s"))
  1985. reach_badge = f" [目标{ch_target_c:.0f}°C | Sensor达标:{s_t} | 内存达标:{m_t}]"
  1986. latest_b = next((v for v in reversed(series["bmc_avg"]) if v is not None), None)
  1987. latest_c_parts = [
  1988. f"CT{ch}:{next((v for v in reversed(series['ct_series'].get(ch, [])) if v is not None), '--')}°C"
  1989. for ch in series["ct_channels"]
  1990. ]
  1991. stat_line = (
  1992. f"当前内存均温: {latest_b:.1f}°C" if latest_b is not None else "当前内存均温: --(无有效数据)"
  1993. ) + " | Sensor: " + (", ".join(latest_c_parts) if latest_c_parts else "无")
  1994. lines.append(f' <rect x="{cx0}" y="{cy0}" width="{cell_w}" height="{cell_h}" fill="#FFFFFF" stroke="#CBD5E1" stroke-width="2" rx="4"/>')
  1995. lines.append(f' <rect x="{cx0+2}" y="{cy0+2}" width="{cell_w-4}" height="44" fill="#EEF3F9"/>')
  1996. lines.append(f' <text x="{cx0+12}" y="{cy0+20}" fill="#0F2747" font-size="14" font-weight="bold">{esc(series["name"])} [内存BMC: {esc(bmc_spec)} | Sensor CT: {esc(ct_spec)}]{esc(reach_badge)}</text>')
  1997. lines.append(f' <text x="{cx0+12}" y="{cy0+39}" fill="#41556E" font-size="12">{esc(stat_line)}</text>')
  1998. px0 = cx0 + 54
  1999. py0 = cy0 + 58
  2000. px1 = cx0 + cell_w - 182
  2001. py1 = cy0 + cell_h - 36
  2002. pw = max(40, px1 - px0)
  2003. ph = max(40, py1 - py0)
  2004. lines.append(f' <rect x="{px0}" y="{py0}" width="{pw}" height="{ph}" fill="#FCFDFF" stroke="#B4C2D2" stroke-width="1"/>')
  2005. traces = _compute_chamber_plot_traces(series, mode=mode)
  2006. y_min, y_max = _y_axis_bounds(traces, target_temp_c=ch_target_c)
  2007. for step_i in range(6):
  2008. frac = step_i / 5.0
  2009. val_y = y_min + (y_max - y_min) * frac
  2010. gy = round(py1 - frac * ph, 1)
  2011. if 0 < step_i < 5:
  2012. lines.append(f' <line x1="{px0}" y1="{gy}" x2="{px1}" y2="{gy}" stroke="#E2E8F0" stroke-dasharray="4,4"/>')
  2013. lines.append(f' <text x="{px0-6}" y="{gy+4}" fill="#5A6978" font-size="11" text-anchor="end">{int(round(val_y))}°C</text>')
  2014. if ch_target_c is not None and y_min <= ch_target_c <= y_max:
  2015. ty = round(py1 - ((ch_target_c - y_min) / max(1e-6, y_max - y_min)) * ph, 1)
  2016. lines.append(f' <line x1="{px0}" y1="{ty}" x2="{px1}" y2="{ty}" stroke="#D97706" stroke-width="2" stroke-dasharray="6,4"/>')
  2017. lines.append(f' <text x="{px1-6}" y="{max(py0+12, ty-4)}" fill="#B45309" font-size="11" font-weight="bold" text-anchor="end">目标 {ch_target_c:.0f}°C</text>')
  2018. n_pts = series["sample_count"]
  2019. elapsed = series["elapsed"]
  2020. t_span = max(1.0, (elapsed[-1] - elapsed[0]) if len(elapsed) >= 2 else 1.0)
  2021. for step_x in range(5):
  2022. fx = step_x / 4.0
  2023. gx = round(px0 + fx * pw, 1)
  2024. if 0 < step_x < 4:
  2025. lines.append(f' <line x1="{gx}" y1="{py0}" x2="{gx}" y2="{py1}" stroke="#E8EDF3" stroke-dasharray="4,4"/>')
  2026. if n_pts >= 2:
  2027. idx_pt = min(n_pts - 1, int(round(fx * (n_pts - 1))))
  2028. lbl_x = f"{elapsed[idx_pt]:.0f}s"
  2029. elif n_pts == 1 and step_x == 2:
  2030. lbl_x = series["time_labels"][0]
  2031. else:
  2032. lbl_x = f"{int(fx * 60)}s" if n_pts == 0 else ""
  2033. if lbl_x:
  2034. lines.append(f' <text x="{gx}" y="{py1+18}" fill="#5A6978" font-size="11" text-anchor="middle">{esc(lbl_x)}</text>')
  2035. has_any = False
  2036. for tr in traces:
  2037. pts_xy = []
  2038. for i, v in enumerate(tr["values"]):
  2039. if v is None:
  2040. continue
  2041. if n_pts <= 1:
  2042. x = px0 + pw / 2.0
  2043. else:
  2044. x = px0 + ((elapsed[i] - elapsed[0]) / t_span) * pw if elapsed[-1] > elapsed[0] else px0 + (i / (n_pts - 1)) * pw
  2045. y = py1 - ((float(v) - y_min) / max(1e-6, y_max - y_min)) * ph
  2046. y = max(py0 + 1, min(py1 - 1, y))
  2047. pts_xy.append((round(x, 1), round(y, 1)))
  2048. if pts_xy:
  2049. has_any = True
  2050. dash = ' stroke-dasharray="6,4"' if tr["dashed"] else ""
  2051. if len(pts_xy) >= 2:
  2052. pts_str = " ".join(f"{x},{y}" for x, y in pts_xy)
  2053. lines.append(f' <polyline fill="none" stroke="{tr["color"]}" stroke-width="{tr["width"]+0.5}"{dash} points="{pts_str}"/>')
  2054. for x, y in pts_xy[::max(1, len(pts_xy) // 20)]:
  2055. lines.append(f' <circle cx="{x}" cy="{y}" r="3" fill="{tr["color"]}"/>')
  2056. if not has_any:
  2057. lines.append(f' <text x="{px0 + pw/2}" y="{py0 + ph/2}" fill="#8C9BAF" font-size="13" text-anchor="middle">等待 0x42 温度数据或导入日志生成曲线...</text>')
  2058. lx0 = px1 + 10
  2059. ly = py0 + 14
  2060. lines.append(f' <text x="{lx0}" y="{ly}" fill="#283C55" font-size="12" font-weight="bold">图例 / 最新值</text>')
  2061. ly += 18
  2062. for tr in traces[:14]:
  2063. last_v = next((v for v in reversed(tr["values"]) if v is not None), None)
  2064. v_txt = f"{last_v:.1f}°C" if isinstance(last_v, float) else (f"{last_v}°C" if last_v is not None else "--")
  2065. lines.append(f' <text x="{lx0}" y="{ly}" fill="{tr["color"]}" font-size="11">● {esc(tr["label"])}: {esc(v_txt)}</text>')
  2066. ly += 16
  2067. if ly > py1:
  2068. break
  2069. lines.append("</svg>\n")
  2070. return "\n".join(lines)
  2071. def export_chamber_curves_csv(
  2072. store: TemperatureCurveStore,
  2073. mapping: ChamberMappingConfig,
  2074. *,
  2075. max_points: int = 0,
  2076. ignore_zero_ct: bool = False,
  2077. ) -> str:
  2078. """Export per-chamber mapped temperature series and raw channels as CSV."""
  2079. pts = store.snapshot(max_points=max_points)
  2080. t0 = pts[0]["timestamp"] if pts else 0.0
  2081. headers = ["sample_index", "time_label", "elapsed_s"]
  2082. for cid in CHAMBER_IDS:
  2083. cfg = mapping.chambers[cid]
  2084. headers.append(f"C{cid}_BMC_AVG")
  2085. for ch in cfg["bmc"]:
  2086. headers.append(f"C{cid}_BMC{ch}")
  2087. headers.append(f"C{cid}_CT_AVG")
  2088. for ch in cfg["ct"]:
  2089. headers.append(f"C{cid}_CT{ch}")
  2090. headers.append("U6_LOCAL_CT0")
  2091. rows = [",".join(headers)]
  2092. for idx, p in enumerate(pts):
  2093. row = [str(idx + 1), str(p["time_label"]), f"{p['timestamp'] - t0:.2f}"]
  2094. for cid in CHAMBER_IDS:
  2095. cfg = mapping.chambers[cid]
  2096. b_vals = [p["bmc"][ch] for ch in cfg["bmc"] if ch < len(p["bmc"]) and p["bmc"][ch] is not None]
  2097. row.append(f"{sum(b_vals)/len(b_vals):.2f}" if b_vals else "")
  2098. for ch in cfg["bmc"]:
  2099. v = p["bmc"][ch] if ch < len(p["bmc"]) else None
  2100. row.append("" if v is None else str(v))
  2101. c_vals = []
  2102. for ch in cfg["ct"]:
  2103. v = p["ct"][ch] if ch < len(p["ct"]) else None
  2104. if ignore_zero_ct and v == 0:
  2105. v = None
  2106. if v is not None:
  2107. c_vals.append(v)
  2108. row.append(f"{sum(c_vals)/len(c_vals):.2f}" if c_vals else "")
  2109. for ch in cfg["ct"]:
  2110. v = p["ct"][ch] if ch < len(p["ct"]) else None
  2111. if ignore_zero_ct and v == 0:
  2112. v = None
  2113. row.append("" if v is None else str(v))
  2114. u6 = p["ct"][0] if p["ct"] else None
  2115. row.append("" if u6 is None else str(u6))
  2116. rows.append(",".join(row))
  2117. return "\n".join(rows) + "\n"
  2118. def self_test(product: str) -> int:
  2119. model = Model(product)
  2120. # 1. Golden GET_ALL frame
  2121. get_frame = encode_frame(FrameType.GET_ALL)
  2122. assert get_frame == bytes.fromhex("A55A02006D7B"), f"GET golden mismatch: {get_frame.hex()}"
  2123. exp_get = model.explain(get_frame)
  2124. assert exp_get["crc_ok"] is True
  2125. assert "GET_ALL" in exp_get["type"]
  2126. # 2. Golden ACKs
  2127. set_ack = bytes.fromhex("A55A8100A635")
  2128. get_ack = bytes.fromhex("A55A8200F560")
  2129. assert decode_frame(set_ack).crc_ok
  2130. assert decode_frame(get_ack).crc_ok
  2131. assert model.parse(set_ack)[0]["kind"] == "ack"
  2132. assert model.parse(get_ack)[0]["kind"] == "ack"
  2133. assert model.explain(set_ack)["crc_ok"] is True
  2134. assert model.explain(get_ack)["crc_ok"] is True
  2135. # 3. Golden NACK
  2136. nack = bytes.fromhex("A55AC0020104B12A")
  2137. assert decode_frame(nack).crc_ok
  2138. parsed_nack = model.parse(nack)[0]
  2139. assert parsed_nack["kind"] == "nack"
  2140. assert parsed_nack["reason"] == "QUEUE_FULL"
  2141. exp_nack = model.explain(nack)
  2142. assert exp_nack["crc_ok"] is True
  2143. assert "QUEUE_FULL" in exp_nack["fields"][1]
  2144. # 4. SET_ALL generation
  2145. values = [val for _, count, val in model.groups() for _ in range(count)]
  2146. frame = model.set_all(values, buzzer=1 if (model.motor or product == "6400-v2") else 0)
  2147. parsed = decode_frame(frame)
  2148. assert parsed.crc_ok
  2149. expected_len = 69 if model.motor else (36 if product == "6400-v2" else sum(count for _, count, _ in model.groups()))
  2150. assert len(parsed.payload) == expected_len
  2151. exp_set = model.explain(frame)
  2152. assert exp_set["crc_ok"] is True
  2153. if model.motor:
  2154. # Golden MOTOR_DONE frames
  2155. done_ul = bytes.fromhex("A55A500404022311B602")
  2156. assert decode_frame(done_ul).crc_ok
  2157. p_done = model.parse(done_ul)[0]
  2158. assert p_done["axis"] == 4 and p_done["reason"] == "UPPER_LIMIT" and p_done["steps_done"] == 4387
  2159. exp_done_ul = model.explain(done_ul)
  2160. assert exp_done_ul["crc_ok"] is True
  2161. assert "4387" in exp_done_ul["fields"][2]
  2162. done_bl = bytes.fromhex("A55A5004040300002364")
  2163. assert decode_frame(done_bl).crc_ok
  2164. p_done_bl = model.parse(done_bl)[0]
  2165. assert p_done_bl["axis"] == 4 and p_done_bl["reason"] == "BOTH_LIMITS" and p_done_bl["steps_done"] == 0
  2166. # V3.1.0 65B GET_DATA (hood_switch=1, buzzer=1) + 8B DIAGNOSTIC
  2167. mr_status = bytes([20] * 4 + [0] * 4 + [255] * 51 + [0, 0, 0, 0, 1, 1])
  2168. mr_dec = model.state(mr_status)
  2169. assert mr_dec["hood_switch"] is True and mr_dec["buzzer"] is True
  2170. mr_diag = bytes([2, 0x80, 3, 1, 0, 0x0B, 0x05, 0x00])
  2171. p_diag = model.parse(encode_frame(FrameType.DIAGNOSTIC, mr_diag))[0]["diagnostic"]
  2172. assert p_diag["supported"] and p_diag["firmware_version"] == "3.1.0" and p_diag["buzzer_on"] and p_diag["active_axes"] == [0, 2]
  2173. if product == "6400-v2":
  2174. status = bytes([0] * 24 + [20] * 8 + [255] * 51 + [0, 25, 100, 1, 1])
  2175. decoded = model.state(status)
  2176. assert decoded["ssr"] == [0, 25, 100]
  2177. assert decoded["hood_switch"] is True and decoded["buzzer"] is True
  2178. assert len(decoded["ct"]["raw"]) == 27
  2179. diagnostic = bytes([1, 0x64, 3, 1, 0, 0x23, 0, 0, 0x4C, 0, 0, 0x80, 0x0C, 25, 1, 0, 1, 1, 0, 48])
  2180. d_parsed = model.parse(encode_frame(FrameType.DIAGNOSTIC, diagnostic))[0]["diagnostic"]
  2181. assert d_parsed["temperature_c"] == 25 and d_parsed["buzzer_on"] is True
  2182. # 5. Chamber mapping default + custom configuration & curve image generation
  2183. cmap = ChamberMappingConfig.default(product)
  2184. assert cmap.chambers[1]["bmc"] == [0, 1, 2, 3, 4, 5] and cmap.chambers[1]["ct"] == [1, 2]
  2185. assert cmap.chambers[2]["bmc"] == [6, 7, 8, 9, 10, 11] and cmap.chambers[2]["ct"] == [3, 4]
  2186. assert cmap.chambers[3]["bmc"] == [12, 13, 14, 15, 16, 17] and cmap.chambers[3]["ct"] == [5, 6]
  2187. assert cmap.chambers[4]["bmc"] == [18, 19, 20, 21, 22, 23] and cmap.chambers[4]["ct"] == [7, 8]
  2188. cmap.set_chamber(1, "0-2, 5", "CT5, CT6")
  2189. assert cmap.chambers[1]["bmc"] == [0, 1, 2, 5] and cmap.chambers[1]["ct"] == [5, 6]
  2190. cmap.reset_to_default()
  2191. store = TemperatureCurveStore()
  2192. store.record_raw_arrays(
  2193. [30 + (i % 6) for i in range(24)],
  2194. [25, 22, 28, 23, 29, 24, 31, 25, 32] + [255] * 18,
  2195. timestamp=1000.0,
  2196. time_label="10:00:00",
  2197. )
  2198. store.record_raw_arrays(
  2199. [32 + (i % 6) for i in range(24)],
  2200. [26, 24, 31, 25, 32, 26, 34, 27, 35] + [255] * 18,
  2201. timestamp=1001.0,
  2202. time_label="10:00:01",
  2203. )
  2204. png_bytes = render_chamber_curves_png(store, cmap, product=product, board=model.board, width=800, height=540)
  2205. assert png_bytes.startswith(b"\x89PNG\r\n\x1a\n") and len(png_bytes) > 500
  2206. svg_str = render_chamber_curves_svg(store, cmap, product=product, board=model.board, width=800, height=540)
  2207. assert "<svg" in svg_str and "腔体 1" in svg_str
  2208. csv_str = export_chamber_curves_csv(store, cmap)
  2209. assert "C1_BMC_AVG" in csv_str and "C4_CT8" in csv_str
  2210. # 6. ThermalTestSession reach-time calculation & continuous recording after first chamber reaches target
  2211. tt = ThermalTestSession(
  2212. product,
  2213. overall_pass_min_temp_c=70.0,
  2214. chamber_target_temp_c={1: 70.0, 2: 72.0, 3: 70.0, 4: 70.0},
  2215. fan_intervention_mode="ref_temp_c",
  2216. fan_intervention_ref_temp_c=55.0,
  2217. initial_fan_duty_percent=0,
  2218. active_fan_duty_percent=50,
  2219. )
  2220. tt.start(start_timestamp=2000.0)
  2221. tt_store = TemperatureCurveStore()
  2222. # t=0s: initial room temp 30C
  2223. s0 = tt_store.record_raw_arrays([30] * 24, [25] + [30] * 8 + [255] * 18, timestamp=2000.0, time_label="10:00:00")
  2224. tt.process_sample(s0, cmap)
  2225. assert not tt.fan_intervened
  2226. # t=60s: Chamber 1 reaches 70C first; fan ref temp 55C also crossed -> fan intervenes
  2227. s1 = tt_store.record_raw_arrays(
  2228. [71] * 6 + [56] * 18,
  2229. [28, 70, 72, 55, 56, 54, 55, 52, 53] + [255] * 18,
  2230. timestamp=2060.0,
  2231. time_label="10:01:00",
  2232. )
  2233. res1 = tt.process_sample(s1, cmap)
  2234. assert res1["fan_switched_now"] is True and tt.current_fan_duty_percent == 50
  2235. assert tt.chamber_stats[1]["sensor_reached"] is True and tt.chamber_stats[1]["sensor_time_to_target_s"] == 60.0
  2236. assert tt.chamber_stats[1]["memory_reached"] is True and tt.chamber_stats[1]["memory_time_to_target_s"] == 60.0
  2237. assert tt.chamber_stats[2]["sensor_reached"] is False
  2238. # t=120s: Chamber 1 already reached target at 60s, MUST continue recording data!
  2239. s2 = tt_store.record_raw_arrays(
  2240. [75] * 6 + [73] * 18,
  2241. [30, 74, 76, 73, 73, 71, 71, 70, 71] + [255] * 18,
  2242. timestamp=2120.0,
  2243. time_label="10:02:00",
  2244. )
  2245. tt.process_sample(s2, cmap)
  2246. assert tt.chamber_stats[1]["sensor_time_to_target_s"] == 60.0 # locked at first reach time
  2247. assert tt.chamber_stats[1]["post_target_samples"] == 1 # continued recording after target!
  2248. assert tt.chamber_stats[1]["sensor_peak_c"] == 75.0
  2249. assert tt.chamber_stats[2]["sensor_time_to_target_s"] == 120.0
  2250. rep = tt.summary()
  2251. assert rep["hood_summary"]["hood_all_reached"] is True
  2252. assert rep["hood_summary"]["hood_sensor_reach_time_s"] == 120.0
  2253. assert "PASS" in tt.export_summary_csv()
  2254. return 0
  2255. def describe(model: Model, frame: bytes) -> str:
  2256. values = model.parse(frame)
  2257. return json.dumps(
  2258. values[0]["state"] if len(values) == 1 and values[0]["kind"] == "status" else values,
  2259. ensure_ascii=False,
  2260. indent=2,
  2261. )
  2262. def reset_motor_actions(axis_slots: list[dict[str, Any]]) -> None:
  2263. """A later thermal SET must not replay a previously selected motion."""
  2264. for slot in axis_slots:
  2265. slot["action_var"].set("NOTHING")
  2266. # ---------------------------------------------------------------------------
  2267. # Full Tkinter GUI Implementation
  2268. # ---------------------------------------------------------------------------
  2269. def run_gui(product: str) -> int:
  2270. try:
  2271. import tkinter as tk
  2272. from tkinter import ttk, messagebox, filedialog
  2273. except ImportError:
  2274. if sys.stderr:
  2275. print("Tkinter unavailable in headless environment; run --self-test instead.", file=sys.stderr)
  2276. return 1
  2277. model = Model(product)
  2278. try:
  2279. root = tk.Tk()
  2280. except Exception as exc:
  2281. if sys.stderr:
  2282. print(f"Display unavailable ({exc}); run --self-test instead or use xvfb-run.", file=sys.stderr)
  2283. return 1
  2284. root.title(f"{model.board} | 软件 v{model.release_version} | Prod2U 调试与监控")
  2285. root.geometry("1180x820")
  2286. root.minsize(960, 640)
  2287. # Global serial state & communication engine
  2288. serial_port_obj: Any = None
  2289. serial_lock = threading.Lock()
  2290. poll_active = False
  2291. poll_generation = 0
  2292. poll_stop_event = threading.Event()
  2293. connection_epoch = 0
  2294. disk_logger = SessionDiskLogger(product)
  2295. tracker = TransactionTracker()
  2296. receiver = StreamReceiver(product)
  2297. request_queue: queue.Queue = queue.Queue()
  2298. scheduler_lock = threading.Lock()
  2299. def dispatch_next_request():
  2300. nonlocal serial_port_obj
  2301. with scheduler_lock:
  2302. t_evt = tracker.check_request_timeout()
  2303. if t_evt:
  2304. root.after(0, append_log, "ERR", "", t_evt["msg"])
  2305. root.after(0, lbl_realtime_stat.config, {"text": t_evt["msg"]})
  2306. if tracker.tx_state != "IDLE":
  2307. return
  2308. if request_queue.empty():
  2309. return
  2310. try:
  2311. item = request_queue.get_nowait()
  2312. if len(item) == 4:
  2313. req_type, frame_bytes, desc, nonce = item
  2314. else:
  2315. req_type, frame_bytes, desc = item
  2316. nonce = None
  2317. except queue.Empty:
  2318. return
  2319. with serial_lock:
  2320. sp = serial_port_obj
  2321. if sp and sp.is_open:
  2322. try:
  2323. tracker.on_request_sent(req_type, timeout=1.0, nonce=nonce)
  2324. sp.write(frame_bytes)
  2325. if model.motor and req_type == "SET":
  2326. root.after(0, reset_motor_actions, axis_slots)
  2327. root.after(0, append_log, "TX", frame_hex(frame_bytes), desc)
  2328. except Exception as exc:
  2329. root.after(0, append_log, "ERR", "", f"发送失败: {exc}")
  2330. # Notebook
  2331. notebook = ttk.Notebook(root)
  2332. notebook.pack(fill="both", expand=True, padx=8, pady=8)
  2333. # -----------------------------------------------------------------------
  2334. # TAB 1: 串口连接与实时控制 (Serial & Realtime Control)
  2335. # -----------------------------------------------------------------------
  2336. tab_serial = ttk.Frame(notebook, padding=10)
  2337. notebook.add(tab_serial, text="📡 串口连接与实时控制")
  2338. # Connection bar
  2339. conn_frame = ttk.LabelFrame(tab_serial, text=f"Host UART · 固件构建速率 {model.host_baud} · 8N1 · BMC 独立 115200", padding=8)
  2340. conn_frame.pack(fill="x", pady=4)
  2341. ttk.Label(conn_frame, text="COM 端口:").pack(side="left", padx=4)
  2342. port_combo = ttk.Combobox(conn_frame, width=14, state="readonly")
  2343. port_combo.pack(side="left", padx=4)
  2344. def refresh_ports():
  2345. if HAVE_SERIAL:
  2346. ports = [p.device for p in serial.tools.list_ports.comports()]
  2347. port_combo["values"] = ports
  2348. if ports and not port_combo.get():
  2349. port_combo.set(ports[0])
  2350. elif not ports:
  2351. port_combo.set("")
  2352. else:
  2353. port_combo["values"] = ["(pyserial 未安装)"]
  2354. port_combo.set("(pyserial 未安装)")
  2355. refresh_ports()
  2356. ttk.Button(conn_frame, text="刷新端口", command=refresh_ports).pack(side="left", padx=4)
  2357. ttk.Label(conn_frame, text="波特率:").pack(side="left", padx=8)
  2358. baud_combo = ttk.Combobox(conn_frame, width=10, values=[str(rate) for rate in HOST_BAUDRATES], state="readonly")
  2359. baud_combo.set(str(model.host_baud))
  2360. baud_combo.pack(side="left", padx=4)
  2361. ttk.Label(conn_frame, text="需与烧录固件速率一致", foreground="gray").pack(side="left", padx=4)
  2362. btn_connect = ttk.Button(conn_frame, text="打开串口")
  2363. btn_connect.pack(side="left", padx=10)
  2364. lbl_conn_status = ttk.Label(conn_frame, text="未连接", foreground="gray", font=("", 10, "bold"))
  2365. lbl_conn_status.pack(side="left", padx=8)
  2366. # Realtime control bar
  2367. ctrl_bar = ttk.Frame(tab_serial, padding=4)
  2368. ctrl_bar.pack(fill="x", pady=6)
  2369. btn_send_get = ttk.Button(ctrl_bar, text="🔍 发送 GET_ALL 查询", state="disabled")
  2370. btn_send_get.pack(side="left", padx=5)
  2371. btn_send_set = ttk.Button(ctrl_bar, text="⚡ 发送当前 SET 配置", state="disabled")
  2372. btn_send_set.pack(side="left", padx=5)
  2373. btn_heartbeat = ttk.Button(ctrl_bar, text="💓 心跳测试 (Ping)", state="disabled")
  2374. btn_heartbeat.pack(side="left", padx=5)
  2375. poll_var = tk.BooleanVar(value=False)
  2376. chk_poll = ttk.Checkbutton(ctrl_bar, text="自动每秒轮询 GET_ALL (维持看门狗)", variable=poll_var, state="disabled")
  2377. chk_poll.pack(side="left", padx=15)
  2378. # Realtime status summary
  2379. stat_summary_frame = ttk.LabelFrame(tab_serial, text="单板实时状态概要", padding=8)
  2380. stat_summary_frame.pack(fill="x", pady=4)
  2381. lbl_realtime_stat = ttk.Label(stat_summary_frame, text="等待查询或接收单板响应...", font=("", 10))
  2382. lbl_realtime_stat.pack(anchor="w")
  2383. lbl_realtime_ptc = ttk.Label(stat_summary_frame, text="【PTC 生效占空比】: 待查询", font=("Consolas", 9), foreground="#003366")
  2384. lbl_realtime_ptc.pack(anchor="w", pady=2)
  2385. lbl_realtime_chambers = ttk.Label(
  2386. stat_summary_frame,
  2387. text="【四腔实时温度 (可配置映射)】: 腔1[内存:-- | CT1=--/CT2=--] 腔2[内存:-- | CT3=--/CT4=--] 腔3[内存:-- | CT5=--/CT6=--] 腔4[内存:-- | CT7=--/CT8=--]",
  2388. font=("Consolas", 9),
  2389. foreground="#0B5345",
  2390. wraplength=1100,
  2391. )
  2392. lbl_realtime_chambers.pack(anchor="w", pady=2)
  2393. lbl_realtime_diag = ttk.Label(stat_summary_frame, text="【固件自主诊断】: 等待 0x52 自动上报",
  2394. font=("Consolas", 9), foreground="#704010", wraplength=1050)
  2395. if product in ("6400-v2", "mrdimm-chamber"):
  2396. lbl_realtime_diag.pack(anchor="w", pady=2)
  2397. # Serial Log area
  2398. log_frame = ttk.LabelFrame(tab_serial, text="通信原始报文日志 (TX / RX 流)", padding=8)
  2399. log_frame.pack(fill="both", expand=True, pady=6)
  2400. text_log = tk.Text(log_frame, height=14, wrap="char", font=("Consolas", 9))
  2401. text_log.pack(fill="both", expand=True, side="left")
  2402. scroll_log = ttk.Scrollbar(log_frame, command=text_log.yview)
  2403. scroll_log.pack(side="right", fill="y")
  2404. text_log.config(yscrollcommand=scroll_log.set)
  2405. def append_log(direction: str, hex_str: str, note: str = ""):
  2406. now = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
  2407. if direction.startswith("TX"):
  2408. tag = "tx"
  2409. elif direction in ("RX", "RX_AUTO", "BOARD_DIAG"):
  2410. tag = "rx"
  2411. elif direction == "RX_RAW":
  2412. tag = "rx_raw"
  2413. elif direction == "NOISE":
  2414. tag = "noise"
  2415. else:
  2416. tag = "err"
  2417. line = f"[{now}] [{direction:6s}] {hex_str}"
  2418. if note:
  2419. line += f" ({note})"
  2420. line += "\n"
  2421. text_log.insert("end", line, tag)
  2422. text_log.see("end")
  2423. disk_logger.log_event(direction, hex_str, note)
  2424. text_log.tag_config("tx", foreground="#0066CC")
  2425. text_log.tag_config("rx", foreground="#008800")
  2426. text_log.tag_config("rx_raw", foreground="#777777")
  2427. text_log.tag_config("noise", foreground="#AA6600")
  2428. text_log.tag_config("err", foreground="#CC0000")
  2429. def open_log_dir():
  2430. log_dir = str(disk_logger.log_dir)
  2431. try:
  2432. if sys.platform == "win32":
  2433. os.startfile(log_dir)
  2434. elif sys.platform == "darwin":
  2435. subprocess.Popen(["open", log_dir])
  2436. else:
  2437. subprocess.Popen(["xdg-open", log_dir])
  2438. except Exception as e:
  2439. messagebox.showinfo("日志目录", f"日志存储在:\n{disk_logger.log_dir}\n打开失败: {e}")
  2440. def export_diagnosis():
  2441. try:
  2442. info = [
  2443. f"=== Prod2U GUI 会话诊断快照 ===",
  2444. f"会话 ID: {disk_logger.session_id}",
  2445. f"产品型号: {product} ({model.board})",
  2446. f"当前连接状态: {tracker.state}",
  2447. f"日志落盘路径:\n{disk_logger.log_path}",
  2448. "",
  2449. "如需提供给 ChatGPT 或技术支持分析,请将上述日志文件直接发送。",
  2450. ]
  2451. messagebox.showinfo("本次诊断信息", "\n".join(info))
  2452. except Exception as e:
  2453. messagebox.showerror("诊断导出失败", str(e))
  2454. btn_clear_log = ttk.Button(ctrl_bar, text="清空日志", command=lambda: text_log.delete("1.0", "end"))
  2455. btn_clear_log.pack(side="right", padx=3)
  2456. btn_open_log = ttk.Button(ctrl_bar, text="📁 打开日志目录", command=open_log_dir)
  2457. btn_open_log.pack(side="right", padx=3)
  2458. btn_export_diag = ttk.Button(ctrl_bar, text="📋 诊断信息", command=export_diagnosis)
  2459. btn_export_diag.pack(side="right", padx=3)
  2460. # -----------------------------------------------------------------------
  2461. # TAB 2: 腔体温度曲线与映射 (Chamber Temperature Curves & Mapping)
  2462. # -----------------------------------------------------------------------
  2463. tab_curves = ttk.Frame(notebook, padding=8)
  2464. notebook.add(tab_curves, text="📈 腔体温度曲线与映射")
  2465. curve_store = TemperatureCurveStore()
  2466. chamber_mapping = ChamberMappingConfig.default(product)
  2467. default_map_path = ChamberMappingConfig.default_config_path(product)
  2468. if default_map_path.is_file():
  2469. try:
  2470. chamber_mapping = ChamberMappingConfig.load(default_map_path, product=product)
  2471. except Exception:
  2472. chamber_mapping = ChamberMappingConfig.default(product)
  2473. thermal_session = ThermalTestSession(product)
  2474. experiment_history: list[dict[str, Any]] = []
  2475. # 1. Configurable Chamber Mapping Frame
  2476. map_frame = ttk.LabelFrame(
  2477. tab_curves,
  2478. text="⚙️ 各腔体通道映射配置 (默认值: 腔1~4 内存=BMC 0-5/6-11/12-17/18-23,Sensor=CT 1,2/3,4/5,6/7,8;支持范围如 0-5 或逗号 1,2)",
  2479. padding=6,
  2480. )
  2481. map_frame.pack(fill="x", pady=3)
  2482. map_grid = ttk.Frame(map_frame)
  2483. map_grid.pack(fill="x", pady=2)
  2484. chamber_bmc_vars: dict[int, tk.StringVar] = {}
  2485. chamber_ct_vars: dict[int, tk.StringVar] = {}
  2486. def open_channel_selector(cid: int, kind: str):
  2487. is_bmc = (kind == "bmc")
  2488. max_ch = 23 if is_bmc else 26
  2489. title_str = f"选择 腔体{cid} 的 {'内存温度 (BMC0..23)' if is_bmc else 'Sensor温度 (CT0..26)'} 通道"
  2490. var_target = chamber_bmc_vars[cid] if is_bmc else chamber_ct_vars[cid]
  2491. try:
  2492. current_set = set(parse_channel_spec(var_target.get(), max_ch))
  2493. except Exception:
  2494. current_set = set()
  2495. dlg = tk.Toplevel(root)
  2496. dlg.title(title_str)
  2497. dlg.geometry("680x360" if not is_bmc else "640x320")
  2498. dlg.transient(root)
  2499. dlg.grab_set()
  2500. ttk.Label(dlg, text=title_str, font=("", 10, "bold")).pack(anchor="w", padx=10, pady=6)
  2501. chk_container = ttk.Frame(dlg, padding=8)
  2502. chk_container.pack(fill="both", expand=True)
  2503. chk_vars: dict[int, tk.BooleanVar] = {}
  2504. cols = 6 if is_bmc else 5
  2505. for idx in range(max_ch + 1):
  2506. bv = tk.BooleanVar(value=(idx in current_set))
  2507. chk_vars[idx] = bv
  2508. lbl = bmc_channel_label(idx, short=False) if is_bmc else ct_channel_label(idx, short=False)
  2509. cb = ttk.Checkbutton(chk_container, text=lbl, variable=bv)
  2510. cb.grid(row=idx // cols, column=idx % cols, sticky="w", padx=6, pady=3)
  2511. btn_row = ttk.Frame(dlg, padding=8)
  2512. btn_row.pack(fill="x")
  2513. def select_all_ch(state: bool):
  2514. for bv in chk_vars.values():
  2515. bv.set(state)
  2516. def confirm_selection():
  2517. chosen = [idx for idx, bv in sorted(chk_vars.items()) if bv.get()]
  2518. var_target.set(format_channel_spec(chosen))
  2519. dlg.destroy()
  2520. apply_chamber_mapping(silent=True)
  2521. ttk.Button(btn_row, text="全选", command=lambda: select_all_ch(True)).pack(side="left", padx=4)
  2522. ttk.Button(btn_row, text="全不选", command=lambda: select_all_ch(False)).pack(side="left", padx=4)
  2523. ttk.Button(btn_row, text="取消", command=dlg.destroy).pack(side="right", padx=4)
  2524. ttk.Button(btn_row, text="✅ 确定并应用", command=confirm_selection).pack(side="right", padx=4)
  2525. for idx, cid in enumerate(CHAMBER_IDS):
  2526. c_col = idx % 2
  2527. c_row = idx // 2
  2528. cell_f = ttk.Frame(map_grid)
  2529. cell_f.grid(row=c_row, column=c_col, sticky="ew", padx=8, pady=2)
  2530. map_grid.columnconfigure(c_col, weight=1)
  2531. ttk.Label(cell_f, text=f"【腔体 {cid}】", font=("", 9, "bold"), foreground="#153259").pack(side="left", padx=2)
  2532. ttk.Label(cell_f, text="内存(BMC):").pack(side="left", padx=2)
  2533. b_var = tk.StringVar(value=format_channel_spec(chamber_mapping.chambers[cid]["bmc"]))
  2534. chamber_bmc_vars[cid] = b_var
  2535. ttk.Entry(cell_f, textvariable=b_var, width=10, font=("Consolas", 9)).pack(side="left", padx=2)
  2536. ttk.Button(cell_f, text="选择", width=4, command=lambda c=cid: open_channel_selector(c, "bmc")).pack(side="left", padx=2)
  2537. ttk.Label(cell_f, text="Sensor(CT):").pack(side="left", padx=(8, 2))
  2538. c_var = tk.StringVar(value=format_channel_spec(chamber_mapping.chambers[cid]["ct"]))
  2539. chamber_ct_vars[cid] = c_var
  2540. ttk.Entry(cell_f, textvariable=c_var, width=10, font=("Consolas", 9)).pack(side="left", padx=2)
  2541. ttk.Button(cell_f, text="选择", width=4, command=lambda c=cid: open_channel_selector(c, "ct")).pack(side="left", padx=2)
  2542. map_btn_bar = ttk.Frame(map_frame)
  2543. map_btn_bar.pack(fill="x", pady=(4, 0))
  2544. lbl_map_status = ttk.Label(map_btn_bar, text="当前使用默认/已存映射,修改后点击【应用映射】即时重绘四腔曲线", foreground="#2E7D32")
  2545. lbl_map_status.pack(side="right", padx=6)
  2546. def sync_vars_from_mapping():
  2547. for cid in CHAMBER_IDS:
  2548. chamber_bmc_vars[cid].set(format_channel_spec(chamber_mapping.chambers[cid]["bmc"]))
  2549. chamber_ct_vars[cid].set(format_channel_spec(chamber_mapping.chambers[cid]["ct"]))
  2550. def apply_chamber_mapping(silent: bool = False) -> bool:
  2551. try:
  2552. for cid in CHAMBER_IDS:
  2553. chamber_mapping.set_chamber(cid, chamber_bmc_vars[cid].get(), chamber_ct_vars[cid].get())
  2554. sync_vars_from_mapping()
  2555. try:
  2556. chamber_mapping.save(default_map_path)
  2557. except Exception:
  2558. pass
  2559. lbl_map_status.config(
  2560. text=f"映射已生效 ({datetime.datetime.now().strftime('%H:%M:%S')}) — 历史数据已按新映射重绘",
  2561. foreground="#006600",
  2562. )
  2563. redraw_all_chamber_canvases()
  2564. return True
  2565. except Exception as exc:
  2566. lbl_map_status.config(text=f"映射格式错误: {exc}", foreground="#CC0000")
  2567. if not silent:
  2568. messagebox.showerror("腔体映射配置错误", str(exc))
  2569. return False
  2570. def reset_chamber_mapping():
  2571. chamber_mapping.reset_to_default()
  2572. sync_vars_from_mapping()
  2573. apply_chamber_mapping(silent=True)
  2574. lbl_map_status.config(text="已恢复默认腔体映射 (BMC: 0-5/6-11/12-17/18-23, CT: 1,2/3,4/5,6/7,8)", foreground="#0055AA")
  2575. def swap_ct_pairs():
  2576. if not apply_chamber_mapping(silent=False):
  2577. return
  2578. chamber_mapping.swap_pairs(swap_bmc=False, swap_ct=True)
  2579. sync_vars_from_mapping()
  2580. apply_chamber_mapping(silent=True)
  2581. lbl_map_status.config(text="已对调腔体 1<->3 与 2<->4 的 Sensor(CT) 通道映射", foreground="#0055AA")
  2582. def swap_bmc_pairs():
  2583. if not apply_chamber_mapping(silent=False):
  2584. return
  2585. chamber_mapping.swap_pairs(swap_bmc=True, swap_ct=False)
  2586. sync_vars_from_mapping()
  2587. apply_chamber_mapping(silent=True)
  2588. lbl_map_status.config(text="已对调腔体 1<->3 与 2<->4 的 内存(BMC) 通道映射", foreground="#0055AA")
  2589. def export_mapping_file():
  2590. if not apply_chamber_mapping(silent=False):
  2591. return
  2592. path = filedialog.asksaveasfilename(
  2593. title="保存腔体映射配置 JSON",
  2594. defaultextension=".json",
  2595. initialfile=f"chamber_mapping_{product}.json",
  2596. filetypes=[("JSON 映射配置", "*.json"), ("所有文件", "*.*")],
  2597. )
  2598. if path:
  2599. try:
  2600. saved = chamber_mapping.save(Path(path))
  2601. lbl_map_status.config(text=f"映射配置已保存: {saved.name}", foreground="#006600")
  2602. except Exception as exc:
  2603. messagebox.showerror("保存失败", str(exc))
  2604. def import_mapping_file():
  2605. path = filedialog.askopenfilename(
  2606. title="载入腔体映射配置 JSON",
  2607. filetypes=[("JSON 映射配置", "*.json"), ("所有文件", "*.*")],
  2608. )
  2609. if path:
  2610. try:
  2611. loaded = ChamberMappingConfig.load(Path(path), product=product)
  2612. for cid in CHAMBER_IDS:
  2613. chamber_mapping.chambers[cid] = dict(loaded.chambers[cid])
  2614. sync_vars_from_mapping()
  2615. apply_chamber_mapping(silent=True)
  2616. lbl_map_status.config(text=f"已载入映射配置: {Path(path).name}", foreground="#006600")
  2617. except Exception as exc:
  2618. messagebox.showerror("载入映射失败", str(exc))
  2619. ttk.Button(map_btn_bar, text="✅ 应用映射", command=lambda: apply_chamber_mapping(False)).pack(side="left", padx=3)
  2620. ttk.Button(map_btn_bar, text="🔄 恢复默认映射", command=reset_chamber_mapping).pack(side="left", padx=3)
  2621. ttk.Button(map_btn_bar, text="🔀 1/2与3/4腔Sensor对调", command=swap_ct_pairs).pack(side="left", padx=3)
  2622. ttk.Button(map_btn_bar, text="🔀 1/2与3/4腔内存对调", command=swap_bmc_pairs).pack(side="left", padx=3)
  2623. ttk.Button(map_btn_bar, text="💾 导出映射JSON", command=export_mapping_file).pack(side="left", padx=3)
  2624. ttk.Button(map_btn_bar, text="📂 导入映射JSON", command=import_mapping_file).pack(side="left", padx=3)
  2625. # 2. Curve Display & Image Printing Toolbar
  2626. plot_ctrl_bar = ttk.Frame(tab_curves, padding=4)
  2627. plot_ctrl_bar.pack(fill="x", pady=2)
  2628. ttk.Label(plot_ctrl_bar, text="显示模式:").pack(side="left", padx=2)
  2629. MODE_LABELS = {
  2630. "通道明细 + 腔体均值 (推荐)": "detail_and_avg",
  2631. "仅腔体均值与极值 (简洁)": "avg_only",
  2632. "仅各通道独立曲线": "detail_only",
  2633. }
  2634. curve_mode_var = tk.StringVar(value="通道明细 + 腔体均值 (推荐)")
  2635. combo_mode = ttk.Combobox(plot_ctrl_bar, textvariable=curve_mode_var, values=list(MODE_LABELS.keys()), width=23, state="readonly")
  2636. combo_mode.pack(side="left", padx=4)
  2637. ttk.Label(plot_ctrl_bar, text="时间窗口:").pack(side="left", padx=4)
  2638. WINDOW_LABELS = {
  2639. "全部历史": 0,
  2640. "最近 60 点": 60,
  2641. "最近 300 点": 300,
  2642. "最近 900 点 (15分钟)": 900,
  2643. }
  2644. curve_win_var = tk.StringVar(value="全部历史")
  2645. combo_win = ttk.Combobox(plot_ctrl_bar, textvariable=curve_win_var, values=list(WINDOW_LABELS.keys()), width=16, state="readonly")
  2646. combo_win.pack(side="left", padx=4)
  2647. ignore_zero_ct_var = tk.BooleanVar(value=False)
  2648. chk_ignore_zero = ttk.Checkbutton(
  2649. plot_ctrl_bar,
  2650. text="过滤 Sensor 0°C (未接探头)",
  2651. variable=ignore_zero_ct_var,
  2652. command=lambda: redraw_all_chamber_canvases(),
  2653. )
  2654. chk_ignore_zero.pack(side="left", padx=8)
  2655. lbl_curve_count = ttk.Label(plot_ctrl_bar, text="采样点: 0", font=("Consolas", 9, "bold"), foreground="#153259")
  2656. lbl_curve_count.pack(side="left", padx=8)
  2657. # 3. 2x2 Grid of 4 Chamber Curve Canvases
  2658. plots_grid = ttk.Frame(tab_curves)
  2659. plots_grid.pack(fill="both", expand=True, pady=4)
  2660. plots_grid.columnconfigure(0, weight=1)
  2661. plots_grid.columnconfigure(1, weight=1)
  2662. plots_grid.rowconfigure(0, weight=1)
  2663. plots_grid.rowconfigure(1, weight=1)
  2664. chamber_canvases: dict[int, tk.Canvas] = {}
  2665. chamber_hover_idx: dict[int, int | None] = {1: None, 2: None, 3: None, 4: None}
  2666. chamber_plot_geom: dict[int, dict[str, Any]] = {}
  2667. for idx, cid in enumerate(CHAMBER_IDS):
  2668. r = idx // 2
  2669. c = idx % 2
  2670. cv = tk.Canvas(plots_grid, bg="#FFFFFF", highlightthickness=1, highlightbackground="#CBD5E1")
  2671. cv.grid(row=r, column=c, sticky="nsew", padx=4, pady=4)
  2672. chamber_canvases[cid] = cv
  2673. def _current_mode_and_window() -> tuple[str, int, bool]:
  2674. m = MODE_LABELS.get(curve_mode_var.get(), "detail_and_avg")
  2675. w = WINDOW_LABELS.get(curve_win_var.get(), 0)
  2676. z = bool(ignore_zero_ct_var.get())
  2677. return m, w, z
  2678. def draw_single_chamber_canvas(cid: int):
  2679. cv = chamber_canvases[cid]
  2680. w = max(320, cv.winfo_width())
  2681. h = max(190, cv.winfo_height())
  2682. cv.delete("all")
  2683. mode, max_pts, ign_zero = _current_mode_and_window()
  2684. series = curve_store.chamber_series(chamber_mapping, cid, max_points=max_pts, ignore_zero_ct=ign_zero)
  2685. bmc_spec = format_channel_spec(series["bmc_channels"]) or "无"
  2686. ct_spec = format_channel_spec(series["ct_channels"]) or "无"
  2687. # Header band
  2688. ch_st = thermal_session.chamber_stats.get(cid, {})
  2689. ch_target_c = float(ch_st.get("effective_target_c", 70.0))
  2690. s_t_str = format_duration_mmss(ch_st.get("sensor_time_to_target_s"))
  2691. m_t_str = format_duration_mmss(ch_st.get("memory_time_to_target_s"))
  2692. cv.create_rectangle(0, 0, w, 40, fill="#EEF3F9", outline="#CBD5E1")
  2693. cv.create_text(
  2694. 10,
  2695. 11,
  2696. anchor="w",
  2697. text=f"{series['name']} [BMC:{bmc_spec} | CT:{ct_spec}] 🎯目标{ch_target_c:.0f}°C (Sensor达标:{s_t_str} | 内存达标:{m_t_str})",
  2698. font=("Microsoft YaHei", 9, "bold"),
  2699. fill="#0F2747",
  2700. )
  2701. latest_b = next((v for v in reversed(series["bmc_avg"]) if v is not None), None)
  2702. latest_c_parts = []
  2703. for ch in series["ct_channels"]:
  2704. v_list = series["ct_series"].get(ch, [])
  2705. v_last = next((v for v in reversed(v_list) if v is not None), None)
  2706. latest_c_parts.append(f"CT{ch}={v_last}°C" if v_last is not None else f"CT{ch}=--")
  2707. stat_txt = (
  2708. f"当前内存均温: {latest_b:.1f}°C" if latest_b is not None else "当前内存均温: --"
  2709. ) + " | Sensor: " + (", ".join(latest_c_parts) if latest_c_parts else "无")
  2710. cv.create_text(10, 29, anchor="w", text=stat_txt, font=("Consolas", 8), fill="#334E68")
  2711. legend_w = 132 if w >= 460 else 108
  2712. px0 = 46
  2713. py0 = 48
  2714. px1 = max(px0 + 60, w - legend_w - 8)
  2715. py1 = max(py0 + 40, h - 24)
  2716. pw = px1 - px0
  2717. ph = py1 - py0
  2718. cv.create_rectangle(px0, py0, px1, py1, fill="#FCFDFF", outline="#B4C2D2")
  2719. traces = _compute_chamber_plot_traces(series, mode=mode)
  2720. y_min, y_max = _y_axis_bounds(traces, target_temp_c=ch_target_c)
  2721. # Horizontal grid & Y axis labels
  2722. for step_i in range(5):
  2723. frac = step_i / 4.0
  2724. val_y = y_min + (y_max - y_min) * frac
  2725. gy = py1 - frac * ph
  2726. if 0 < step_i < 4:
  2727. cv.create_line(px0 + 1, gy, px1 - 1, gy, fill="#E2E8F0", dash=(3, 3))
  2728. cv.create_text(px0 - 4, gy, anchor="e", text=f"{int(round(val_y))}°C", font=("Consolas", 8), fill="#5A6978")
  2729. if y_min <= ch_target_c <= y_max:
  2730. ty = py1 - ((ch_target_c - y_min) / max(1e-6, y_max - y_min)) * ph
  2731. cv.create_line(px0 + 1, ty, px1 - 1, ty, fill="#D97706", width=1.5, dash=(5, 3))
  2732. cv.create_text(px1 - 4, max(py0 + 8, ty - 7), anchor="e", text=f"目标{ch_target_c:.0f}°C", font=("Consolas", 8, "bold"), fill="#B45309")
  2733. # Vertical grid & X axis labels
  2734. n_pts = series["sample_count"]
  2735. elapsed = series["elapsed"]
  2736. t_span = max(1.0, (elapsed[-1] - elapsed[0]) if len(elapsed) >= 2 else 1.0)
  2737. for step_x in range(5):
  2738. fx = step_x / 4.0
  2739. gx = px0 + fx * pw
  2740. if 0 < step_x < 4:
  2741. cv.create_line(gx, py0 + 1, gx, py1 - 1, fill="#E8EDF3", dash=(3, 3))
  2742. if n_pts >= 2:
  2743. idx_pt = min(n_pts - 1, int(round(fx * (n_pts - 1))))
  2744. lbl_x = f"{elapsed[idx_pt]:.0f}s"
  2745. elif n_pts == 1 and step_x == 2:
  2746. lbl_x = series["time_labels"][0]
  2747. else:
  2748. lbl_x = f"{int(fx * 60)}s" if n_pts == 0 else ""
  2749. if lbl_x:
  2750. cv.create_text(gx, py1 + 11, anchor="center", text=lbl_x, font=("Consolas", 8), fill="#5A6978")
  2751. chamber_plot_geom[cid] = {
  2752. "px0": px0, "py0": py0, "px1": px1, "py1": py1, "pw": pw, "ph": ph,
  2753. "n_pts": n_pts, "elapsed": elapsed, "t_span": t_span, "series": series, "traces": traces,
  2754. }
  2755. has_any_point = False
  2756. for tr in traces:
  2757. pts_xy = []
  2758. for i, v in enumerate(tr["values"]):
  2759. if v is None:
  2760. continue
  2761. if n_pts <= 1:
  2762. x = px0 + pw / 2.0
  2763. else:
  2764. x = px0 + ((elapsed[i] - elapsed[0]) / t_span) * pw if elapsed[-1] > elapsed[0] else px0 + (i / (n_pts - 1)) * pw
  2765. y = py1 - ((float(v) - y_min) / max(1e-6, y_max - y_min)) * ph
  2766. y = max(py0 + 2, min(py1 - 2, y))
  2767. pts_xy.append((x, y))
  2768. if pts_xy:
  2769. has_any_point = True
  2770. if len(pts_xy) >= 2:
  2771. flat = [coord for pt in pts_xy for coord in pt]
  2772. dash_pat = (5, 3) if tr["dashed"] else ()
  2773. cv.create_line(*flat, fill=tr["color"], width=tr["width"] + 0.5, dash=dash_pat)
  2774. stride = max(1, len(pts_xy) // 18)
  2775. for k, (mx, my) in enumerate(pts_xy):
  2776. if k == 0 or k == len(pts_xy) - 1 or k % stride == 0:
  2777. r_mk = 3 if tr["width"] >= 2 else 2
  2778. if tr["diamond"]:
  2779. cv.create_polygon(mx, my - r_mk - 1, mx + r_mk + 1, my, mx, my + r_mk + 1, mx - r_mk - 1, my, fill=tr["color"], outline="")
  2780. else:
  2781. cv.create_oval(mx - r_mk, my - r_mk, mx + r_mk, my + r_mk, fill=tr["color"], outline="")
  2782. if not has_any_point:
  2783. cv.create_text(
  2784. px0 + pw / 2,
  2785. py0 + ph / 2,
  2786. text="等待接收 0x42 温度数据,或点击【导入日志绘图】...",
  2787. font=("Microsoft YaHei", 9),
  2788. fill="#8C9BAF",
  2789. )
  2790. # Hover crosshair & tooltip
  2791. h_idx = chamber_hover_idx.get(cid)
  2792. if h_idx is not None and 0 <= h_idx < n_pts:
  2793. if n_pts <= 1:
  2794. hx = px0 + pw / 2.0
  2795. else:
  2796. hx = px0 + ((elapsed[h_idx] - elapsed[0]) / t_span) * pw if elapsed[-1] > elapsed[0] else px0 + (h_idx / (n_pts - 1)) * pw
  2797. cv.create_line(hx, py0, hx, py1, fill="#475569", dash=(2, 2))
  2798. tip_items = [f"点#{h_idx+1} ({series['time_labels'][h_idx]}, +{elapsed[h_idx]:.1f}s)"]
  2799. for tr in traces[:8]:
  2800. v_at = tr["values"][h_idx] if h_idx < len(tr["values"]) else None
  2801. if v_at is not None:
  2802. v_s = f"{v_at:.1f}°C" if isinstance(v_at, float) else f"{v_at}°C"
  2803. tip_items.append(f"{tr['label']}:{v_s}")
  2804. tip_text = " | ".join(tip_items)
  2805. cv.create_rectangle(px0 + 4, py0 + 3, min(px1 - 4, px0 + 10 + len(tip_text) * 6), py0 + 21, fill="#FFFDE7", outline="#FBC02D")
  2806. cv.create_text(px0 + 8, py0 + 12, anchor="w", text=tip_text, font=("Consolas", 8), fill="#1E293B")
  2807. # Legend on right side
  2808. lx0 = px1 + 6
  2809. ly = py0 + 6
  2810. cv.create_text(lx0, ly, anchor="w", text="图例 / 最新值", font=("Microsoft YaHei", 8, "bold"), fill="#1E293B")
  2811. ly += 15
  2812. for tr in traces[:12]:
  2813. last_v = next((v for v in reversed(tr["values"]) if v is not None), None)
  2814. v_txt = f"{last_v:.1f}°C" if isinstance(last_v, float) else (f"{last_v}°C" if last_v is not None else "--")
  2815. dash_pat = (3, 2) if tr["dashed"] else ()
  2816. cv.create_line(lx0, ly, lx0 + 12, ly, fill=tr["color"], width=max(2, tr["width"]), dash=dash_pat)
  2817. cv.create_text(lx0 + 15, ly, anchor="w", text=f"{tr['label']}:{v_txt}", font=("Consolas", 8), fill=tr["color"])
  2818. ly += 14
  2819. if ly > py1:
  2820. break
  2821. def redraw_all_chamber_canvases(*_):
  2822. lbl_curve_count.config(text=f"采样点: {len(curve_store)}")
  2823. for cid in CHAMBER_IDS:
  2824. draw_single_chamber_canvas(cid)
  2825. for cid, cv in chamber_canvases.items():
  2826. cv.bind("<Configure>", lambda _e, c=cid: draw_single_chamber_canvas(c))
  2827. def _on_motion(event, c=cid):
  2828. g = chamber_plot_geom.get(c)
  2829. if not g or g["n_pts"] == 0:
  2830. return
  2831. if g["px0"] <= event.x <= g["px1"] and g["py0"] <= event.y <= g["py1"]:
  2832. if g["n_pts"] == 1:
  2833. idx_near = 0
  2834. else:
  2835. rel_x = (event.x - g["px0"]) / max(1.0, g["pw"])
  2836. target_t = g["elapsed"][0] + rel_x * g["t_span"]
  2837. idx_near = min(range(g["n_pts"]), key=lambda i: abs(g["elapsed"][i] - target_t))
  2838. if chamber_hover_idx.get(c) != idx_near:
  2839. chamber_hover_idx[c] = idx_near
  2840. draw_single_chamber_canvas(c)
  2841. elif chamber_hover_idx.get(c) is not None:
  2842. chamber_hover_idx[c] = None
  2843. draw_single_chamber_canvas(c)
  2844. def _on_leave(_event, c=cid):
  2845. if chamber_hover_idx.get(c) is not None:
  2846. chamber_hover_idx[c] = None
  2847. draw_single_chamber_canvas(c)
  2848. cv.bind("<Motion>", _on_motion)
  2849. cv.bind("<Leave>", _on_leave)
  2850. combo_mode.bind("<<ComboboxSelected>>", redraw_all_chamber_canvases)
  2851. combo_win.bind("<<ComboboxSelected>>", redraw_all_chamber_canvases)
  2852. def print_or_export_curves(direct_print: bool = True):
  2853. if not apply_chamber_mapping(silent=False):
  2854. return
  2855. mode, max_pts, ign_zero = _current_mode_and_window()
  2856. ts_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  2857. out_dir = Path(disk_logger.log_dir)
  2858. out_dir.mkdir(parents=True, exist_ok=True)
  2859. png_path = out_dir / f"chamber_curves_{product}_{ts_tag}.png"
  2860. svg_path = out_dir / f"chamber_curves_{product}_{ts_tag}.svg"
  2861. csv_path = out_dir / f"chamber_curves_{product}_{ts_tag}.csv"
  2862. try:
  2863. png_bytes = render_chamber_curves_png(
  2864. curve_store, chamber_mapping, product=product, board=model.board,
  2865. mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
  2866. thermal_session=thermal_session,
  2867. )
  2868. png_path.write_bytes(png_bytes)
  2869. svg_text = render_chamber_curves_svg(
  2870. curve_store, chamber_mapping, product=product, board=model.board,
  2871. mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
  2872. thermal_session=thermal_session,
  2873. )
  2874. svg_path.write_text(svg_text, encoding="utf-8")
  2875. csv_text = export_chamber_curves_csv(
  2876. curve_store, chamber_mapping, max_points=max_pts, ignore_zero_ct=ign_zero,
  2877. )
  2878. csv_path.write_text(csv_text, encoding="utf-8-sig")
  2879. lbl_map_status.config(text=f"已生成图像: {png_path.name}", foreground="#006600")
  2880. if direct_print:
  2881. opened = False
  2882. if sys.platform == "win32":
  2883. try:
  2884. os.startfile(str(png_path))
  2885. opened = True
  2886. except Exception:
  2887. pass
  2888. elif sys.platform == "darwin":
  2889. try:
  2890. subprocess.Popen(["open", str(png_path)])
  2891. opened = True
  2892. except Exception:
  2893. pass
  2894. else:
  2895. try:
  2896. subprocess.Popen(["xdg-open", str(png_path)])
  2897. opened = True
  2898. except Exception:
  2899. pass
  2900. messagebox.showinfo(
  2901. "四腔温度曲线图像已生成",
  2902. f"已直接生成四腔体内存温度与Sensor温度曲线图:\n\n"
  2903. f"• 高清 PNG 图像:\n {png_path}\n"
  2904. f"• 矢量 SVG 图像:\n {svg_path}\n"
  2905. f"• 曲线数据 CSV:\n {csv_path}\n\n"
  2906. + ("已自动调用系统查看器打开图像,可直接查看或 Ctrl+P 打印。" if opened else "可在日志目录中直接打开或打印该图像。"),
  2907. )
  2908. except Exception as exc:
  2909. messagebox.showerror("图像打印/导出失败", str(exc))
  2910. def save_curves_as_dialog():
  2911. if not apply_chamber_mapping(silent=False):
  2912. return
  2913. mode, max_pts, ign_zero = _current_mode_and_window()
  2914. ts_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  2915. path = filedialog.asksaveasfilename(
  2916. title="另存四腔温度曲线图像或数据",
  2917. defaultextension=".png",
  2918. initialfile=f"chamber_curves_{product}_{ts_tag}.png",
  2919. filetypes=[
  2920. ("PNG 高清曲线图", "*.png"),
  2921. ("SVG 矢量曲线图", "*.svg"),
  2922. ("CSV 温度数据表", "*.csv"),
  2923. ],
  2924. )
  2925. if not path:
  2926. return
  2927. target = Path(path)
  2928. try:
  2929. ext = target.suffix.lower()
  2930. if ext == ".svg":
  2931. target.write_text(
  2932. render_chamber_curves_svg(
  2933. curve_store, chamber_mapping, product=product, board=model.board,
  2934. mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
  2935. ),
  2936. encoding="utf-8",
  2937. )
  2938. elif ext == ".csv":
  2939. target.write_text(
  2940. export_chamber_curves_csv(
  2941. curve_store, chamber_mapping, max_points=max_pts, ignore_zero_ct=ign_zero,
  2942. ),
  2943. encoding="utf-8-sig",
  2944. )
  2945. else:
  2946. target.write_bytes(
  2947. render_chamber_curves_png(
  2948. curve_store, chamber_mapping, product=product, board=model.board,
  2949. mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
  2950. )
  2951. )
  2952. lbl_map_status.config(text=f"已另存为: {target.name}", foreground="#006600")
  2953. except Exception as exc:
  2954. messagebox.showerror("另存失败", str(exc))
  2955. def import_log_for_curves():
  2956. path = filedialog.askopenfilename(
  2957. title="导入日志文件生成温度曲线 (支持 pwm_scope JSONL / GUI 会话日志)",
  2958. initialdir=str(disk_logger.log_dir),
  2959. filetypes=[
  2960. ("日志与数据文件", "*.jsonl *.log *.txt"),
  2961. ("所有文件", "*.*"),
  2962. ],
  2963. )
  2964. if not path:
  2965. return
  2966. try:
  2967. count = curve_store.load_from_log_file(Path(path), model=model)
  2968. thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
  2969. refresh_thermal_test_ui()
  2970. redraw_all_chamber_canvases()
  2971. lbl_map_status.config(text=f"从 {Path(path).name} 导入了 {count} 条温度记录", foreground="#006600")
  2972. if count == 0:
  2973. messagebox.showwarning("未找到温度帧", "所选日志文件中未解析到有效的 0x42 GET_DATA 温度记录或 CYCLE 数据。")
  2974. except Exception as exc:
  2975. messagebox.showerror("导入日志失败", str(exc))
  2976. def clear_curves():
  2977. curve_store.clear()
  2978. thermal_session.reset_stats()
  2979. refresh_thermal_test_ui()
  2980. redraw_all_chamber_canvases()
  2981. lbl_map_status.config(text="已清空曲线历史数据与达标统计", foreground="#555555")
  2982. ttk.Button(plot_ctrl_bar, text="🗑 清空曲线", command=clear_curves).pack(side="right", padx=3)
  2983. ttk.Button(plot_ctrl_bar, text="📂 导入日志绘图", command=import_log_for_curves).pack(side="right", padx=3)
  2984. ttk.Button(plot_ctrl_bar, text="💾 另存图像为...", command=save_curves_as_dialog).pack(side="right", padx=3)
  2985. ttk.Button(plot_ctrl_bar, text="🖨 直接打印/导出曲线图 (PNG/SVG)", command=lambda: print_or_export_curves(True)).pack(side="right", padx=4)
  2986. # -----------------------------------------------------------------------
  2987. # TAB 2.5: 高温罩温度测试 (High-Temperature Hood Thermal Test & Fan Study)
  2988. # -----------------------------------------------------------------------
  2989. tab_thermal_test = ttk.Frame(notebook, padding=8)
  2990. notebook.add(tab_thermal_test, text="🔥 高温罩温度测试")
  2991. # Section A: Target Temperature & Pass Minimum Configuration
  2992. tt_target_frame = ttk.LabelFrame(
  2993. tab_thermal_test,
  2994. text="🎯 1. 高温罩四腔预期目标温度与最低通过温度配置 (暂定 70°C;先达标腔体锁定耗时后仍持续记录全部腔体数据)",
  2995. padding=6,
  2996. )
  2997. tt_target_frame.pack(fill="x", pady=3)
  2998. tt_row1 = ttk.Frame(tt_target_frame)
  2999. tt_row1.pack(fill="x", pady=2)
  3000. ttk.Label(tt_row1, text="测试名称:").pack(side="left", padx=2)
  3001. tt_name_var = tk.StringVar(value=f"{model.board} 高温罩升温测试")
  3002. ttk.Entry(tt_row1, textvariable=tt_name_var, width=24).pack(side="left", padx=4)
  3003. ttk.Label(tt_row1, text="高温罩四腔最低通过温度(°C):", font=("", 9, "bold"), foreground="#B45309").pack(side="left", padx=(10, 2))
  3004. tt_pass_min_var = tk.StringVar(value="70")
  3005. ttk.Spinbox(tt_row1, from_=20, to=200, width=5, textvariable=tt_pass_min_var).pack(side="left", padx=2)
  3006. tt_chamber_target_vars: dict[int, tk.StringVar] = {}
  3007. for cid in CHAMBER_IDS:
  3008. ttk.Label(tt_row1, text=f"腔{cid}目标(°C):").pack(side="left", padx=(8, 2))
  3009. v_t = tk.StringVar(value="70")
  3010. tt_chamber_target_vars[cid] = v_t
  3011. ttk.Spinbox(tt_row1, from_=20, to=200, width=5, textvariable=v_t).pack(side="left", padx=2)
  3012. def sync_all_chamber_targets_to_pass_min():
  3013. p_val = tt_pass_min_var.get().strip() or "70"
  3014. for cid in CHAMBER_IDS:
  3015. tt_chamber_target_vars[cid].set(p_val)
  3016. apply_thermal_test_config(recalc=True)
  3017. ttk.Button(tt_row1, text="同步至四腔", command=sync_all_chamber_targets_to_pass_min).pack(side="left", padx=6)
  3018. EVAL_MODE_MAP = {"腔体均温 (AVG)": "avg", "腔体最高 (MAX)": "max", "腔体最低 (MIN)": "min"}
  3019. ttk.Label(tt_row1, text="Sensor判定:").pack(side="left", padx=(8, 2))
  3020. tt_ct_eval_var = tk.StringVar(value="腔体均温 (AVG)")
  3021. ttk.Combobox(tt_row1, textvariable=tt_ct_eval_var, values=list(EVAL_MODE_MAP.keys()), width=13, state="readonly").pack(side="left", padx=2)
  3022. ttk.Label(tt_row1, text="内存判定:").pack(side="left", padx=(6, 2))
  3023. tt_bmc_eval_var = tk.StringVar(value="腔体均温 (AVG)")
  3024. ttk.Combobox(tt_row1, textvariable=tt_bmc_eval_var, values=list(EVAL_MODE_MAP.keys()), width=13, state="readonly").pack(side="left", padx=2)
  3025. # Section B: Fan Speed & Fan Intervention Timing / Reference Temperature Study
  3026. tt_fan_frame = ttk.LabelFrame(
  3027. tab_thermal_test,
  3028. text="🌀 2. 风扇转速与介入时机实验参数 (探究风扇转速、风扇开始介入时间或参考温度与腔体升温达标时间的关系)",
  3029. padding=6,
  3030. )
  3031. tt_fan_frame.pack(fill="x", pady=3)
  3032. tt_row2 = ttk.Frame(tt_fan_frame)
  3033. tt_row2.pack(fill="x", pady=2)
  3034. ttk.Label(tt_row2, text="PTC加热(%):").pack(side="left", padx=2)
  3035. tt_ptc_duty_var = tk.StringVar(value="100")
  3036. ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_ptc_duty_var).pack(side="left", padx=2)
  3037. ttk.Label(tt_row2, text="SSR加热(%):").pack(side="left", padx=(6, 2))
  3038. tt_ssr_duty_var = tk.StringVar(value="100")
  3039. ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_ssr_duty_var).pack(side="left", padx=2)
  3040. ttk.Label(tt_row2, text="初始风扇(%):").pack(side="left", padx=(8, 2))
  3041. tt_init_fan_var = tk.StringVar(value="0")
  3042. ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_init_fan_var).pack(side="left", padx=2)
  3043. ttk.Label(tt_row2, text="介入后风扇(%):", font=("", 9, "bold"), foreground="#153259").pack(side="left", padx=(8, 2))
  3044. tt_active_fan_var = tk.StringVar(value="50")
  3045. ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_active_fan_var).pack(side="left", padx=2)
  3046. INTERVENTION_MODE_MAP = {
  3047. "按介入时间 (秒)": "time_s",
  3048. "按参考温度 (°C)": "ref_temp_c",
  3049. "立即介入 (0s)": "immediate",
  3050. "仅手动/纯观测": "manual",
  3051. }
  3052. ttk.Label(tt_row2, text="风扇介入方式:").pack(side="left", padx=(8, 2))
  3053. tt_intervene_mode_var = tk.StringVar(value="按介入时间 (秒)")
  3054. ttk.Combobox(tt_row2, textvariable=tt_intervene_mode_var, values=list(INTERVENTION_MODE_MAP.keys()), width=14, state="readonly").pack(side="left", padx=2)
  3055. ttk.Label(tt_row2, text="介入时间(s):").pack(side="left", padx=(6, 2))
  3056. tt_intervene_time_var = tk.StringVar(value="120")
  3057. ttk.Spinbox(tt_row2, from_=0, to=3600, width=5, textvariable=tt_intervene_time_var).pack(side="left", padx=2)
  3058. ttk.Label(tt_row2, text="参考温度(°C):").pack(side="left", padx=(6, 2))
  3059. tt_intervene_temp_var = tk.StringVar(value="55")
  3060. ttk.Spinbox(tt_row2, from_=20, to=200, width=5, textvariable=tt_intervene_temp_var).pack(side="left", padx=2)
  3061. tt_auto_ctrl_var = tk.BooleanVar(value=True)
  3062. ttk.Checkbutton(
  3063. tt_row2,
  3064. text="测试时自动下发SET并轮询GET",
  3065. variable=tt_auto_ctrl_var,
  3066. ).pack(side="left", padx=8)
  3067. # Section C: Controls & Backend Sync Bar
  3068. tt_ctrl_bar = ttk.Frame(tab_thermal_test, padding=3)
  3069. tt_ctrl_bar.pack(fill="x", pady=2)
  3070. lbl_tt_status = ttk.Label(
  3071. tt_ctrl_bar,
  3072. text="状态: 待机 (点击【开始温度测试】或【重新统计当前曲线】计算各腔 Sensor 与内存达标时间)",
  3073. font=("Microsoft YaHei", 9, "bold"),
  3074. foreground="#153259",
  3075. )
  3076. lbl_tt_status.pack(side="left", padx=4)
  3077. tt_backend_url_var = tk.StringVar(value=os.environ.get("PROD2U_THERMAL_BACKEND_URL", "http://192.168.2.25:8766"))
  3078. # Section D: 4-Chamber + Overall Hood Reach-Time Treeview Table
  3079. tt_table_frame = ttk.LabelFrame(
  3080. tab_thermal_test,
  3081. text="⏱️ 3. 各腔体 Sensor(CT) 温度与 内存(BMC) 温度达标时间实时统计表 (先达标腔体持续记录验证)",
  3082. padding=6,
  3083. )
  3084. tt_table_frame.pack(fill="both", expand=True, pady=3)
  3085. tt_cols = (
  3086. "chamber",
  3087. "target",
  3088. "sensor_temps",
  3089. "sensor_time",
  3090. "memory_temps",
  3091. "memory_time",
  3092. "continuous_status",
  3093. )
  3094. tt_tree = ttk.Treeview(tt_table_frame, columns=tt_cols, show="headings", height=6)
  3095. tt_tree.heading("chamber", text="腔体 / 区域")
  3096. tt_tree.heading("target", text="预期目标 / 最低通过")
  3097. tt_tree.heading("sensor_temps", text="Sensor温度 (初始 / 当前 / 峰值)")
  3098. tt_tree.heading("sensor_time", text="Sensor 达到目标耗时")
  3099. tt_tree.heading("memory_temps", text="内存BMC温度 (初始 / 当前 / 峰值)")
  3100. tt_tree.heading("memory_time", text="内存BMC 达到目标耗时")
  3101. tt_tree.heading("continuous_status", text="状态与达标后持续记录点数")
  3102. tt_tree.column("chamber", width=130, anchor="center")
  3103. tt_tree.column("target", width=135, anchor="center")
  3104. tt_tree.column("sensor_temps", width=185, anchor="center")
  3105. tt_tree.column("sensor_time", width=155, anchor="center")
  3106. tt_tree.column("memory_temps", width=185, anchor="center")
  3107. tt_tree.column("memory_time", width=155, anchor="center")
  3108. tt_tree.column("continuous_status", width=210, anchor="center")
  3109. tt_tree.pack(fill="both", expand=True)
  3110. # Section E: Multi-Run Experiment Comparison Table + Backend Bar
  3111. tt_exp_frame = ttk.LabelFrame(
  3112. tab_thermal_test,
  3113. text="🔬 4. 风扇转速 / 介入时间 / 参考温度 vs 升温达标时间多轮实验对比与远程后端 (192.168.2.25)",
  3114. padding=6,
  3115. )
  3116. tt_exp_frame.pack(fill="both", expand=True, pady=3)
  3117. exp_cols = (
  3118. "run_id",
  3119. "fan_cfg",
  3120. "intervene",
  3121. "c1_reach",
  3122. "c2_reach",
  3123. "c3_reach",
  3124. "c4_reach",
  3125. "hood_reach",
  3126. )
  3127. exp_tree = ttk.Treeview(tt_exp_frame, columns=exp_cols, show="headings", height=4)
  3128. exp_tree.heading("run_id", text="实验轮次 / 名称")
  3129. exp_tree.heading("fan_cfg", text="加热 / 风扇转速")
  3130. exp_tree.heading("intervene", text="风扇介入时机 / 温度")
  3131. exp_tree.heading("c1_reach", text="腔1 (Sensor/内存)")
  3132. exp_tree.heading("c2_reach", text="腔2 (Sensor/内存)")
  3133. exp_tree.heading("c3_reach", text="腔3 (Sensor/内存)")
  3134. exp_tree.heading("c4_reach", text="腔4 (Sensor/内存)")
  3135. exp_tree.heading("hood_reach", text="四腔整体通过耗时")
  3136. exp_tree.column("run_id", width=165, anchor="w")
  3137. exp_tree.column("fan_cfg", width=145, anchor="center")
  3138. exp_tree.column("intervene", width=165, anchor="center")
  3139. exp_tree.column("c1_reach", width=125, anchor="center")
  3140. exp_tree.column("c2_reach", width=125, anchor="center")
  3141. exp_tree.column("c3_reach", width=125, anchor="center")
  3142. exp_tree.column("c4_reach", width=125, anchor="center")
  3143. exp_tree.column("hood_reach", width=145, anchor="center")
  3144. exp_tree.pack(fill="both", expand=True, pady=2)
  3145. backend_bar = ttk.Frame(tt_exp_frame)
  3146. backend_bar.pack(fill="x", pady=2)
  3147. ttk.Label(backend_bar, text="远程测试后端地址 (192.168.2.25 容器):").pack(side="left", padx=2)
  3148. ttk.Entry(backend_bar, textvariable=tt_backend_url_var, width=28, font=("Consolas", 9)).pack(side="left", padx=4)
  3149. def apply_thermal_test_config(recalc: bool = False) -> bool:
  3150. try:
  3151. pass_min = float(tt_pass_min_var.get().strip() or "70")
  3152. c_targets = {
  3153. cid: float(tt_chamber_target_vars[cid].get().strip() or "70")
  3154. for cid in CHAMBER_IDS
  3155. }
  3156. thermal_session.test_name = tt_name_var.get().strip() or f"{model.board} 高温罩升温测试"
  3157. thermal_session.bmc_eval_mode = EVAL_MODE_MAP.get(tt_bmc_eval_var.get(), "avg")
  3158. thermal_session.ct_eval_mode = EVAL_MODE_MAP.get(tt_ct_eval_var.get(), "avg")
  3159. thermal_session.ptc_duty_percent = max(0, min(100, int(float(tt_ptc_duty_var.get() or "100"))))
  3160. thermal_session.ssr_duty_percent = max(0, min(100, int(float(tt_ssr_duty_var.get() or "100"))))
  3161. thermal_session.initial_fan_duty_percent = max(0, min(100, int(float(tt_init_fan_var.get() or "0"))))
  3162. thermal_session.active_fan_duty_percent = max(0, min(100, int(float(tt_active_fan_var.get() or "50"))))
  3163. thermal_session.fan_intervention_mode = INTERVENTION_MODE_MAP.get(tt_intervene_mode_var.get(), "time_s")
  3164. thermal_session.fan_intervention_time_s = max(0.0, float(tt_intervene_time_var.get() or "120"))
  3165. thermal_session.fan_intervention_ref_temp_c = float(tt_intervene_temp_var.get() or "55")
  3166. thermal_session.backend_url = tt_backend_url_var.get().strip()
  3167. thermal_session.set_targets(pass_min, c_targets)
  3168. if recalc:
  3169. thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
  3170. refresh_thermal_test_ui()
  3171. redraw_all_chamber_canvases()
  3172. return True
  3173. except Exception as exc:
  3174. messagebox.showerror("温度测试参数错误", str(exc))
  3175. return False
  3176. def refresh_thermal_test_ui():
  3177. for item in tt_tree.get_children():
  3178. tt_tree.delete(item)
  3179. rep = thermal_session.summary()
  3180. for cid in CHAMBER_IDS:
  3181. st = thermal_session.chamber_stats[cid]
  3182. s_t_txt = (
  3183. f"{st['sensor_initial_c'] or '--'} / {st['sensor_current_c'] or '--'} / {st['sensor_peak_c'] or '--'} °C"
  3184. )
  3185. m_t_txt = (
  3186. f"{st['memory_initial_c'] or '--'} / {st['memory_current_c'] or '--'} / {st['memory_peak_c'] or '--'} °C"
  3187. )
  3188. s_reach_txt = (
  3189. f"✅ {format_duration_mmss(st['sensor_time_to_target_s'])}"
  3190. if st["sensor_reached"]
  3191. else "⏳ 未达标"
  3192. )
  3193. m_reach_txt = (
  3194. f"✅ {format_duration_mmss(st['memory_time_to_target_s'])}"
  3195. if st["memory_reached"]
  3196. else "⏳ 未达标"
  3197. )
  3198. if st["both_reached"]:
  3199. status_txt = f"✅ 双达标 (持续记录 +{st['post_target_samples']} 点)"
  3200. elif st["sensor_reached"] or st["memory_reached"]:
  3201. status_txt = f"🌓 单项达标 (持续记录 +{st['post_target_samples']} 点)"
  3202. else:
  3203. status_txt = "🔥 加热升温中..." if thermal_session.active else "待达标"
  3204. tt_tree.insert(
  3205. "",
  3206. "end",
  3207. values=(
  3208. f"腔体 {cid}",
  3209. f"目标 {st['target_temp_c']:.0f}°C / 通过≥{st['pass_min_temp_c']:.0f}°C",
  3210. s_t_txt,
  3211. s_reach_txt,
  3212. m_t_txt,
  3213. m_reach_txt,
  3214. status_txt,
  3215. ),
  3216. )
  3217. hs = rep["hood_summary"]
  3218. first_info = rep["first_reached"]
  3219. first_str = (
  3220. f"腔{first_info['chamber_id']}于{first_info['elapsed_s']:.1f}s率先达标,已持续追记+{first_info['total_post_target_samples']}点"
  3221. if first_info["chamber_id"] is not None
  3222. else "尚无腔体达标"
  3223. )
  3224. tt_tree.insert(
  3225. "",
  3226. "end",
  3227. values=(
  3228. "🏆 高温罩四腔汇总",
  3229. f"四腔最低通过 ≥{thermal_session.overall_pass_min_temp_c:.0f}°C",
  3230. f"已达标: {hs['sensor_reached_count']}/4 腔",
  3231. f"🌟 {format_duration_mmss(hs['hood_sensor_reach_time_s'])}" if hs["sensor_all_4_reached"] else f"{hs['sensor_reached_count']}/4 达标",
  3232. f"已达标: {hs['memory_reached_count']}/4 腔",
  3233. f"🌟 {format_duration_mmss(hs['hood_memory_reach_time_s'])}" if hs["memory_all_4_reached"] else f"{hs['memory_reached_count']}/4 达标",
  3234. first_str,
  3235. ),
  3236. )
  3237. exp = rep["experiment_params"]
  3238. fan_badge = (
  3239. f"风扇已介入({exp['active_fan_duty_percent']}% @ {exp['fan_intervened_reason']})"
  3240. if exp["fan_intervened"]
  3241. else f"风扇待介入(当前{exp['current_fan_duty_percent']}% -> 目标{exp['active_fan_duty_percent']}%)"
  3242. )
  3243. state_word = "🟢 正在测试 (持续记录中)" if thermal_session.active else "⚪ 未运行/已完成"
  3244. lbl_tt_status.config(
  3245. text=f"{state_word} | 已耗时: {rep['elapsed_total_s']:.1f}s | 样本: {rep['sample_count']} | {fan_badge}"
  3246. )
  3247. def send_thermal_test_set(note_prefix: str = "温度测试自动控制"):
  3248. vals = thermal_session.build_set_values(model)
  3249. for i, v in enumerate(vals):
  3250. if i < len(set_vars):
  3251. set_vars[i].set(str(v))
  3252. with serial_lock:
  3253. sp = serial_port_obj
  3254. if sp and sp.is_open and tt_auto_ctrl_var.get():
  3255. try:
  3256. f = model.set_all(vals)
  3257. request_queue.put(("SET", f, f"{note_prefix}: PTC={thermal_session.ptc_duty_percent}% FAN={thermal_session.current_fan_duty_percent}%"))
  3258. dispatch_next_request()
  3259. except Exception as exc:
  3260. append_log("ERR", "", f"温度测试下发 SET 失败: {exc}")
  3261. def start_thermal_test():
  3262. if not apply_thermal_test_config(recalc=False):
  3263. return
  3264. curve_store.clear()
  3265. thermal_session.start()
  3266. refresh_thermal_test_ui()
  3267. redraw_all_chamber_canvases()
  3268. send_thermal_test_set("温度测试启动阶段")
  3269. with serial_lock:
  3270. sp = serial_port_obj
  3271. if sp and sp.is_open and tt_auto_ctrl_var.get() and not poll_var.get():
  3272. poll_var.set(True)
  3273. on_poll_toggle()
  3274. def stop_thermal_test():
  3275. thermal_session.stop()
  3276. record_run_to_comparison_table()
  3277. refresh_thermal_test_ui()
  3278. def record_run_to_comparison_table():
  3279. rep = thermal_session.summary()
  3280. exp = rep["experiment_params"]
  3281. hs = rep["hood_summary"]
  3282. experiment_history.append(rep)
  3283. fan_cfg = f"PTC{exp['ptc_duty_percent']}% | 风扇{exp['initial_fan_duty_percent']}%→{exp['active_fan_duty_percent']}%"
  3284. if exp["fan_intervened"]:
  3285. intervene_txt = f"{exp['fan_intervened_elapsed_s']:.0f}s / {exp['fan_intervened_temp_c'] or '--'}°C"
  3286. elif exp["fan_intervention_mode"] == "time_s":
  3287. intervene_txt = f"定时 {exp['fan_intervention_time_s']:.0f}s"
  3288. elif exp["fan_intervention_mode"] == "ref_temp_c":
  3289. intervene_txt = f"定温 {exp['fan_intervention_ref_temp_c']:.0f}°C"
  3290. else:
  3291. intervene_txt = exp["fan_intervention_mode"]
  3292. def ch_pair(c_id: int) -> str:
  3293. st_c = thermal_session.chamber_stats[c_id]
  3294. s_v = f"{st_c['sensor_time_to_target_s']:.0f}s" if st_c["sensor_time_to_target_s"] is not None else "--"
  3295. m_v = f"{st_c['memory_time_to_target_s']:.0f}s" if st_c["memory_time_to_target_s"] is not None else "--"
  3296. return f"S:{s_v} / M:{m_v}"
  3297. hood_txt = (
  3298. f"S:{hs['hood_sensor_reach_time_s'] or '--'}s / M:{hs['hood_memory_reach_time_s'] or '--'}s"
  3299. )
  3300. exp_tree.insert(
  3301. "",
  3302. "end",
  3303. values=(
  3304. f"{rep['session_id']} ({rep['test_name'][:10]})",
  3305. fan_cfg,
  3306. intervene_txt,
  3307. ch_pair(1),
  3308. ch_pair(2),
  3309. ch_pair(3),
  3310. ch_pair(4),
  3311. hood_txt,
  3312. ),
  3313. )
  3314. def export_thermal_test_report():
  3315. if not apply_thermal_test_config(recalc=False):
  3316. return
  3317. if thermal_session.sample_count == 0 and len(curve_store) > 0:
  3318. thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
  3319. refresh_thermal_test_ui()
  3320. ts_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  3321. out_dir = Path(disk_logger.log_dir)
  3322. out_dir.mkdir(parents=True, exist_ok=True)
  3323. json_path = out_dir / f"thermal_test_report_{product}_{ts_tag}.json"
  3324. csv_path = out_dir / f"thermal_test_summary_{product}_{ts_tag}.csv"
  3325. png_path = out_dir / f"thermal_test_curves_{product}_{ts_tag}.png"
  3326. try:
  3327. mode, max_pts, ign_zero = _current_mode_and_window()
  3328. full_report = {
  3329. "report": thermal_session.summary(),
  3330. "mapping": chamber_mapping.to_dict(),
  3331. "experiment_history": experiment_history,
  3332. }
  3333. json_path.write_text(json.dumps(full_report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  3334. csv_path.write_text(thermal_session.export_summary_csv(), encoding="utf-8-sig")
  3335. png_path.write_bytes(
  3336. render_chamber_curves_png(
  3337. curve_store, chamber_mapping, product=product, board=model.board,
  3338. mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
  3339. thermal_session=thermal_session,
  3340. )
  3341. )
  3342. messagebox.showinfo(
  3343. "温度测试报告已导出",
  3344. f"已导出高温罩四腔温度测试报告:\n\n"
  3345. f"• JSON 详细报告:\n {json_path}\n"
  3346. f"• CSV 达标时间统计表:\n {csv_path}\n"
  3347. f"• PNG 带目标温度线四腔曲线图:\n {png_path}",
  3348. )
  3349. except Exception as exc:
  3350. messagebox.showerror("导出温度测试报告失败", str(exc))
  3351. def sync_thermal_test_to_backend():
  3352. if not apply_thermal_test_config(recalc=False):
  3353. return
  3354. if thermal_session.sample_count == 0 and len(curve_store) > 0:
  3355. thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
  3356. refresh_thermal_test_ui()
  3357. try:
  3358. res = thermal_session.sync_to_backend(
  3359. curve_store, chamber_mapping, backend_url=tt_backend_url_var.get().strip()
  3360. )
  3361. record_run_to_comparison_table()
  3362. messagebox.showinfo(
  3363. "已同步至远程测试后端",
  3364. f"测试数据已成功上传至后端 ({tt_backend_url_var.get().strip()}):\n"
  3365. f"会话 ID: {res.get('session_id', thermal_session.session_id)}\n"
  3366. f"当前后端累计实验组数: {res.get('total_runs', '--')}",
  3367. )
  3368. except Exception as exc:
  3369. messagebox.showerror(
  3370. "同步远程后端失败",
  3371. f"无法连接温度测试后端 {tt_backend_url_var.get().strip()}:\n{exc}\n\n"
  3372. f"请确认 192.168.2.25 容器内 thermal_test_server.py 已启动。",
  3373. )
  3374. def open_thermal_web_frontend():
  3375. import webbrowser
  3376. url = tt_backend_url_var.get().strip() or "http://192.168.2.25:8766"
  3377. webbrowser.open(url)
  3378. ttk.Button(tt_ctrl_bar, text="📊 导出测试报告(JSON/CSV/PNG)", command=export_thermal_test_report).pack(side="right", padx=3)
  3379. ttk.Button(tt_ctrl_bar, text="📌 记录至对比表", command=record_run_to_comparison_table).pack(side="right", padx=3)
  3380. ttk.Button(tt_ctrl_bar, text="🔄 重新统计当前曲线", command=lambda: apply_thermal_test_config(recalc=True)).pack(side="right", padx=3)
  3381. ttk.Button(tt_ctrl_bar, text="⏹ 停止温度测试", command=stop_thermal_test).pack(side="right", padx=3)
  3382. ttk.Button(tt_ctrl_bar, text="▶️ 开始温度测试 (持续记录)", command=start_thermal_test).pack(side="right", padx=3)
  3383. ttk.Button(backend_bar, text="☁️ 同步当前测试至后端", command=sync_thermal_test_to_backend).pack(side="left", padx=4)
  3384. ttk.Button(backend_bar, text="🌐 打开网页前端 (查看/对比/导出)", command=open_thermal_web_frontend).pack(side="left", padx=4)
  3385. refresh_thermal_test_ui()
  3386. # Quick jump buttons on Tab 1 control bar
  3387. ttk.Button(
  3388. ctrl_bar,
  3389. text="🔥 高温罩温度测试",
  3390. command=lambda: (notebook.select(tab_thermal_test), refresh_thermal_test_ui()),
  3391. ).pack(side="right", padx=4)
  3392. ttk.Button(
  3393. ctrl_bar,
  3394. text="📈 腔体温度曲线 / 图像打印",
  3395. command=lambda: (notebook.select(tab_curves), redraw_all_chamber_canvases()),
  3396. ).pack(side="right", padx=4)
  3397. # -----------------------------------------------------------------------
  3398. # TAB 3: SET 命令生成与下发 (SET_ALL Builder & Decoder)
  3399. # -----------------------------------------------------------------------
  3400. if product == "6400-v2":
  3401. tab_set_view = ttk.Frame(notebook)
  3402. notebook.add(tab_set_view, text="⚙️ SET 命令生成与解析")
  3403. set_scroll = ttk.Scrollbar(tab_set_view, orient="vertical")
  3404. set_scroll.pack(side="right", fill="y")
  3405. set_canvas = tk.Canvas(tab_set_view, highlightthickness=0, yscrollcommand=set_scroll.set)
  3406. set_canvas.pack(side="left", fill="both", expand=True)
  3407. set_scroll.config(command=set_canvas.yview)
  3408. tab_set = ttk.Frame(set_canvas, padding=10)
  3409. set_window = set_canvas.create_window((0, 0), window=tab_set, anchor="nw")
  3410. tab_set.bind("<Configure>", lambda event: set_canvas.configure(scrollregion=set_canvas.bbox("all")))
  3411. set_canvas.bind("<Configure>", lambda event: set_canvas.itemconfigure(set_window, width=event.width))
  3412. else:
  3413. tab_set = ttk.Frame(notebook, padding=10)
  3414. notebook.add(tab_set, text="⚙️ SET 命令生成与解析")
  3415. ttk.Label(tab_set, text=f"{model.board} ({product}) — 输出通道百分比设置 (0..100 %)", font=("", 11, "bold")).pack(anchor="w", pady=4)
  3416. set_vars = []
  3417. for grp, cnt, default in model.groups():
  3418. frame_grp = ttk.LabelFrame(tab_set, text=f"{model.group_label(grp)} 通道 ({cnt} 路)", padding=6)
  3419. frame_grp.pack(fill="x", pady=4)
  3420. grp_vars = []
  3421. # Batch preset bar for large channel groups (e.g. PTC 24 channels)
  3422. if cnt >= 8:
  3423. preset_bar = ttk.Frame(frame_grp)
  3424. preset_bar.pack(fill="x", pady=2)
  3425. ttk.Label(preset_bar, text=f"快捷预设全部 {grp}:", font=("", 9, "bold")).pack(side="left", padx=4)
  3426. def make_set_all_fn(vs, val):
  3427. def fn():
  3428. for v in vs:
  3429. v.set(str(val))
  3430. return fn
  3431. for p_val in (0, 20, 50, 100):
  3432. ttk.Button(preset_bar, text=f"全设 {p_val}%", width=8,
  3433. command=make_set_all_fn(grp_vars, p_val)).pack(side="left", padx=2)
  3434. # Multi-column grid for channels (8 cols for 24 channels -> 3 rows of 8)
  3435. grid_frame = ttk.Frame(frame_grp)
  3436. grid_frame.pack(fill="x", pady=2)
  3437. cols = 8 if cnt >= 16 else (4 if cnt <= 4 else 6)
  3438. if product == "6400-v2":
  3439. cols = 6 if grp == "PTC" else (2 if grp in FAN_GROUP_NAMES else 3)
  3440. for i in range(cnt):
  3441. row = i // cols
  3442. col = i % cols
  3443. cell = ttk.Frame(grid_frame)
  3444. cell.grid(row=row, column=col, padx=4, pady=2, sticky="w")
  3445. label_text = model.output_label(grp, i) + ":"
  3446. label_width = 24 if product == "6400-v2" and grp in (*FAN_GROUP_NAMES, "SSR") else 7
  3447. ttk.Label(cell, text=label_text, width=label_width, font=("Consolas", 9)).pack(side="left")
  3448. var = tk.StringVar(value=str(default))
  3449. set_vars.append(var)
  3450. grp_vars.append(var)
  3451. ttk.Spinbox(cell, from_=0, to=100, width=4, textvariable=var).pack(side="left")
  3452. ttk.Label(cell, text="%", font=("Consolas", 8), foreground="gray").pack(side="left")
  3453. axis_slots = []
  3454. if model.motor:
  3455. frame_motor = ttk.LabelFrame(tab_set, text="12 轴运动段配置 (每轴 5 字节: action + steps:u16le + half_us:u16le)", padding=6)
  3456. frame_motor.pack(fill="x", pady=4)
  3457. ttk.Label(frame_motor, text="不同轴可同时运行;同一轴收到 MOTOR_DONE 后再 PUSH,或先 STOP_CLEAR。发送后动作自动回 NOTHING,温控值保留。",
  3458. foreground="#555555").pack(anchor="w", pady=2)
  3459. for ax in range(12):
  3460. ax_frame = ttk.Frame(frame_motor)
  3461. ax_frame.pack(anchor="w", pady=2)
  3462. ttk.Label(ax_frame, text=f"{MRDIMM_AXIS_NAMES[ax]}: ", width=24, font=("Consolas", 9)).pack(side="left")
  3463. act_var = tk.StringVar(value="NOTHING")
  3464. ttk.Combobox(ax_frame, textvariable=act_var, values=("NOTHING", "PUSH_DOWN", "PUSH_UP", "STOP_CLEAR"), width=11, state="readonly").pack(side="left", padx=2)
  3465. ttk.Label(ax_frame, text="步数:").pack(side="left", padx=2)
  3466. steps_var = tk.StringVar(value="0")
  3467. ttk.Entry(ax_frame, textvariable=steps_var, width=7).pack(side="left", padx=2)
  3468. ttk.Label(ax_frame, text="半周期(us):").pack(side="left", padx=2)
  3469. half_var = tk.StringVar(value="0")
  3470. ttk.Entry(ax_frame, textvariable=half_var, width=7).pack(side="left", padx=2)
  3471. axis_slots.append({"action_var": act_var, "steps_var": steps_var, "half_var": half_var})
  3472. buzzer_var = tk.BooleanVar(value=False)
  3473. if product in ("6400-v2", "mrdimm-chamber"):
  3474. frame_buz = ttk.LabelFrame(tab_set, text="🔔 蜂鸣器触发控制 (SET_ALL 末尾字节,CON146.1 / 球位 H6;看门狗超时自动关闭)", padding=6)
  3475. frame_buz.pack(fill="x", pady=4)
  3476. ttk.Checkbutton(frame_buz, text="触发蜂鸣器开启 (1=ON, 0=OFF)", variable=buzzer_var).pack(side="left", padx=6)
  3477. # Generated SET frame display
  3478. frame_set_res = ttk.LabelFrame(tab_set, text="生成的 SET_ALL 命令报文 (HEX 与逐字段拆解)", padding=8)
  3479. frame_set_res.pack(fill="both", expand=True, pady=6)
  3480. set_btn_bar = ttk.Frame(frame_set_res)
  3481. set_btn_bar.pack(fill="x", pady=2)
  3482. text_set_hex = tk.Text(frame_set_res, height=3, wrap="char", font=("Consolas", 10, "bold"), foreground="#003399")
  3483. text_set_hex.pack(fill="x", pady=4)
  3484. text_set_explain = tk.Text(frame_set_res, height=10, wrap="word", font=("Consolas", 9))
  3485. text_set_explain.pack(fill="both", expand=True, pady=4)
  3486. def do_generate_set() -> bytes:
  3487. vals = [int(v.get()) for v in set_vars]
  3488. motor_reqs = None
  3489. if model.motor:
  3490. act_map = {"NOTHING": 0, "PUSH_DOWN": 1, "PUSH_UP": 2, "STOP_CLEAR": 255}
  3491. motor_reqs = [
  3492. {
  3493. "action": act_map[s["action_var"].get()],
  3494. "steps": int(s["steps_var"].get()),
  3495. "half_period_us": int(s["half_var"].get()),
  3496. }
  3497. for s in axis_slots
  3498. ]
  3499. f = model.set_all(vals, motor_reqs, buzzer=1 if buzzer_var.get() else 0)
  3500. text_set_hex.delete("1.0", "end")
  3501. text_set_hex.insert("1.0", frame_hex(f))
  3502. exp = model.explain(f)
  3503. text_set_explain.delete("1.0", "end")
  3504. text_set_explain.insert("end", f"【报文概览】: {exp['summary']}\n")
  3505. text_set_explain.insert("end", f"【帧类型】: {exp['type']} | 【载荷长度】: {exp['length']} | 【CRC-16/CCITT-FALSE】: {exp['crc_hex']} ({exp['crc_status']})\n")
  3506. text_set_explain.insert("end", "【逐通道明细】:\n")
  3507. for fld in exp.get("fields", []):
  3508. text_set_explain.insert("end", f" • {fld}\n")
  3509. return f
  3510. ttk.Button(set_btn_bar, text="🔨 生成 SET_ALL 命令", command=do_generate_set).pack(side="left", padx=4)
  3511. # -----------------------------------------------------------------------
  3512. # TAB 3: GET 命令生成与解析 (GET_ALL & GET_DATA Decoder)
  3513. # -----------------------------------------------------------------------
  3514. tab_get = ttk.Frame(notebook, padding=10)
  3515. notebook.add(tab_get, text="📊 GET 命令生成与解析")
  3516. # Command Generator block
  3517. frame_get_cmd = ttk.LabelFrame(tab_get, text="1. GET_ALL 查询命令生成", padding=8)
  3518. frame_get_cmd.pack(fill="x", pady=4)
  3519. get_cmd_bar = ttk.Frame(frame_get_cmd)
  3520. get_cmd_bar.pack(fill="x")
  3521. ttk.Label(get_cmd_bar, text="标准 GET_ALL 请求报文 (HEX):", font=("", 10, "bold")).pack(side="left", padx=4)
  3522. lbl_get_hex = ttk.Label(get_cmd_bar, text="A5 5A 02 00 6D 7B", font=("Consolas", 11, "bold"), foreground="#0066CC")
  3523. lbl_get_hex.pack(side="left", padx=8)
  3524. lbl_get_desc = ttk.Label(frame_get_cmd, text="解析: 同步头=A5 5A | 帧类型=0x02 (GET_ALL) | 载荷长度=0x00 | CRC16=0x6D 0x7B (低字节在先) | 语义: 请求单板返回实时占空比、BMC 24 通道与 CT7428 27 通道温度", foreground="#555555")
  3525. lbl_get_desc.pack(anchor="w", pady=2)
  3526. # Response Decoder block
  3527. frame_get_resp = ttk.LabelFrame(tab_get, text="2. GET 响应报文解析 (支持粘贴 GET_ACK、GET_DATA 或连续流)", padding=8)
  3528. frame_get_resp.pack(fill="both", expand=True, pady=6)
  3529. ttk.Label(frame_get_resp, text="粘贴单板返回的 HEX 响应:").pack(anchor="w")
  3530. text_get_resp_in = tk.Text(frame_get_resp, height=3, wrap="char", font=("Consolas", 9))
  3531. text_get_resp_in.pack(fill="x", pady=4)
  3532. resp_btn_bar = ttk.Frame(frame_get_resp)
  3533. resp_btn_bar.pack(fill="x", pady=2)
  3534. text_get_resp_out = tk.Text(frame_get_resp, height=15, wrap="word", font=("Consolas", 9))
  3535. text_get_resp_out.pack(fill="both", expand=True, pady=4)
  3536. def do_parse_get_resp(raw_hex_str: str | None = None):
  3537. raw = (raw_hex_str if raw_hex_str is not None else text_get_resp_in.get("1.0", "end")).strip()
  3538. if not raw:
  3539. return
  3540. try:
  3541. data = parse_hex(raw)
  3542. parsed_list = model.parse(data)
  3543. text_get_resp_out.delete("1.0", "end")
  3544. for idx, item in enumerate(parsed_list):
  3545. kind = item.get("kind")
  3546. if kind == "ack":
  3547. text_get_resp_out.insert("end", f"=== [帧 {idx+1}] {item.get('type')} ===\n")
  3548. text_get_resp_out.insert("end", "单板已确认受理查询请求 (GET_ACK 0x82),随后将传输 GET_DATA 状态帧。\n\n")
  3549. elif kind == "status":
  3550. state = item.get("state", {})
  3551. text_get_resp_out.insert("end", f"=== [帧 {idx+1}] GET_DATA (0x42) 详细解码 ===\n")
  3552. # Show duties
  3553. groups = model.groups()
  3554. for grp, cnt, _ in groups:
  3555. duties = state.get(grp.lower(), [])
  3556. if cnt >= 8:
  3557. text_get_resp_out.insert("end", f"【{grp} 实际生效占空比 (共 {len(duties)} 路)】:\n")
  3558. line = ""
  3559. for i, val in enumerate(duties):
  3560. line += f" {grp}{i:02d}: {val:3d} %"
  3561. if (i + 1) % 6 == 0:
  3562. text_get_resp_out.insert("end", line + "\n")
  3563. line = ""
  3564. else:
  3565. line += " | "
  3566. if line:
  3567. text_get_resp_out.insert("end", line.rstrip(" | ") + "\n")
  3568. else:
  3569. ch_strs = [f"{model.output_label(grp, i)}: {v}%" for i, v in enumerate(duties)]
  3570. text_get_resp_out.insert("end", f"【{model.group_label(grp)} 实际生效占空比 ({len(duties)} 路)】: {' | '.join(ch_strs)}\n")
  3571. if model.motor:
  3572. lm = state.get("lower_limit_mask", 0)
  3573. um = state.get("upper_limit_mask", 0)
  3574. text_get_resp_out.insert("end", f"【限位状态】: 下限位掩码=0x{lm:04X} (二进制={lm:012b}), 上限位掩码=0x{um:04X} (二进制={um:012b})\n")
  3575. for ax in range(12):
  3576. l_act = "触发阻断" if (lm & (1 << ax)) else "正常"
  3577. u_act = "触发阻断" if (um & (1 << ax)) else "正常"
  3578. if (lm & (1 << ax)) or (um & (1 << ax)):
  3579. ax_lbl = MRDIMM_AXIS_NAMES[ax] if ax < len(MRDIMM_AXIS_NAMES) else f"Axis{ax}"
  3580. text_get_resp_out.insert("end", f" • {ax_lbl}: 下限位={l_act}, 上限位={u_act}\n")
  3581. if product in ("6400-v2", "mrdimm-chamber"):
  3582. hood_txt = "按下 (高电平=1)" if state.get("hood_switch") else "未按下/默认 (低电平=0)"
  3583. buz_txt = "开启 (1)" if state.get("buzzer") else "关闭 (0)"
  3584. text_get_resp_out.insert("end", f"【高温罩开关检测】: {hood_txt} | 【蜂鸣器状态】: {buz_txt}\n")
  3585. # Temperatures
  3586. bmc = state.get("bmc", {}).get("temperature_c", [])
  3587. ct = state.get("ct", {}).get("temperature_c", [])
  3588. bmc_valid_cnt = sum(1 for t in bmc if t is not None)
  3589. if bmc_valid_cnt == 0:
  3590. bmc_status_note = " (尚无有效采样;0xFF)"
  3591. else:
  3592. bmc_status_note = f" ({bmc_valid_cnt}/24 通道已就绪)"
  3593. text_get_resp_out.insert("end", f"\n【BMC 24 通道温度遥测】{bmc_status_note}:\n")
  3594. for i, t in enumerate(bmc):
  3595. t_str = f"{t:3d} °C" if t is not None else "--(无效/未采样)"
  3596. text_get_resp_out.insert("end", f" BMC{i:02d}: {t_str}" + ("\n" if (i + 1) % 6 == 0 else " | "))
  3597. text_get_resp_out.insert("end", "\n【CT7428 27 通道温度遥测】:\n")
  3598. for i, t in enumerate(ct):
  3599. t_str = f"{t:3d} °C" if t is not None else "--(无效/未采样)"
  3600. text_get_resp_out.insert("end", f" CT{i:02d}: {t_str}" + ("\n" if (i + 1) % 6 == 0 else " | "))
  3601. text_get_resp_out.insert("end", "\n【四腔映射温度汇总 (可配置映射)】:\n")
  3602. text_get_resp_out.insert(
  3603. "end",
  3604. " " + chamber_mapping.format_realtime_summary(state, ignore_zero_ct=ignore_zero_ct_var.get()) + "\n\n",
  3605. )
  3606. if raw_hex_str is None:
  3607. sample_rec = curve_store.record_state(state)
  3608. tt_evt = thermal_session.process_sample(
  3609. sample_rec, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get()
  3610. )
  3611. if thermal_session.active and tt_evt.get("fan_switched_now"):
  3612. send_thermal_test_set("风扇到达介入条件自动调速")
  3613. refresh_thermal_test_ui()
  3614. lbl_realtime_chambers.config(
  3615. text="【四腔实时温度 (可配置映射)】: "
  3616. + chamber_mapping.format_realtime_summary(state, ignore_zero_ct=ignore_zero_ct_var.get())
  3617. )
  3618. redraw_all_chamber_canvases()
  3619. else:
  3620. text_get_resp_out.insert("end", f"=== [帧 {idx+1}] {item} ===\n\n")
  3621. except Exception as exc:
  3622. text_get_resp_out.delete("1.0", "end")
  3623. text_get_resp_out.insert("1.0", f"解析失败: {exc}")
  3624. ttk.Button(resp_btn_bar, text="🔍 解析 GET 响应", command=lambda: do_parse_get_resp()).pack(side="left", padx=4)
  3625. # -----------------------------------------------------------------------
  3626. # TAB 4: 通用报文检查器 (Universal Frame Inspector)
  3627. # -----------------------------------------------------------------------
  3628. tab_inspect = ttk.Frame(notebook, padding=10)
  3629. notebook.add(tab_inspect, text="🔬 通用报文检查器 (Inspector)")
  3630. ttk.Label(tab_inspect, text="输入或粘贴任意 HEX 报文(支持空格、冒号分隔,不区分大小写):", font=("", 10, "bold")).pack(anchor="w")
  3631. text_insp_in = tk.Text(tab_inspect, height=4, wrap="char", font=("Consolas", 10))
  3632. text_insp_in.pack(fill="x", pady=4)
  3633. # Quick golden templates bar
  3634. quick_bar = ttk.LabelFrame(tab_inspect, text="快速载入标准 Golden 帧测试模板", padding=6)
  3635. quick_bar.pack(fill="x", pady=4)
  3636. def load_template(hex_str: str):
  3637. text_insp_in.delete("1.0", "end")
  3638. text_insp_in.insert("1.0", hex_str)
  3639. do_inspect()
  3640. ttk.Button(quick_bar, text="GET_ALL 请求", command=lambda: load_template("A5 5A 02 00 6D 7B")).pack(side="left", padx=3)
  3641. ttk.Button(quick_bar, text="SET_ACK 应答", command=lambda: load_template("A5 5A 81 00 A6 35")).pack(side="left", padx=3)
  3642. ttk.Button(quick_bar, text="GET_ACK 应答", command=lambda: load_template("A5 5A 82 00 F5 60")).pack(side="left", padx=3)
  3643. ttk.Button(quick_bar, text="心跳请求(Ping)", command=lambda: load_template("A5 5A 03 00 5C 48")).pack(side="left", padx=3)
  3644. ttk.Button(quick_bar, text="心跳应答(Pong)", command=lambda: load_template("A5 5A 83 00 C4 53")).pack(side="left", padx=3)
  3645. ttk.Button(quick_bar, text="NACK 队列满", command=lambda: load_template("A5 5A C0 02 01 04 B1 2A")).pack(side="left", padx=3)
  3646. if model.motor:
  3647. ttk.Button(quick_bar, text="MOTOR_DONE(上限位4387步)", command=lambda: load_template("A5 5A 50 04 04 02 23 11 B6 02")).pack(side="left", padx=3)
  3648. ttk.Button(quick_bar, text="MOTOR_DONE(双限位0步)", command=lambda: load_template("A5 5A 50 04 04 03 00 00 23 64")).pack(side="left", padx=3)
  3649. else:
  3650. ttk.Button(quick_bar, text="6400 安全 SET 帧", command=lambda: load_template(frame_hex(model.set_all([default for _, count, default in model.groups() for _ in range(count)])))).pack(side="left", padx=3)
  3651. # Inspector output
  3652. insp_out_frame = ttk.LabelFrame(tab_inspect, text="报文逐字节解析与语义拆解", padding=8)
  3653. insp_out_frame.pack(fill="both", expand=True, pady=4)
  3654. text_insp_out = tk.Text(insp_out_frame, wrap="word", font=("Consolas", 10))
  3655. text_insp_out.pack(fill="both", expand=True)
  3656. def do_inspect():
  3657. raw_text = text_insp_in.get("1.0", "end").strip()
  3658. if not raw_text:
  3659. return
  3660. try:
  3661. raw_bytes = parse_hex(raw_text)
  3662. exp = model.explain(raw_bytes)
  3663. text_insp_out.delete("1.0", "end")
  3664. text_insp_out.insert("end", f"【原始 HEX】: {exp['hex']}\n")
  3665. text_insp_out.insert("end", f"【帧类型】: {exp['type']}\n")
  3666. text_insp_out.insert("end", f"【载荷长度】: {exp['length']}\n")
  3667. text_insp_out.insert("end", f"【CRC-16 校验码】: {exp['crc_hex']} -> {exp['crc_status']}\n")
  3668. text_insp_out.insert("end", f"【业务含义总结】: {exp['summary']}\n")
  3669. text_insp_out.insert("end", "-" * 70 + "\n")
  3670. text_insp_out.insert("end", "【字段详细拆解】:\n")
  3671. for f in exp.get("fields", []):
  3672. text_insp_out.insert("end", f" • {f}\n")
  3673. except Exception as exc:
  3674. text_insp_out.delete("1.0", "end")
  3675. text_insp_out.insert("1.0", f"报文解析异常: {exc}")
  3676. ttk.Button(tab_inspect, text="🚀 立即解码报文", command=do_inspect).pack(pady=4)
  3677. # -----------------------------------------------------------------------
  3678. # TAB 5: 构建与工程信息 (Build & Info)
  3679. # -----------------------------------------------------------------------
  3680. tab_info = ttk.Frame(notebook, padding=10)
  3681. notebook.add(tab_info, text="ℹ️ 构建与协议信息")
  3682. text_info = tk.Text(tab_info, height=18, font=("Consolas", 10))
  3683. text_info.pack(fill="both", expand=True)
  3684. info_dict = {
  3685. "product": product,
  3686. "board": model.board,
  3687. "device": "EF2L45BG256B",
  3688. "clock_hz": 25000000,
  3689. "release_version": model.release_version,
  3690. "firmware_host_baud": model.host_baud,
  3691. "selectable_host_baud": list(HOST_BAUDRATES),
  3692. "bmc_baud": 115200,
  3693. "auto_output": "0x51 自发信标" if model.motor else ("每秒 0x42 状态 + 0x52 芯片诊断" if product == "6400-v2" else "0x42 自动状态遥测,GET_ACK 后的数据才完成查询"),
  3694. "motor_usage": "每轴 1 个未完成动作;不同轴可并行;同轴等待 DONE 或先 STOP_CLEAR,发送后动作回 NOTHING" if model.motor else "无电机",
  3695. "wire_format": "8N1",
  3696. "wire_framing": "A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L:u8 | CRC_H:u8",
  3697. "crc_algorithm": "CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, refin/refout false, xorout 0x0000, LSB first)",
  3698. "watchdog_timeout_sec": 30,
  3699. "temperature_representation": "单字节 uint8 摄氏度 (00..FE = 0..254 °C, FF = 无效)",
  3700. "contract_sha256": model.contract.get("contract_sha256"),
  3701. "metadata": model.metadata,
  3702. }
  3703. text_info.insert("1.0", json.dumps(info_dict, ensure_ascii=False, indent=2))
  3704. # -----------------------------------------------------------------------
  3705. # Serial Port Handler & Background Thread
  3706. # -----------------------------------------------------------------------
  3707. def serial_read_loop(my_epoch: int):
  3708. nonlocal serial_port_obj
  3709. receiver.clear()
  3710. while True:
  3711. if my_epoch != connection_epoch:
  3712. break
  3713. with serial_lock:
  3714. sp = serial_port_obj
  3715. if sp is None or not sp.is_open:
  3716. break
  3717. try:
  3718. waiting = sp.in_waiting
  3719. if waiting > 0:
  3720. chunk = sp.read(waiting)
  3721. if chunk:
  3722. events = receiver.feed_bytes(chunk)
  3723. for evt_type, data in events:
  3724. if evt_type == "RX_RAW":
  3725. root.after(0, append_log, "RX_RAW", data.hex(" ").upper(), f"底层串口读取 {len(data)} 字节")
  3726. elif evt_type == "DISCARDED_NOISE":
  3727. try:
  3728. text = data.decode("ascii", errors="replace").strip()
  3729. # If printable ASCII text, display as BMC diagnostic log
  3730. if text and any(c.isalnum() for c in text):
  3731. root.after(0, append_log, "BOARD_DIAG", text, "板端自动调试文本/回显")
  3732. else:
  3733. root.after(0, append_log, "NOISE", data.hex(" ").upper(), f"过滤无效字节 ({len(data)} 字节)")
  3734. except Exception:
  3735. root.after(0, append_log, "NOISE", data.hex(" ").upper(), f"过滤无效字节 ({len(data)} 字节)")
  3736. elif evt_type == "FRAME_REJECTED":
  3737. rej_data = data["data"].hex(" ").upper() if isinstance(data, dict) and "data" in data else ""
  3738. rej_reason = data["reason"] if isinstance(data, dict) and "reason" in data else str(data)
  3739. root.after(0, append_log, "RX_ERR", rej_data, f"报文拒绝: {rej_reason}")
  3740. root.after(0, lbl_realtime_stat.config, {"text": f"报文拒绝: {rej_reason}"})
  3741. elif evt_type == "FRAME_VALID":
  3742. frame_bytes = data["frame_bytes"]
  3743. ftype = data["frame_type"]
  3744. payload = data["payload"]
  3745. exp = model.explain(frame_bytes)
  3746. tx_res = tracker.on_valid_frame(ftype, payload)
  3747. rx_tag = "RX_AUTO" if tx_res["status_code"] in ("UNSOLICITED_DATA", "BEACON", "DIAGNOSTIC") else "RX"
  3748. root.after(0, append_log, rx_tag, frame_hex(frame_bytes), tx_res.get("msg") or exp.get("type", ftype.name))
  3749. if tx_res.get("msg"):
  3750. root.after(0, lbl_realtime_stat.config, {"text": tx_res["msg"]})
  3751. if ftype == FrameType.GET_DATA:
  3752. root.after(0, update_realtime_status, frame_bytes, tx_res.get("is_match", False))
  3753. elif ftype == FrameType.DIAGNOSTIC:
  3754. root.after(0, lbl_realtime_diag.config, {"text": exp["summary"]})
  3755. dispatch_next_request()
  3756. else:
  3757. # Check inter-byte timeout for stalled partial frames
  3758. timeout_evts = receiver.check_timeout()
  3759. for evt_type, data in timeout_evts:
  3760. if evt_type == "FRAME_REJECTED":
  3761. rej_data = data["data"].hex(" ").upper() if isinstance(data, dict) and "data" in data else ""
  3762. rej_reason = data["reason"] if isinstance(data, dict) and "reason" in data else str(data)
  3763. root.after(0, append_log, "RX_ERR", rej_data, f"超时重置: {rej_reason}")
  3764. elif evt_type == "FRAME_VALID":
  3765. frame_bytes = data["frame_bytes"]
  3766. ftype = data["frame_type"]
  3767. payload = data["payload"]
  3768. exp = model.explain(frame_bytes)
  3769. tx_res = tracker.on_valid_frame(ftype, payload)
  3770. rx_tag = "RX_AUTO" if tx_res["status_code"] in ("UNSOLICITED_DATA", "BEACON", "DIAGNOSTIC") else "RX"
  3771. root.after(0, append_log, rx_tag, frame_hex(frame_bytes), tx_res.get("msg") or exp.get("type", ftype.name))
  3772. if tx_res.get("msg"):
  3773. root.after(0, lbl_realtime_stat.config, {"text": tx_res["msg"]})
  3774. if ftype == FrameType.GET_DATA:
  3775. root.after(0, update_realtime_status, frame_bytes, tx_res.get("is_match", False))
  3776. elif ftype == FrameType.DIAGNOSTIC:
  3777. root.after(0, lbl_realtime_diag.config, {"text": exp["summary"]})
  3778. dispatch_next_request()
  3779. time.sleep(0.02)
  3780. except Exception as exc:
  3781. root.after(0, append_log, "ERR", "", f"串口读取异常: {exc}")
  3782. break
  3783. def update_realtime_status(frame_data: bytes, matched_query: bool = False):
  3784. try:
  3785. parsed = model.parse(frame_data)
  3786. for item in parsed:
  3787. if item.get("kind") == "status":
  3788. st = item["state"]
  3789. bmc_valid = sum(1 for t in st.get("bmc", {}).get("temperature_c", []) if t is not None)
  3790. ct_valid = sum(1 for t in st.get("ct", {}).get("temperature_c", []) if t is not None)
  3791. bmc_note = "无有效采样" if bmc_valid == 0 else f"{bmc_valid}/24 通道就绪"
  3792. origin = "查询应答" if matched_query else "自动遥测(未关联查询)"
  3793. summary = f"{origin} | BMC: {bmc_note} | CT7428 有效: {ct_valid}/27 通道"
  3794. if product in ("6400-v2", "mrdimm-chamber"):
  3795. hood_s = "按下(1)" if st.get("hood_switch") else "未按(0)"
  3796. buz_s = "开(1)" if st.get("buzzer") else "关(0)"
  3797. summary += f" | 高温罩开关={hood_s} | 蜂鸣器={buz_s}"
  3798. if model.motor:
  3799. lm = st.get("lower_limit_mask", 0)
  3800. um = st.get("upper_limit_mask", 0)
  3801. summary += f" | 下限位=0x{lm:03X} | 上限位=0x{um:03X}"
  3802. fan_d = st.get("fan", [])
  3803. ptc_d = st.get("ptc", [])
  3804. lbl_realtime_ptc.config(text=f"【FAN 4路占空比】: {fan_d} | 【PTC 4路占空比】: {ptc_d}")
  3805. else:
  3806. ptc_d = st.get("ptc", [])
  3807. if ptc_d:
  3808. lines = []
  3809. for c in range(0, len(ptc_d), 8):
  3810. chunk = ptc_d[c : c + 8]
  3811. lines.append(" | ".join(f"PTC{c+j:02d}:{v:3d}%" for j, v in enumerate(chunk)))
  3812. front_d = st.get("front", [])
  3813. rear_d = st.get("rear", [])
  3814. fan_lines = [f"{model.output_label(group, index)}: {value}%"
  3815. for group, duties in (("Front", front_d), ("Rear", rear_d))
  3816. for index, value in enumerate(duties)]
  3817. ssr_lines = [f"{model.output_label('SSR', index)}: {value}%"
  3818. for index, value in enumerate(st.get("ssr", []))]
  3819. ssr_text = "\n【加热布 SSR(20 Hz,50 ms 周期)】:\n " + " | ".join(ssr_lines) if ssr_lines else ""
  3820. lbl_realtime_ptc.config(text=f"【PTC 生效占空比 (共{len(ptc_d)}路)】:\n " + "\n ".join(lines) + "\n【风扇占空比】:\n " + "\n ".join(" | ".join(fan_lines[n:n+2]) for n in range(0, len(fan_lines), 2)) + ssr_text)
  3821. lbl_realtime_stat.config(text=summary)
  3822. sample_rec = curve_store.record_state(st)
  3823. tt_evt = thermal_session.process_sample(
  3824. sample_rec, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get()
  3825. )
  3826. if thermal_session.active and tt_evt.get("fan_switched_now"):
  3827. send_thermal_test_set("风扇到达介入条件自动调速")
  3828. refresh_thermal_test_ui()
  3829. lbl_realtime_chambers.config(
  3830. text="【四腔实时温度 (可配置映射)】: "
  3831. + chamber_mapping.format_realtime_summary(st, ignore_zero_ct=ignore_zero_ct_var.get())
  3832. )
  3833. redraw_all_chamber_canvases()
  3834. # Also update TAB 3 output
  3835. do_parse_get_resp(frame_hex(frame_data))
  3836. except Exception:
  3837. pass
  3838. def poll_loop(my_epoch: int, my_gen: int):
  3839. while not poll_stop_event.is_set():
  3840. if my_epoch != connection_epoch or my_gen != poll_generation:
  3841. break
  3842. with serial_lock:
  3843. sp = serial_port_obj
  3844. if sp and sp.is_open:
  3845. get_frame = model.get_all()
  3846. request_queue.put(("GET", get_frame, "自动轮询 GET_ALL (维持看门狗)"))
  3847. dispatch_next_request()
  3848. poll_stop_event.wait(timeout=1.0)
  3849. def toggle_connect():
  3850. nonlocal serial_port_obj, poll_active, connection_epoch, poll_generation
  3851. if not HAVE_SERIAL:
  3852. messagebox.showerror("缺少库", "未检测到 pyserial 库,无法进行串口通信。\n可在命令行运行: pip install pyserial")
  3853. return
  3854. with serial_lock:
  3855. if serial_port_obj and serial_port_obj.is_open:
  3856. connection_epoch += 1
  3857. poll_generation += 1
  3858. poll_stop_event.set()
  3859. poll_var.set(False)
  3860. while not request_queue.empty():
  3861. try:
  3862. request_queue.get_nowait()
  3863. except queue.Empty:
  3864. break
  3865. try:
  3866. serial_port_obj.close()
  3867. except Exception:
  3868. pass
  3869. serial_port_obj = None
  3870. tracker.on_port_closed()
  3871. btn_connect.config(text="打开串口")
  3872. lbl_conn_status.config(text="已断开", foreground="gray")
  3873. btn_send_get.config(state="disabled")
  3874. btn_send_set.config(state="disabled")
  3875. btn_heartbeat.config(state="disabled")
  3876. chk_poll.config(state="disabled")
  3877. return
  3878. port = port_combo.get().strip()
  3879. if not port:
  3880. messagebox.showwarning("提示", "请先选择有效的 COM 端口")
  3881. return
  3882. baud = int(baud_combo.get().strip())
  3883. try:
  3884. connection_epoch += 1
  3885. sp = serial.Serial(port, baudrate=baud, timeout=0.1)
  3886. with serial_lock:
  3887. serial_port_obj = sp
  3888. tracker.on_port_opened(port, baud)
  3889. btn_connect.config(text="关闭串口")
  3890. lbl_conn_status.config(text=f"已连接 {port} @ {baud}", foreground="green")
  3891. btn_send_get.config(state="normal")
  3892. btn_send_set.config(state="normal")
  3893. btn_heartbeat.config(state="normal")
  3894. chk_poll.config(state="normal")
  3895. # Start reading thread with this epoch
  3896. threading.Thread(target=serial_read_loop, args=(connection_epoch,), daemon=True).start()
  3897. except PermissionError as exc:
  3898. messagebox.showerror(
  3899. "端口占用",
  3900. f"无法打开串口 {port} (拒绝访问 / Access Denied)!\n\n"
  3901. f"根因诊断:该端口当前已被其他程序独占占用(如灵光串口调试助手 SerialDebug.exe 或另一个上位机进程)。\n\n"
  3902. f"解决办法:请先在任务管理器或相关软件中关闭占用 {port} 的程序,然后再点击打开串口。"
  3903. )
  3904. except Exception as exc:
  3905. err_str = str(exc)
  3906. if "Access is denied" in err_str or "PermissionError" in err_str:
  3907. msg = (
  3908. f"无法打开串口 {port} (拒绝访问)!\n\n"
  3909. f"检测到该端口正被另一个进程独占占用。请关闭占用该串口的工具后重试。"
  3910. )
  3911. else:
  3912. msg = f"无法打开串口 {port}:\n{exc}"
  3913. messagebox.showerror("连接失败", msg)
  3914. def send_get_clicked():
  3915. with serial_lock:
  3916. sp = serial_port_obj
  3917. if not sp or not sp.is_open:
  3918. messagebox.showwarning("提示", "串口未连接")
  3919. return
  3920. get_frame = model.get_all()
  3921. request_queue.put(("GET", get_frame, "GET_ALL 查询 (等待应答)"))
  3922. dispatch_next_request()
  3923. def send_set_clicked():
  3924. with serial_lock:
  3925. sp = serial_port_obj
  3926. if not sp or not sp.is_open:
  3927. messagebox.showwarning("提示", "串口未连接")
  3928. return
  3929. try:
  3930. set_frame = do_generate_set()
  3931. request_queue.put(("SET", set_frame, "SET_ALL 配置下发 (等待确认)"))
  3932. dispatch_next_request()
  3933. except Exception as exc:
  3934. messagebox.showerror("发送失败", str(exc))
  3935. def send_heartbeat_clicked():
  3936. with serial_lock:
  3937. sp = serial_port_obj
  3938. if not sp or not sp.is_open:
  3939. messagebox.showwarning("提示", "串口未连接")
  3940. return
  3941. nonce = os.urandom(4)
  3942. hb_frame = model.heartbeat(nonce=nonce)
  3943. request_queue.put(("PING", hb_frame, f"HEARTBEAT 心跳测试 Ping (Nonce: 0x{nonce.hex().upper()})", nonce))
  3944. dispatch_next_request()
  3945. def on_poll_toggle():
  3946. nonlocal poll_generation
  3947. poll_generation += 1
  3948. is_active = poll_var.get()
  3949. if is_active:
  3950. poll_stop_event.clear()
  3951. threading.Thread(target=poll_loop, args=(connection_epoch, poll_generation), daemon=True).start()
  3952. else:
  3953. poll_stop_event.set()
  3954. btn_connect.config(command=toggle_connect)
  3955. btn_send_get.config(command=send_get_clicked)
  3956. btn_send_set.config(command=send_set_clicked)
  3957. btn_heartbeat.config(command=send_heartbeat_clicked)
  3958. chk_poll.config(command=on_poll_toggle)
  3959. # Initial generation
  3960. do_generate_set()
  3961. root.mainloop()
  3962. return 0
  3963. def main(product: str, argv: list[str] | None = None) -> int:
  3964. args = sys.argv if argv is None else argv
  3965. if "--self-test" in args:
  3966. report_path = None
  3967. if "--self-test-report" in args:
  3968. report_path = Path(args[args.index("--self-test-report") + 1])
  3969. report = {"schema": "prod2u-gui-self-test-v1", "product": product,
  3970. "status": "FAIL", "serial_opened": False,
  3971. "hardware_validation": "NOT_RUN", "visual_gui_validation": "NOT_RUN"}
  3972. try:
  3973. code = self_test(product)
  3974. model = Model(product)
  3975. report.update(status="PASS" if code == 0 else "FAIL",
  3976. release_version=model.release_version, host_baud=model.host_baud,
  3977. metadata=model.metadata)
  3978. return code
  3979. except Exception as exc:
  3980. report["error"] = str(exc)
  3981. return 1
  3982. finally:
  3983. if report_path is not None:
  3984. report_path.parent.mkdir(parents=True, exist_ok=True)
  3985. report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  3986. if "--plot-log" in args and "--plot-out" in args:
  3987. log_path = Path(args[args.index("--plot-log") + 1])
  3988. out_path = Path(args[args.index("--plot-out") + 1])
  3989. model = Model(product)
  3990. cfg = ChamberMappingConfig.default(product)
  3991. if "--chamber-map" in args:
  3992. cfg = ChamberMappingConfig.load(Path(args[args.index("--chamber-map") + 1]), product=product)
  3993. store = TemperatureCurveStore()
  3994. count = store.load_from_log_file(log_path, model)
  3995. out_path.parent.mkdir(parents=True, exist_ok=True)
  3996. suffix = out_path.suffix.lower()
  3997. if suffix == ".svg":
  3998. out_path.write_text(render_chamber_curves_svg(store, cfg, product=product, board=model.board), encoding="utf-8")
  3999. elif suffix == ".csv":
  4000. out_path.write_text(export_chamber_curves_csv(store, cfg), encoding="utf-8")
  4001. else:
  4002. out_path.write_bytes(render_chamber_curves_png(store, cfg, product=product, board=model.board))
  4003. print(f"OK: imported {count} samples from {log_path} -> {out_path}")
  4004. return 0
  4005. return run_gui(product)
  4006. if __name__ == "__main__":
  4007. prod = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] in ("6400-front-rear", "mrdimm-chamber", "6400-v2") else "6400-front-rear"
  4008. sys.exit(main(prod))