From: kyz Date: Sun, 1 Nov 2026 13:50:58 +0000 (+0800) Subject: add iap, add date info X-Git-Url: http://kyz.pub/gitweb/?a=commitdiff_plain;h=7a79c791be3944a087e8fe65f52bf5e3edfc54f0;p=yn%2Fdispboard-tools.git add iap, add date info --- diff --git a/app.py b/app.py index 44f7b12..fc326bb 100644 --- a/app.py +++ b/app.py @@ -48,6 +48,7 @@ class SlaveRequestHandler(RequestHandler): '/api/register': lambda: self._handle_get_register(params), '/api/status': self._handle_get_status, '/api/token': self._handle_get_token_status, + '/api/iap': self._handle_get_iap_status, '/api/log': self._handle_get_log, '/api/coils': self._handle_get_coils, } @@ -212,6 +213,13 @@ class SlaveRequestHandler(RequestHandler): else: self._send_error('当前未持有令牌或正在发送中', 400) + def _handle_get_iap_status(self): + """获取 IAP 升级状态.""" + slave = get_slave() + with _lock: + status = slave.get_iap_status() + self._send_json(status) + def _handle_slave_start(self): slave = get_slave() if not slave.running: diff --git a/diag_canat.py b/diag_canat.py index e0fcbcd..3f093bc 100644 --- a/diag_canat.py +++ b/diag_canat.py @@ -1,347 +1,347 @@ -""" -CANalyst-II (ControlCAN.dll) 连接诊断脚本. - -用法: python diag_canat.py -逐项打印: DLL 加载 / 打开设备 / 读板信息 / 复位 / 初始化 / 启动 的返回值, -并用多种 DevType 与 DevIndex 组合尝试, 以便定位 VCI_InitCAN 返回 0 的原因. -""" -import ctypes -import os -import sys -import time -from ctypes import byref - - -class VCIInITConfig(ctypes.Structure): - _fields_ = [ - ("AccCode", ctypes.c_uint), - ("AccMask", ctypes.c_uint), - ("Reserved", ctypes.c_uint), - ("Filter", ctypes.c_ubyte), - ("Timing0", ctypes.c_ubyte), - ("Timing1", ctypes.c_ubyte), - ("Mode", ctypes.c_ubyte), - ] - - -class VCIBoardInfo(ctypes.Structure): - _fields_ = [ - ("hw_Version", ctypes.c_ushort), - ("fw_Version", ctypes.c_ushort), - ("dr_Version", ctypes.c_ushort), - ("in_Version", ctypes.c_ushort), - ("irq_Num", ctypes.c_ushort), - ("can_Num", ctypes.c_ubyte), - ("str_Serial_Num", ctypes.c_char * 20), - ("str_hw_Type", ctypes.c_char * 40), - ("Reserved", ctypes.c_ushort * 4), - ] - - -def load_dll(): - root = os.path.dirname(os.path.abspath(__file__)) - path = os.path.join(root, "ControlCAN.dll") - if not os.path.isfile(path): - print(f"[FAIL] 未找到 {path}") - sys.exit(1) - os.add_dll_directory(root) - dll = ctypes.CDLL(path) - dll.VCI_OpenDevice.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_uint] - dll.VCI_OpenDevice.restype = ctypes.c_int - dll.VCI_CloseDevice.argtypes = [ctypes.c_uint, ctypes.c_uint] - dll.VCI_CloseDevice.restype = ctypes.c_int - dll.VCI_ReadBoardInfo.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(VCIBoardInfo)] - dll.VCI_ReadBoardInfo.restype = ctypes.c_int - dll.VCI_ResetCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort] - dll.VCI_ResetCAN.restype = ctypes.c_int - dll.VCI_InitCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, ctypes.POINTER(VCIInITConfig)] - dll.VCI_InitCAN.restype = ctypes.c_int - dll.VCI_StartCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort] - dll.VCI_StartCAN.restype = ctypes.c_int - dll.VCI_ClearBuffer.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort] - dll.VCI_ClearBuffer.restype = ctypes.c_int - dll.VCI_SetReference.argtypes = [ - ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, ctypes.c_uint, ctypes.c_void_p, - ] - dll.VCI_SetReference.restype = ctypes.c_int - - dll.VCI_Receive.argtypes = [ - ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, - ctypes.POINTER(VCICanObj), ctypes.c_uint, ctypes.c_int, - ] - dll.VCI_Receive.restype = ctypes.c_uint - return dll - - -class VCICanObj(ctypes.Structure): - _fields_ = [ - ("ID", ctypes.c_uint), - ("TimeStamp", ctypes.c_uint), - ("TimeFlag", ctypes.c_ubyte), - ("SendType", ctypes.c_ubyte), - ("RemoteFlag", ctypes.c_ubyte), - ("ExternFlag", ctypes.c_ubyte), - ("DataLen", ctypes.c_ubyte), - ("Data", ctypes.c_ubyte * 8), - ("Reserved", ctypes.c_ubyte * 3), - ] - - -def _rx_listen(dll, dt, di, ch, clk): - """打开并初始化指定通道, 侦听 12 秒, 返回收到的报文列表.""" - got = [] - try: - dll.VCI_CloseDevice(dt, di) - except Exception: - pass - if dll.VCI_OpenDevice(dt, di, 0) == 0: - return None - dll.VCI_SetReference(dt, di, ch, 1, byref(ctypes.c_uint(clk))) - dll.VCI_ResetCAN(dt, di, ch) - cfg = VCIInITConfig() - cfg.AccCode = 0 - cfg.AccMask = 0xFFFFFFFF - cfg.Reserved = 0 - cfg.Filter = 0 - cfg.Timing0 = 0x01 # DevType=4 成功组合 - cfg.Timing1 = 0x14 - cfg.Mode = 0 - ri = dll.VCI_InitCAN(dt, di, ch, byref(cfg)) - if ri <= 0: - dll.VCI_CloseDevice(dt, di) - return None - dll.VCI_ClearBuffer(dt, di, ch) - st = dll.VCI_StartCAN(dt, di, ch) - print(f" 通道{ch}: clk={clk} InitCAN={ri} StartCAN={st} 侦听中(12s)...") - buf = (VCICanObj * 32)() - deadline = time.time() + 12 - while time.time() < deadline: - n = dll.VCI_Receive(dt, di, ch, buf, 32, 300) - for i in range(n): - obj = buf[i] - data = bytes(obj.Data[:obj.DataLen]) - got.append((obj.ID, obj.ExternFlag, data)) - print(f" -> 收到 ID=0x{obj.ID:03X} {'X' if obj.ExternFlag else 'S'} " - f"LEN={len(data)} {' '.join('%02X' % b for b in data)}") - if n: - got.clear() # 只要收到一条即视为命中, 清掉以便按通道判定 - dll.VCI_CloseDevice(dt, di) - return got - - -def _rx_listen_timing(dll, dt, di, ch, clk, t0, t1, dur=8.0): - """以指定 主时钟(timing) 配置监听某通道, 监听 dur 秒, 返回是否收到帧. - - VCI_InitCAN 成功并不代表波特率匹配! 所以这里会一直监听, 只要收到 - 任何原始帧即认为该 (通道×主时钟×时序) 组合命中. - """ - try: - dll.VCI_CloseDevice(dt, di) - except Exception: - pass - if dll.VCI_OpenDevice(dt, di, 0) == 0: - return False - # 按需设置主时钟(2E-U 等需要; 普通 USBCAN2 会忽略) - try: - dll.VCI_SetReference(dt, di, ch, 1, byref(ctypes.c_uint(clk))) - except Exception: - pass - dll.VCI_ResetCAN(dt, di, ch) - cfg = VCIInITConfig() - cfg.AccCode = 0 - cfg.AccMask = 0xFFFFFFFF - cfg.Reserved = 0 - cfg.Filter = 0 - cfg.Timing0 = t0 - cfg.Timing1 = t1 - cfg.Mode = 0 - ri = dll.VCI_InitCAN(dt, di, ch, byref(cfg)) - if ri <= 0: - dll.VCI_CloseDevice(dt, di) - return False - dll.VCI_ClearBuffer(dt, di, ch) - st = dll.VCI_StartCAN(dt, di, ch) - buf = (VCICanObj * 32)() - deadline = time.time() + dur - got = False - while time.time() < deadline: - n = dll.VCI_Receive(dt, di, ch, buf, 32, 300) - for i in range(n): - obj = buf[i] - data = bytes(obj.Data[:obj.DataLen]) - got = True - print(f" ✓ [{dt}|{di}|{ch}] clk={clk} T0=0x{t0:02X} T1=0x{t1:02X} " - f"InitCAN={ri} StartCAN={st} -> 收到 ID=0x{obj.ID:03X} " - f"{' '.join('%02X' % b for b in data)}") - dll.VCI_CloseDevice(dt, di) - return got - - -def _real_rx_test(dll): - """枚举所有 (DevType × 通道 × 主时钟 × 时序) 组合去真听. - - 因为外部设备每约几秒发一个测试包, 只有波特率真正匹配的通道才能收到. - 据此锁定 can_layer.py 该用的 设备类型/通道/主时钟/时序. - """ - print("=" * 60) - print("[真实接收枚举测试]") - print("请确保外部设备每约几秒发一个测试包, 并已关闭 app.py.") - print("将枚举 DevType(4/21) × 通道(CAN0/CAN1) × 主时钟 × 1M时序...") - print("=" * 60) - - # 1Mbps 候选时序: - # 16MHz 主时钟 -> (0x00,0x14) = 1M (SJA1000 标准) - # 16MHz 主时钟 -> (0x01,0x14) = 1M(simple) 用户工具通用先例 - # 12MHz 主时钟 -> (0x00,0x1C) ~=1M - # 8MHz 主时钟 -> (0x00,0x03)*sample 不用 - timing_cand = { - 16000000: [(0x00, 0x14), (0x01, 0x14), (0x01, 0x1C)], - 12000000: [(0x00, 0x1C), (0x01, 0x1C)], - 8000000: [(0x00, 0x1C), (0x01, 0x1C)], - } - - devtypes = [4, 21] - hits = [] - for dt in devtypes: - for ch in (0, 1): - for clk, tlist in timing_cand.items(): - for (t0, t1) in tlist: - print(f"[T] DevType={dt} 通道{ch} clk={clk} T0=0x{t0:02X} T1=0x{t1:02X} ...") - if _rx_listen_timing(dll, dt, try_di_global, ch, clk, t0, t1, 8.0): - hits.append((dt, ch, clk, t0, t1)) - if hits: - print("\n" + "=" * 60) - print("[命中] 以下组合可以真正收到外部设备的报文:") - for h in hits: - print(f" DevType={h[0]} 通道={h[1]} 主时钟={h[2]} T0=0x{h[3]:02X} T1=0x{h[4]:02X}") - print("=" * 60) - else: - print("\n[结果] 所有组合均未收到任何报文. 可能: 设备未连 CAN 总线/HI端,") - print(" 或外部设备不在网络上, 或接线/终端电阻问题.") - print("=" * 60) - - -try_di_global = 0 - - -def main(): - print("=" * 60) - print("CANalyst-II 连接诊断") - print("=" * 60) - dll = load_dll() - print("[OK] ControlCAN.dll 加载成功") - - # 创建芯都设备类型: USBCAN_2E_U=21, USBCAN2=4, USBCAN1=3, USBCAN_E_U=20 - devtypes = [21, 4, 3, 20] - print(f"[INFO] Python {'64位' if sys.maxsize > 2**32 else '32位'}") - - found = False - for dt in devtypes: - for di in range(2): # DevIndex 0..1 - try: - dll.VCI_CloseDevice(dt, di) - except Exception: - pass - o = dll.VCI_OpenDevice(dt, di, 0) - if o == 0: - continue - board = VCIBoardInfo() - rb = dll.VCI_ReadBoardInfo(dt, di, byref(board)) - hw = board.str_hw_Type.decode("utf-8", "ignore").strip("\x00") - sn = board.str_Serial_Num.decode("utf-8", "ignore").strip("\x00") - print(f"\n[OK] 设备可打开: DevType={dt}, DevIndex={di}, " - f"OpenDevice={o}, ReadBoardInfo={rb}") - print(f" 硬件类型: {hw or '(空)'}") - print(f" 序列号 : {sn or '(空)'}") - print(f" CAN通道数: {board.can_Num}") - found = True - try_dt, try_di = dt, di - try: - dll.VCI_CloseDevice(dt, di) - except Exception: - pass - # 只测试找到的第一个设备, 避免重复 - break - if found: - break - - if not found: - print("[FAIL] 所有 DevType/DevIndex 组合都无法打开设备.") - print(" 请确认: 设备已插入、驱动已安装、未被其他程序占用。") - return - - # 对找到的设备, 重点测试 VCI_SetReference + VCI_InitCAN 的 2E-U 标准流程 - print(f"\n[INFO] VCIInITConfig 结构体大小 = {ctypes.sizeof(VCIInITConfig)} 字节 (期望 16)") - - # 先按住找到的 DevType 测试 SetReference 前置流程 - print("\n--- 测试: OpenDevice -> SetReference(时钟) -> ResetCAN -> InitCAN ---") - ch = 0 - found_ok = 0 - - # 主时钟频率候选 (2E-U 设备可能是 8MHz 或 16MHz) - clk_values = [12000000, 16000000, 8000000, 2000000] - # Timing 候选 - t0t1_list = [ - (0x01, 0x14), # 用户工具时序 - (0x00, 0x14), - (0x00, 0x1C), - (0x03, 0x1C), - ] - - for dt in [try_dt] + [d for d in (21, 4, 3, 20) if d != try_dt]: - for clk in clk_values: - for (t0, t1) in t0t1_list: - try: - dll.VCI_CloseDevice(dt, try_di) - except Exception: - pass - if dll.VCI_OpenDevice(dt, try_di, 0) == 0: - continue - # 2E-U 关键: 先 SetReference 设置主时钟 - ref_ret = dll.VCI_SetReference( - dt, try_di, ch, 1, byref(ctypes.c_uint(clk))) - dll.VCI_ResetCAN(dt, try_di, ch) - - cfg = VCIInITConfig() - cfg.AccCode = 0 - cfg.AccMask = 0xFFFFFFFF - cfg.Reserved = 0 - cfg.Filter = 0 - cfg.Timing0 = t0 - cfg.Timing1 = t1 - cfg.Mode = 0 - ri = dll.VCI_InitCAN(dt, try_di, ch, byref(cfg)) - if ri > 0: - found_ok += 1 - cb = dll.VCI_ClearBuffer(dt, try_di, ch) - st = dll.VCI_StartCAN(dt, try_di, ch) - print(f"\n[OK] DevType={dt} 时钟={clk} T0=0x{t0:02X} T1=0x{t1:02X} " - f"-> SetRef={ref_ret} InitCAN={ri} (成功) " - f"ClearBuf={cb} StartCAN={st}") - dll.VCI_CloseDevice(dt, try_di) - break # 每组成功即停 - # 无成功则静默, 少量打印 - dll.VCI_CloseDevice(dt, try_di) - if found_ok: - break - if found_ok: - break - - global try_di_global - try_di_global = try_di - - if found_ok: - print(f"\n[成功] 找到可用组合, 共 {found_ok} 次成功.\n") - _real_rx_test(dll) - else: - print("\n[失败] 所有 DevType/SetReference/Timing 组合均失败.") - print(" 提示: 需要核对 ControlCAN.h 中该设备的 RefType 具体含义,") - print(" 以及 USBCAN_E_U(20)/USBCAN_2E_U(21) 的正确用法.") - print(" 请查阅随附的《4.接口函数库(二次开发库)使用说明书.pdf》") - - print("\n" + "=" * 60) - print("诊断完成。") - - -if __name__ == "__main__": +""" +CANalyst-II (ControlCAN.dll) 连接诊断脚本. + +用法: python diag_canat.py +逐项打印: DLL 加载 / 打开设备 / 读板信息 / 复位 / 初始化 / 启动 的返回值, +并用多种 DevType 与 DevIndex 组合尝试, 以便定位 VCI_InitCAN 返回 0 的原因. +""" +import ctypes +import os +import sys +import time +from ctypes import byref + + +class VCIInITConfig(ctypes.Structure): + _fields_ = [ + ("AccCode", ctypes.c_uint), + ("AccMask", ctypes.c_uint), + ("Reserved", ctypes.c_uint), + ("Filter", ctypes.c_ubyte), + ("Timing0", ctypes.c_ubyte), + ("Timing1", ctypes.c_ubyte), + ("Mode", ctypes.c_ubyte), + ] + + +class VCIBoardInfo(ctypes.Structure): + _fields_ = [ + ("hw_Version", ctypes.c_ushort), + ("fw_Version", ctypes.c_ushort), + ("dr_Version", ctypes.c_ushort), + ("in_Version", ctypes.c_ushort), + ("irq_Num", ctypes.c_ushort), + ("can_Num", ctypes.c_ubyte), + ("str_Serial_Num", ctypes.c_char * 20), + ("str_hw_Type", ctypes.c_char * 40), + ("Reserved", ctypes.c_ushort * 4), + ] + + +def load_dll(): + root = os.path.dirname(os.path.abspath(__file__)) + path = os.path.join(root, "ControlCAN.dll") + if not os.path.isfile(path): + print(f"[FAIL] 未找到 {path}") + sys.exit(1) + os.add_dll_directory(root) + dll = ctypes.CDLL(path) + dll.VCI_OpenDevice.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_uint] + dll.VCI_OpenDevice.restype = ctypes.c_int + dll.VCI_CloseDevice.argtypes = [ctypes.c_uint, ctypes.c_uint] + dll.VCI_CloseDevice.restype = ctypes.c_int + dll.VCI_ReadBoardInfo.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(VCIBoardInfo)] + dll.VCI_ReadBoardInfo.restype = ctypes.c_int + dll.VCI_ResetCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort] + dll.VCI_ResetCAN.restype = ctypes.c_int + dll.VCI_InitCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, ctypes.POINTER(VCIInITConfig)] + dll.VCI_InitCAN.restype = ctypes.c_int + dll.VCI_StartCAN.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort] + dll.VCI_StartCAN.restype = ctypes.c_int + dll.VCI_ClearBuffer.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort] + dll.VCI_ClearBuffer.restype = ctypes.c_int + dll.VCI_SetReference.argtypes = [ + ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, ctypes.c_uint, ctypes.c_void_p, + ] + dll.VCI_SetReference.restype = ctypes.c_int + + dll.VCI_Receive.argtypes = [ + ctypes.c_uint, ctypes.c_uint, ctypes.c_ushort, + ctypes.POINTER(VCICanObj), ctypes.c_uint, ctypes.c_int, + ] + dll.VCI_Receive.restype = ctypes.c_uint + return dll + + +class VCICanObj(ctypes.Structure): + _fields_ = [ + ("ID", ctypes.c_uint), + ("TimeStamp", ctypes.c_uint), + ("TimeFlag", ctypes.c_ubyte), + ("SendType", ctypes.c_ubyte), + ("RemoteFlag", ctypes.c_ubyte), + ("ExternFlag", ctypes.c_ubyte), + ("DataLen", ctypes.c_ubyte), + ("Data", ctypes.c_ubyte * 8), + ("Reserved", ctypes.c_ubyte * 3), + ] + + +def _rx_listen(dll, dt, di, ch, clk): + """打开并初始化指定通道, 侦听 12 秒, 返回收到的报文列表.""" + got = [] + try: + dll.VCI_CloseDevice(dt, di) + except Exception: + pass + if dll.VCI_OpenDevice(dt, di, 0) == 0: + return None + dll.VCI_SetReference(dt, di, ch, 1, byref(ctypes.c_uint(clk))) + dll.VCI_ResetCAN(dt, di, ch) + cfg = VCIInITConfig() + cfg.AccCode = 0 + cfg.AccMask = 0xFFFFFFFF + cfg.Reserved = 0 + cfg.Filter = 0 + cfg.Timing0 = 0x01 # DevType=4 成功组合 + cfg.Timing1 = 0x14 + cfg.Mode = 0 + ri = dll.VCI_InitCAN(dt, di, ch, byref(cfg)) + if ri <= 0: + dll.VCI_CloseDevice(dt, di) + return None + dll.VCI_ClearBuffer(dt, di, ch) + st = dll.VCI_StartCAN(dt, di, ch) + print(f" 通道{ch}: clk={clk} InitCAN={ri} StartCAN={st} 侦听中(12s)...") + buf = (VCICanObj * 32)() + deadline = time.time() + 12 + while time.time() < deadline: + n = dll.VCI_Receive(dt, di, ch, buf, 32, 300) + for i in range(n): + obj = buf[i] + data = bytes(obj.Data[:obj.DataLen]) + got.append((obj.ID, obj.ExternFlag, data)) + print(f" -> 收到 ID=0x{obj.ID:03X} {'X' if obj.ExternFlag else 'S'} " + f"LEN={len(data)} {' '.join('%02X' % b for b in data)}") + if n: + got.clear() # 只要收到一条即视为命中, 清掉以便按通道判定 + dll.VCI_CloseDevice(dt, di) + return got + + +def _rx_listen_timing(dll, dt, di, ch, clk, t0, t1, dur=8.0): + """以指定 主时钟(timing) 配置监听某通道, 监听 dur 秒, 返回是否收到帧. + + VCI_InitCAN 成功并不代表波特率匹配! 所以这里会一直监听, 只要收到 + 任何原始帧即认为该 (通道×主时钟×时序) 组合命中. + """ + try: + dll.VCI_CloseDevice(dt, di) + except Exception: + pass + if dll.VCI_OpenDevice(dt, di, 0) == 0: + return False + # 按需设置主时钟(2E-U 等需要; 普通 USBCAN2 会忽略) + try: + dll.VCI_SetReference(dt, di, ch, 1, byref(ctypes.c_uint(clk))) + except Exception: + pass + dll.VCI_ResetCAN(dt, di, ch) + cfg = VCIInITConfig() + cfg.AccCode = 0 + cfg.AccMask = 0xFFFFFFFF + cfg.Reserved = 0 + cfg.Filter = 0 + cfg.Timing0 = t0 + cfg.Timing1 = t1 + cfg.Mode = 0 + ri = dll.VCI_InitCAN(dt, di, ch, byref(cfg)) + if ri <= 0: + dll.VCI_CloseDevice(dt, di) + return False + dll.VCI_ClearBuffer(dt, di, ch) + st = dll.VCI_StartCAN(dt, di, ch) + buf = (VCICanObj * 32)() + deadline = time.time() + dur + got = False + while time.time() < deadline: + n = dll.VCI_Receive(dt, di, ch, buf, 32, 300) + for i in range(n): + obj = buf[i] + data = bytes(obj.Data[:obj.DataLen]) + got = True + print(f" ✓ [{dt}|{di}|{ch}] clk={clk} T0=0x{t0:02X} T1=0x{t1:02X} " + f"InitCAN={ri} StartCAN={st} -> 收到 ID=0x{obj.ID:03X} " + f"{' '.join('%02X' % b for b in data)}") + dll.VCI_CloseDevice(dt, di) + return got + + +def _real_rx_test(dll): + """枚举所有 (DevType × 通道 × 主时钟 × 时序) 组合去真听. + + 因为外部设备每约几秒发一个测试包, 只有波特率真正匹配的通道才能收到. + 据此锁定 can_layer.py 该用的 设备类型/通道/主时钟/时序. + """ + print("=" * 60) + print("[真实接收枚举测试]") + print("请确保外部设备每约几秒发一个测试包, 并已关闭 app.py.") + print("将枚举 DevType(4/21) × 通道(CAN0/CAN1) × 主时钟 × 1M时序...") + print("=" * 60) + + # 1Mbps 候选时序: + # 16MHz 主时钟 -> (0x00,0x14) = 1M (SJA1000 标准) + # 16MHz 主时钟 -> (0x01,0x14) = 1M(simple) 用户工具通用先例 + # 12MHz 主时钟 -> (0x00,0x1C) ~=1M + # 8MHz 主时钟 -> (0x00,0x03)*sample 不用 + timing_cand = { + 16000000: [(0x00, 0x14), (0x01, 0x14), (0x01, 0x1C)], + 12000000: [(0x00, 0x1C), (0x01, 0x1C)], + 8000000: [(0x00, 0x1C), (0x01, 0x1C)], + } + + devtypes = [4, 21] + hits = [] + for dt in devtypes: + for ch in (0, 1): + for clk, tlist in timing_cand.items(): + for (t0, t1) in tlist: + print(f"[T] DevType={dt} 通道{ch} clk={clk} T0=0x{t0:02X} T1=0x{t1:02X} ...") + if _rx_listen_timing(dll, dt, try_di_global, ch, clk, t0, t1, 8.0): + hits.append((dt, ch, clk, t0, t1)) + if hits: + print("\n" + "=" * 60) + print("[命中] 以下组合可以真正收到外部设备的报文:") + for h in hits: + print(f" DevType={h[0]} 通道={h[1]} 主时钟={h[2]} T0=0x{h[3]:02X} T1=0x{h[4]:02X}") + print("=" * 60) + else: + print("\n[结果] 所有组合均未收到任何报文. 可能: 设备未连 CAN 总线/HI端,") + print(" 或外部设备不在网络上, 或接线/终端电阻问题.") + print("=" * 60) + + +try_di_global = 0 + + +def main(): + print("=" * 60) + print("CANalyst-II 连接诊断") + print("=" * 60) + dll = load_dll() + print("[OK] ControlCAN.dll 加载成功") + + # 创建芯都设备类型: USBCAN_2E_U=21, USBCAN2=4, USBCAN1=3, USBCAN_E_U=20 + devtypes = [21, 4, 3, 20] + print(f"[INFO] Python {'64位' if sys.maxsize > 2**32 else '32位'}") + + found = False + for dt in devtypes: + for di in range(2): # DevIndex 0..1 + try: + dll.VCI_CloseDevice(dt, di) + except Exception: + pass + o = dll.VCI_OpenDevice(dt, di, 0) + if o == 0: + continue + board = VCIBoardInfo() + rb = dll.VCI_ReadBoardInfo(dt, di, byref(board)) + hw = board.str_hw_Type.decode("utf-8", "ignore").strip("\x00") + sn = board.str_Serial_Num.decode("utf-8", "ignore").strip("\x00") + print(f"\n[OK] 设备可打开: DevType={dt}, DevIndex={di}, " + f"OpenDevice={o}, ReadBoardInfo={rb}") + print(f" 硬件类型: {hw or '(空)'}") + print(f" 序列号 : {sn or '(空)'}") + print(f" CAN通道数: {board.can_Num}") + found = True + try_dt, try_di = dt, di + try: + dll.VCI_CloseDevice(dt, di) + except Exception: + pass + # 只测试找到的第一个设备, 避免重复 + break + if found: + break + + if not found: + print("[FAIL] 所有 DevType/DevIndex 组合都无法打开设备.") + print(" 请确认: 设备已插入、驱动已安装、未被其他程序占用。") + return + + # 对找到的设备, 重点测试 VCI_SetReference + VCI_InitCAN 的 2E-U 标准流程 + print(f"\n[INFO] VCIInITConfig 结构体大小 = {ctypes.sizeof(VCIInITConfig)} 字节 (期望 16)") + + # 先按住找到的 DevType 测试 SetReference 前置流程 + print("\n--- 测试: OpenDevice -> SetReference(时钟) -> ResetCAN -> InitCAN ---") + ch = 0 + found_ok = 0 + + # 主时钟频率候选 (2E-U 设备可能是 8MHz 或 16MHz) + clk_values = [12000000, 16000000, 8000000, 2000000] + # Timing 候选 + t0t1_list = [ + (0x01, 0x14), # 用户工具时序 + (0x00, 0x14), + (0x00, 0x1C), + (0x03, 0x1C), + ] + + for dt in [try_dt] + [d for d in (21, 4, 3, 20) if d != try_dt]: + for clk in clk_values: + for (t0, t1) in t0t1_list: + try: + dll.VCI_CloseDevice(dt, try_di) + except Exception: + pass + if dll.VCI_OpenDevice(dt, try_di, 0) == 0: + continue + # 2E-U 关键: 先 SetReference 设置主时钟 + ref_ret = dll.VCI_SetReference( + dt, try_di, ch, 1, byref(ctypes.c_uint(clk))) + dll.VCI_ResetCAN(dt, try_di, ch) + + cfg = VCIInITConfig() + cfg.AccCode = 0 + cfg.AccMask = 0xFFFFFFFF + cfg.Reserved = 0 + cfg.Filter = 0 + cfg.Timing0 = t0 + cfg.Timing1 = t1 + cfg.Mode = 0 + ri = dll.VCI_InitCAN(dt, try_di, ch, byref(cfg)) + if ri > 0: + found_ok += 1 + cb = dll.VCI_ClearBuffer(dt, try_di, ch) + st = dll.VCI_StartCAN(dt, try_di, ch) + print(f"\n[OK] DevType={dt} 时钟={clk} T0=0x{t0:02X} T1=0x{t1:02X} " + f"-> SetRef={ref_ret} InitCAN={ri} (成功) " + f"ClearBuf={cb} StartCAN={st}") + dll.VCI_CloseDevice(dt, try_di) + break # 每组成功即停 + # 无成功则静默, 少量打印 + dll.VCI_CloseDevice(dt, try_di) + if found_ok: + break + if found_ok: + break + + global try_di_global + try_di_global = try_di + + if found_ok: + print(f"\n[成功] 找到可用组合, 共 {found_ok} 次成功.\n") + _real_rx_test(dll) + else: + print("\n[失败] 所有 DevType/SetReference/Timing 组合均失败.") + print(" 提示: 需要核对 ControlCAN.h 中该设备的 RefType 具体含义,") + print(" 以及 USBCAN_E_U(20)/USBCAN_2E_U(21) 的正确用法.") + print(" 请查阅随附的《4.接口函数库(二次开发库)使用说明书.pdf》") + + print("\n" + "=" * 60) + print("诊断完成。") + + +if __name__ == "__main__": main() \ No newline at end of file diff --git a/sim/__pycache__/__init__.cpython-312.pyc b/sim/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 5f96c29..0000000 Binary files a/sim/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/sim/__pycache__/__init__.cpython-38.pyc b/sim/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 1218e4e..0000000 Binary files a/sim/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/sim/__pycache__/can_layer.cpython-312.pyc b/sim/__pycache__/can_layer.cpython-312.pyc deleted file mode 100644 index 8521a13..0000000 Binary files a/sim/__pycache__/can_layer.cpython-312.pyc and /dev/null differ diff --git a/sim/__pycache__/can_layer.cpython-38.pyc b/sim/__pycache__/can_layer.cpython-38.pyc deleted file mode 100644 index 0113b0c..0000000 Binary files a/sim/__pycache__/can_layer.cpython-38.pyc and /dev/null differ diff --git a/sim/__pycache__/modbus_layer.cpython-312.pyc b/sim/__pycache__/modbus_layer.cpython-312.pyc deleted file mode 100644 index 15c52ba..0000000 Binary files a/sim/__pycache__/modbus_layer.cpython-312.pyc and /dev/null differ diff --git a/sim/__pycache__/modbus_layer.cpython-38.pyc b/sim/__pycache__/modbus_layer.cpython-38.pyc deleted file mode 100644 index aefd430..0000000 Binary files a/sim/__pycache__/modbus_layer.cpython-38.pyc and /dev/null differ diff --git a/sim/__pycache__/slave_sim.cpython-312.pyc b/sim/__pycache__/slave_sim.cpython-312.pyc deleted file mode 100644 index 87c5168..0000000 Binary files a/sim/__pycache__/slave_sim.cpython-312.pyc and /dev/null differ diff --git a/sim/__pycache__/slave_sim.cpython-38.pyc b/sim/__pycache__/slave_sim.cpython-38.pyc deleted file mode 100644 index b58638e..0000000 Binary files a/sim/__pycache__/slave_sim.cpython-38.pyc and /dev/null differ diff --git a/sim/__pycache__/web_gui.cpython-312.pyc b/sim/__pycache__/web_gui.cpython-312.pyc deleted file mode 100644 index 57e2cac..0000000 Binary files a/sim/__pycache__/web_gui.cpython-312.pyc and /dev/null differ diff --git a/sim/__pycache__/web_gui.cpython-38.pyc b/sim/__pycache__/web_gui.cpython-38.pyc deleted file mode 100644 index ba26d70..0000000 Binary files a/sim/__pycache__/web_gui.cpython-38.pyc and /dev/null differ diff --git a/sim/can_layer.py b/sim/can_layer.py index 2cbdd8e..1696654 100644 --- a/sim/can_layer.py +++ b/sim/can_layer.py @@ -449,9 +449,10 @@ class CanInterface: data = bytes(obj.Data[:obj.DataLen]) ts = time.strftime("%H:%M:%S") + (".%03d" % (obj.TimeStamp)) hex_str = " ".join("%02X" % b for b in data) - #print(f"[CAN RX] t={ts} ID=0x{arb_id:03X} LEN={len(data)} {hex_str}") + print(f"[CAN RX] t={ts} ID=0x{arb_id:03X} LEN={len(data)} {hex_str}") with self.rx_lock: self.rx_queue.append((arb_id, data)) + print( "qlen"+str(len(self.rx_queue))) except Exception: if self.running: time.sleep(0.01) @@ -530,7 +531,8 @@ class CanInterface: recv_crc = _struct.unpack('1曲线", 1002: "I>1时间(ms)", diff --git a/sim/slave_sim.py b/sim/slave_sim.py index 8446873..75d344f 100644 --- a/sim/slave_sim.py +++ b/sim/slave_sim.py @@ -49,6 +49,48 @@ TOKEN_MASTER_HOLD_S = 5 # 持有令牌作为 Master 的时间 (秒) TOKEN_VALUE_MASK = 0xFF00 # 高字节固定 0xFF TOKEN_SEQ_MASK = 0x00FF # 低字节为令牌序号 +# ---- IAP 固件升级相关 ---- +COIL_IAP_START = 31 # IAP升级开始 +COIL_IAP_UPGRADE = 32 # 升级[保护板] +COIL_IAP_OK = 35 # 升级成功 +COIL_IAP_FAIL = 36 # 升级失败 + +IAP_READY_DELAY_S = 2.0 # 收到线圈32后延迟2秒发就绪包 +IAP_READY_FRAME = b'\x01\x01\xFF' # 3 字节就绪包 (不遵循 Modbus 协议) + +# 固件数据包格式 (每包 256 字节, 不遵循 Modbus 协议) +IAP_FW_PACKET_SIZE = 256 # 固件数据包总长度 +IAP_FW_OFFSET_SIZE = 4 # 包头偏移地址长度 (高字节在前 / big-endian) +IAP_FW_DATA_SIZE = 250 # 每包固件数据长度 +IAP_FW_CRC_SIZE = 2 # 尾部 CRC 长度 (低字节在前, 高字节在后) + +IAP_ACK_FRAME = b'\x01\x01\xAA' # ACK: 包有效 +IAP_NACK_FRAME = b'\x01\x01\x55' # NACK: 包无效 + +# CRC16-CCITT (多项式 0x1021) +IAP_CRC_POLY = 0x1021 +IAP_CRC_INIT = 0xFFFF # 常用 CRC-16/CCITT-FALSE; 若与主站不符可改为 0x0000 + +IAP_FW_SAVE_DIR = 'iap_firmware' # 固件保存目录 (相对工程根目录) + +# ---- 系统时间寄存器 (656-662) ---- +# 7 个寄存器依次表示: 年 月 日 时 分 秒 毫秒 +# 运行期间持续与 PC 系统时间同步 (毫秒固定为 0) +TIME_REG_START = 656 +TIME_REG_COUNT = 7 +TIME_REG_MS = 0 + + +def crc16_ccitt(data: bytes, poly: int = IAP_CRC_POLY, + init: int = IAP_CRC_INIT) -> int: + """计算 CRC16-CCITT, 多项式 0x1021 (MSB-first, 无反相).""" + crc = init + for byte in data: + crc ^= (byte << 8) + for _ in range(8): + crc = ((crc << 1) ^ poly) if (crc & 0x8000) else (crc << 1) + crc &= 0xFFFF + return crc def create_default_registers(): """Create default register map with each register's value = its address.""" @@ -155,7 +197,23 @@ class SlaveSimulator: self.token_auto_return = False # 令牌自动回传模式 (False=手动, True=自动) self.TOKEN_AUTO_DELAY_S = 1.0 # 自动模式下收到令牌后延迟回传的秒数 + # IAP 升级状态 + self.iap_start = False # 收到 31 (IAP升级开始) + self.iap_upgrading = False # 收到 32 (升级[保护板]) + self.iap_ready_pending = False # 待发送就绪包 + self.iap_ready_time = 0.0 # 触发就绪包的时间戳 + self.iap_ready_sent = False # 就绪包是否已发送 + + # 固件接收 + self.iap_fw_chunks = [] # 已校验通过的固件数据块 (每块250字节) + self.iap_next_offset = 0 # 期望的下一包偏移 (0, 250, 500, ...) + + # 系统时间同步线程 (寄存器 656-662) + self.time_thread = None + self.time_running = False + self._init_registers() + self._update_time_registers() if config_path: self._apply_config(config_path) @@ -175,24 +233,64 @@ class SlaveSimulator: pass print(f"[CONFIG] Applied {len(config['registers'])} register overrides from {path}") + def _update_time_registers(self): + """将寄存器 656-662 更新为当前 PC 系统时间. + + 格式: 年 月 日 时 分 秒 毫秒 + 年: 完整年份 (如 2026) + 毫秒: 固定为 0 + """ + now = datetime.now() + self.registers[TIME_REG_START + 0] = now.year + self.registers[TIME_REG_START + 1] = now.month + self.registers[TIME_REG_START + 2] = now.day + self.registers[TIME_REG_START + 3] = now.hour + self.registers[TIME_REG_START + 4] = now.minute + self.registers[TIME_REG_START + 5] = now.second + self.registers[TIME_REG_START + 6] = TIME_REG_MS + + def _time_loop(self): + """后台线程: 每秒刷新一次系统时间寄存器.""" + while self.time_running: + try: + self._update_time_registers() + except Exception: + pass + time.sleep(1.0) + def start(self, bitrate=1000000): self.can = CanInterface(self.interface, CAN_SLAVE_ID, bitrate=bitrate) self.can.open() self.running = True self.thread = threading.Thread(target=self._run, daemon=True) self.thread.start() + + # 启动系统时间同步线程 (寄存器 656-662) + self.time_running = True + self.time_thread = threading.Thread(target=self._time_loop, daemon=True) + self.time_thread.start() + print(f"[SLAVE] Started on channel {self.interface}, " f"CAN ID=0x{CAN_SLAVE_ID:X}, " f"{bitrate/1000:.0f} kbps") def stop(self): self.running = False + self.time_running = False + if self.time_thread: + self.time_thread.join(timeout=2) + self.time_thread = None if self.can: self.can.close() def _run(self): while self.running: try: + # ---- IAP: 收到线圈32后延迟2秒发送就绪包 ---- + if (self.iap_ready_pending and not self.iap_ready_sent + and time.time() - self.iap_ready_time >= IAP_READY_DELAY_S): + self._send_iap_ready() + # ---- 自动模式下检查是否到时间回传令牌 ---- if (self.token_auto_return and self.has_token and not self.pending_token_send): @@ -244,8 +342,19 @@ class SlaveSimulator: if len(modbus_data) < 4: return + # ---- 诊断:打印每个重组出的完整报文的长度与首字节 ---- + head = " ".join("%02X" % b for b in modbus_data[:16]) + print(f"[RX-ASSEMBLED] len={len(modbus_data):>3} head={head}") + + # ---- 固件数据包: 固定 256 字节, 不遵循 Modbus 协议 ---- + # 仅当已发送就绪包后才开始接收; 判定: 整包 256 字节 + 升级链路就绪 + if len(modbus_data) == IAP_FW_PACKET_SIZE and self.iap_ready_sent: + self._handle_iap_firmware(modbus_data) + return + parsed = extract_modbus_data(modbus_data) if parsed is None or 'error' in parsed: + print(f"[RX-DROP] 非 Modbus 且非固件包: len={len(modbus_data)}") return addr = parsed.get('address', 0) @@ -316,6 +425,11 @@ class SlaveSimulator: self._send_response(response) return + # 若读取范围覆盖系统时间寄存器 (656-662), 先刷新为当前 PC 时间 + end = start + quantity - 1 + if start <= TIME_REG_START + TIME_REG_COUNT - 1 and end >= TIME_REG_START: + self._update_time_registers() + data = [] for i in range(quantity): reg_addr = start + i @@ -334,6 +448,8 @@ class SlaveSimulator: if 0 <= coil_addr <= 45: self.coils[coil_addr] = on self._execute_control(coil_addr, on) + # 处理 IAP 升级相关线圈 (31/32/35/36) + self._handle_iap_write(coil_addr, on) # 使用 bit7=1 的响应地址 resp_addr = make_response_addr(SLAVE_MODBUS_ADDR, sender_addr) @@ -412,6 +528,164 @@ class SlaveSimulator: self.token_seq = next_seq return True + # ======== IAP 固件升级 ======== + + def _handle_iap_write(self, coil_addr: int, on: bool): + """处理 IAP 升级相关线圈写入. + + 31: IAP升级开始 -> 显示"升级开始"状态 + 32: 升级[保护板] -> 显示"升级中"状态, 2秒后发 3 字节就绪包 + 35/36: 升级成功/失败 -> 清除 31/32 两个状态 + """ + if coil_addr == COIL_IAP_START: + self.iap_start = on + if on: + # 新一轮升级开始: 清空上一轮固件数据 + self.iap_fw_chunks = [] + self.iap_next_offset = 0 + print(f"[IAP] Coil 31 (IAP升级开始) = ON, 固件接收已复位") + else: + print(f"[IAP] Coil 31 (IAP升级开始) = OFF") + elif coil_addr == COIL_IAP_UPGRADE: + self.iap_upgrading = on + if on: + self.iap_ready_pending = True + self.iap_ready_time = time.time() + self.iap_ready_sent = False + print(f"[IAP] Coil 32 (升级[保护板]) = ON, " + f"{IAP_READY_DELAY_S:.0f}秒后发送就绪包 01 01 FF") + else: + self.iap_ready_pending = False + print(f"[IAP] Coil 32 (升级[保护板]) = OFF") + elif coil_addr in (COIL_IAP_OK, COIL_IAP_FAIL): + if on: + if coil_addr == COIL_IAP_OK: + self._finalize_iap_success() + else: + self._finalize_iap_fail() + print(f"[IAP] Coil {coil_addr} " + f"({'升级成功' if coil_addr == COIL_IAP_OK else '升级失败'}) = ON") + + def _handle_iap_firmware(self, pkt: bytes): + """处理一个 256 字节固件数据包. + + [0:4] 偏移地址 (big-endian, 高字节在前), 期望 0, 250, 500, ... + [4:254] 250 字节固件数据 + [254:256] CRC16-CCITT (0x1021), 低字节在前, 高字节在后 + """ + offset = struct.unpack('>I', pkt[0:IAP_FW_OFFSET_SIZE])[0] + payload = pkt[IAP_FW_OFFSET_SIZE:IAP_FW_OFFSET_SIZE + IAP_FW_DATA_SIZE] + recv_crc = struct.unpack('5} 校验OK, " + f"已收{len(self.iap_fw_chunks)}块 -> ACK") + else: + self.can.send_modbus_frame(IAP_NACK_FRAME) + reason = [] + if not ok_offset: + reason.append(f"偏移{offset}(期望{self.iap_next_offset})") + if not ok_crc: + reason.append(f"CRC(收0x{recv_crc:04X}/算0x{calc_crc:04X})") + print(f"[IAP] 固件包 偏移={offset:>5} 校验失败 " + f"({' '.join(reason)}) -> NACK") + + def _finalize_iap_success(self): + """升级成功(35): 拼接固件写入 bin 文件, 输出文件路径/大小.""" + self.iap_start = False + self.iap_upgrading = False + self.iap_ready_pending = False + self.iap_ready_sent = False + + fw = b''.join(self.iap_fw_chunks) + self.iap_fw_chunks = [] + next_offset = self.iap_next_offset + self.iap_next_offset = 0 + + if not fw: + log = self._get_logger() + log("固件升级成功, 但未收到任何固件数据") + print("[IAP] 升级成功, 但未收到任何固件数据") + return + + try: + save_dir = os.path.join(os.path.dirname(__file__), + '..', IAP_FW_SAVE_DIR) + os.makedirs(save_dir, exist_ok=True) + path = os.path.join(save_dir, + f"firmware_{datetime.now().strftime('%Y%m%d_%H%M%S')}.bin") + with open(path, 'wb') as f: + f.write(fw) + abs_path = os.path.abspath(path) + size = len(fw) + log = self._get_logger() + log(f"固件升级成功: 文件 {abs_path}, 大小 {size} 字节, " + f"共 {size // IAP_FW_DATA_SIZE} 块, 末偏移 0x{next_offset:04X}") + print(f"[IAP] 升级成功, 已保存: {abs_path} ({size} 字节)") + except Exception as e: + log = self._get_logger() + log(f"固件保存失败: {e}") + print(f"[IAP] 固件保存失败: {e}") + + def _finalize_iap_fail(self): + """升级失败(36): 丢弃已收数据, 清除升级状态.""" + self.iap_start = False + self.iap_upgrading = False + self.iap_ready_pending = False + self.iap_ready_sent = False + lost = len(self.iap_fw_chunks) + self.iap_fw_chunks = [] + self.iap_next_offset = 0 + self._get_logger()( + f"固件升级失败, 已丢弃 {lost} 个数据块") + print(f"[IAP] 升级失败, 已丢弃 {lost} 块固件数据") + + @staticmethod + def _get_logger(): + """惰性获取 Web 日志函数, 避免与 web_gui 循环导入.""" + from .web_gui import log_message + return log_message + + def _send_iap_ready(self): + """发送 3 字节就绪包 01 01 FF (不遵循 Modbus 协议).""" + if not self.can: + self.iap_ready_pending = False + return + self.iap_ready_pending = False + self.iap_ready_sent = True + print(f"[IAP] <<< 发送就绪包: " + f"{' '.join('%02X' % b for b in IAP_READY_FRAME)} " + f"(设备就绪, 等待固件数据)") + self.can.send_modbus_frame(IAP_READY_FRAME) + + def get_iap_status(self) -> dict: + """返回当前 IAP 升级状态, 供 Web GUI 的 /api/iap 接口调用.""" + if self.iap_upgrading and self.iap_ready_sent: + state = "UPGRADING" + elif self.iap_upgrading: + state = "READY_PENDING" + elif self.iap_start: + state = "STARTED" + else: + state = "IDLE" + return { + 'iap_start': self.iap_start, + 'upgrading': self.iap_upgrading, + 'ready_sent': self.iap_ready_sent, + 'fw_chunks': len(self.iap_fw_chunks), + 'fw_next_offset': self.iap_next_offset, + 'state': state, + } + # ======== 公开接口 (供 Web GUI 调用) ======== def get_token_status(self) -> dict: @@ -501,6 +775,9 @@ class SlaveSimulator: self.registers[addr] = value & 0xFFFF def get_register(self, addr): + # 读取系统时间寄存器 (656-662) 时即时刷新, 保证返回最新 PC 时间 + if TIME_REG_START <= addr < TIME_REG_START + TIME_REG_COUNT: + self._update_time_registers() return self.registers.get(addr, 0) def generate_event(self, event_type, event_data=0): diff --git a/sim/web_gui.py b/sim/web_gui.py index bc6a091..66a43ca 100644 --- a/sim/web_gui.py +++ b/sim/web_gui.py @@ -96,7 +96,10 @@ REGISTER_NAMES = { 600: "保护板软件版本", 608: "装置型号", 616: "装置ID", 624: "制造日期", 632: "制造时间", 640: "序列号", 648: "设备位号", - 656: "MAC地址", 663: "LCD版本", 671: "增强板版本", + 656: "系统时间-年", 657: "系统时间-月", 658: "系统时间-日", + 659: "系统时间-时", 660: "系统时间-分", 661: "系统时间-秒", + 662: "系统时间-毫秒", + 663: "LCD版本", 671: "增强板版本", # ---- 保护参数 (1000-1079) ---- 1000: "Ir1 过流1段(0.1A)", 1001: "I>1曲线", 1002: "I>1时间(ms)", @@ -862,6 +865,8 @@ HTML_PAGE = r""" 0 寄存器 + + @@ -957,6 +962,7 @@ document.addEventListener('DOMContentLoaded', function() { loadAreas(); checkStatus(); checkTokenStatus(); + checkIapStatus(); startAutoRefresh(); refreshLogs(); loadCoils(); @@ -1331,6 +1337,10 @@ async function toggleCoil(addr) { const led = item.querySelector('.coil-led'); if (led) led.className = `coil-led ${result.on ? 'on' : 'off'}`; } + // IAP 相关线圈切换后立即刷新升级状态 + if (addr === 31 || addr === 32 || addr === 35 || addr === 36) { + checkIapStatus(); + } } } catch (e) { console.error('切换线圈失败:', e); @@ -1453,6 +1463,45 @@ async function checkTokenStatus() { } } +// ============================================================ +// IAP 升级状态 +// ============================================================ +async function checkIapStatus() { + const startBadge = document.getElementById('iapStartBadge'); + const upgradBadge = document.getElementById('iapUpgradingBadge'); + try { + const data = await apiGet('/api/iap'); + // 31: IAP升级开始 + if (data.iap_start) { + startBadge.style.display = 'inline'; + startBadge.textContent = '升级开始'; + startBadge.style.background = '#722ed1'; + startBadge.style.color = 'white'; + } else { + startBadge.style.display = 'none'; + } + // 32: 升级[保护板] (升级中) + if (data.upgrading) { + upgradBadge.style.display = 'inline'; + if (data.ready_sent) { + const chunks = (data.fw_chunks || 0); + upgradBadge.textContent = chunks > 0 + ? `保护板升级中 (已收${chunks}块)` + : '保护板升级中'; + upgradBadge.style.background = '#eb2f96'; + } else { + upgradBadge.textContent = '保护板就绪中...'; + upgradBadge.style.background = '#fa8c16'; + } + upgradBadge.style.color = 'white'; + } else { + upgradBadge.style.display = 'none'; + } + } catch (e) { + console.warn('[IAP] checkIapStatus error:', e); + } +} + async function toggleTokenAuto() { const chk = document.getElementById('chkTokenAuto'); const enabled = chk.checked; @@ -1558,6 +1607,7 @@ async function refreshOpenAreas() { if (!autoRefresh) return; refreshCoils(); checkTokenStatus(); + checkIapStatus(); const tables = document.querySelectorAll('.reg-table.open'); for (const table of tables) { const section = table.closest('.area');