prod2u_gui.py 214 KB

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