From b6cf723cad6b0d6002327eff6a0bae0f38002bab Mon Sep 17 00:00:00 2001
From: ldh <17393183636@163.com>
Date: Fri, 6 Nov 2026 14:55:37 +0800
Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=B9=E7=9B=AE=E6=96=87?=
=?UTF-8?q?=E4=BB=B6=E3=80=82?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 89 ++++
TS660_Bridge.ini.sample | 60 +++
TS660_DLL.sln | 28 ++
TS660_DLL/TS660_DLL.vcxproj | 191 ++++++++
TS660_DLL/TS660_DLL.vcxproj.filters | 62 +++
TS660_DLL/src/TS660_DLL.def | 12 +
TS660_DLL/src/bridge.cpp | 257 ++++++++++
TS660_DLL/src/bridge.h | 56 +++
TS660_DLL/src/bridge_config.cpp | 182 +++++++
TS660_DLL/src/bridge_config.h | 45 ++
TS660_DLL/src/exports.cpp | 169 +++++++
TS660_DLL/src/link.h | 24 +
TS660_DLL/src/log.cpp | 78 +++
TS660_DLL/src/log.h | 29 ++
TS660_DLL/src/tdg7_device.cpp | 709 ++++++++++++++++++++++++++++
TS660_DLL/src/tdg7_device.h | 60 +++
TS660_DLL/src/win32_link.cpp | 158 +++++++
TS660_DLL/src/win32_link.h | 28 ++
build.cmd | 29 ++
19 files changed, 2266 insertions(+)
create mode 100644 README.md
create mode 100644 TS660_Bridge.ini.sample
create mode 100644 TS660_DLL.sln
create mode 100644 TS660_DLL/TS660_DLL.vcxproj
create mode 100644 TS660_DLL/TS660_DLL.vcxproj.filters
create mode 100644 TS660_DLL/src/TS660_DLL.def
create mode 100644 TS660_DLL/src/bridge.cpp
create mode 100644 TS660_DLL/src/bridge.h
create mode 100644 TS660_DLL/src/bridge_config.cpp
create mode 100644 TS660_DLL/src/bridge_config.h
create mode 100644 TS660_DLL/src/exports.cpp
create mode 100644 TS660_DLL/src/link.h
create mode 100644 TS660_DLL/src/log.cpp
create mode 100644 TS660_DLL/src/log.h
create mode 100644 TS660_DLL/src/tdg7_device.cpp
create mode 100644 TS660_DLL/src/tdg7_device.h
create mode 100644 TS660_DLL/src/win32_link.cpp
create mode 100644 TS660_DLL/src/win32_link.h
create mode 100644 build.cmd
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f56cd39
--- /dev/null
+++ b/README.md
@@ -0,0 +1,89 @@
+# TS660_DLL(B 设备版)Visual Studio 2026 工程
+
+把 B 设备(TDG-7 七通道时序发生器)包装成 A 设备(TS660)的 `TS660_DLL.dll`。
+本工程只负责编译这个原生 DLL;主程序 `SpectroVision` 不需要任何改动,替换 DLL 即可。
+
+## 目录
+
+```
+Delay-WZ/
+├─ TS660_DLL.sln 解决方案(VS2026 直接打开)
+├─ build.cmd 命令行一键编译 x64 + x86
+├─ TS660_Bridge.ini.sample 可选配置模板(改名为 TS660_Bridge.ini 生效)
+└─ TS660_DLL/
+ ├─ TS660_DLL.vcxproj
+ ├─ TS660_DLL.vcxproj.filters
+ └─ src/
+ ├─ exports.cpp 9 个 ts660_* 导出(句柄校验)
+ ├─ TS660_DLL.def 导出名表(x86 下保持未修饰名)
+ ├─ bridge.cpp/.h A 语义 → B 语义(通道映射、触发、全局输出)
+ ├─ bridge_config.cpp/.h 默认值 + TS660_Bridge.ini 解析
+ ├─ tdg7_device.cpp/.h B 设备串口协议(命令拼装、应答解析、回读校验)
+ ├─ win32_link.cpp/.h Win32 串口(8N1、无流控、DTR/RTS 关闭)
+ └─ log.cpp/.h 可选日志(文件 + OutputDebugString)
+```
+
+## 编译
+
+### 方式一:Visual Studio 2026
+
+1. 双击 `TS660_DLL.sln`;
+2. 顶部工具栏选择 `Release` + `x64`(或 `x86`);
+3. `生成 → 生成解决方案`(F7)。
+
+输出:
+
+| 平台 | 输出路径 |
+| --- | --- |
+| x64 | `bin\x64\Release\TS660_DLL.dll` |
+| x86 | `bin\Win32\Release\TS660_DLL.dll` |
+| Debug | 对应 `bin\<平台>\Debug\` |
+
+### 方式二:命令行
+
+```bat
+build.cmd
+```
+
+脚本会通过 `vswhere` 找 MSBuild,依次编 Release x64 和 Release x86。
+
+## 部署
+
+把对应位数的 `TS660_DLL.dll` 复制到 `SpectroVision.exe` 同目录(覆盖原文件,先备份)。
+位数必须与 exe 一致,否则会报 `BadImageFormatException`。
+
+需要调试串口时,把 `TS660_Bridge.ini.sample` 改名为 `TS660_Bridge.ini`,与 DLL 放一起,内容:
+
+```ini
+[Log]
+Enable=1
+```
+
+日志默认写到 DLL 同目录 `TS660_Bridge.log`,包含每条 `TX` / `RX`、触发模式、发射时的输出状态。
+
+## 改代码的位置
+
+| 想改什么 | 改哪里 |
+| --- | --- |
+| A→B 通道映射(默认 A1→B4、A2→B5、A3→B1、A4→B2) | `src/bridge_config.h` 的 `map[5]`,或 ini 的 `[ChannelMap]` |
+| A 触发模式 → B `TrigSel/FireMode` | `src/bridge_config.h` 的 `trigSel` / `fireMode`,或 ini 的 `[Trigger]` |
+| 通道打开/关闭时写 B 的 `Ch{n}Out` 值 | `src/bridge_config.h` 的 `onMode` / `offMode`,或 ini 的 `[Output]` |
+| 串口超时、写后延时、回读校验 | `src/bridge_config.h`,或 ini 的 `[Bridge]` |
+| B 协议命令格式 / 应答解析 | `src/tdg7_device.cpp` |
+| 导出函数签名 | `src/exports.cpp` + `src/TS660_DLL.def`(两处都要加) |
+
+> 源码是 **UTF-8 with BOM**,工程已经设置 `/utf-8`。新增/另存源文件时保持 UTF-8,
+> 不要存成 GBK,否则中文日志字符串会编译报错。
+
+## 新增导出函数
+
+1. 在 `TS660_DLL.def` 的 `EXPORTS` 里加函数名;
+2. 在 `exports.cpp` 里写 `extern "C" 返回类型 函数名(参数...)`;
+3. 主程序 `DelayerAPI.cs` 里补同签名的 `[DllImport]`(使用 `CallingConvention.Cdecl`)。
+
+## 与主程序的关系
+
+* 主程序通过 `[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]` 调用 9 个函数;
+* 本 DLL 用 `/MT` 静态链接 CRT,目标机不需要装 VC++ 运行库,只依赖 `KERNEL32.dll`;
+* 协议/映射测试和 ABI 测试在本仓库的 `TS660Bridge\tests`(用 `TS660Bridge\build.ps1` 运行),
+ 本工程只编译 DLL 本体,便于现场改参数后快速出包。
diff --git a/TS660_Bridge.ini.sample b/TS660_Bridge.ini.sample
new file mode 100644
index 0000000..6794244
--- /dev/null
+++ b/TS660_Bridge.ini.sample
@@ -0,0 +1,60 @@
+; TS660_DLL(B 设备版)可选配置文件
+;
+; 用法:把本文件改名为 TS660_Bridge.ini,与 TS660_DLL.dll 放在同一目录。
+; 不提供本文件时,DLL 使用下面列出的内置默认值,行为完全一致。
+;
+; 注意:所有数值都可用十进制;布尔值用 1/0。
+
+[Bridge]
+; 串口名覆盖。留空 = 使用主程序配置项 SelectedSPort_Delayer 里的端口(如 COM3)。
+Port=
+; 波特率。0 表示按 ts660_init 传入值,仍为 0 时用 9600。
+Baud=9600
+; 单条命令等待应答的超时(毫秒)。
+ReadTimeoutMs=600
+; 写命令后等待仪器处理的固定延时(毫秒),与 Tdg7ChlDriver 一致。
+WriteSettleMs=10
+; 写参数后回读校验;1=开启。
+VerifyReadback=1
+; 打开串口时先把 7 个通道输出全部置为 OffMode(GND),避免上电残留脉冲。
+SilenceOnOpen=1
+
+[ChannelMap]
+; A 设备通道 -> B 设备通道(1..7,不能重复)
+A1=B4
+A2=B5
+A3=B1
+A4=B2
+
+[Trigger]
+; A 设备触发模式 -> B 设备 (TrigSel, FireMode)
+; TrigSel: 0=内触发 1=外触发上升沿 2=外触发下降沿
+; FireMode: 0=连续 1=单次
+; A 主程序只使用 0(内部触发)与 2(软件触发)。
+; 若 B 固件在 TrigSel=1 下 Fire 不产生脉冲,可把 Mode2TrigSel 改成 0 试试。
+Mode0TrigSel=0
+Mode0FireMode=0
+Mode1TrigSel=1
+Mode1FireMode=0
+Mode2TrigSel=1
+Mode2FireMode=1
+Mode3TrigSel=2
+Mode3FireMode=0
+Mode4TrigSel=2
+Mode4FireMode=1
+
+[Output]
+; 通道开启/关闭时写入 B 的 Ch{n}Out 值:
+; 0=正脉冲 1=负脉冲 2=常高+5V 3=常低GND
+OnMode=0
+OffMode=3
+
+[Temperature]
+; B 设备没有温度传感器,ts660_read_temperature 固定返回该值。
+Celsius=25.0
+
+[Log]
+; 调试时置 1,会把每条收发命令写入日志,便于定位串口/协议问题。
+Enable=0
+; 留空 = DLL 同目录 TS660_Bridge.log;也可以写绝对路径(需可写目录)。
+File=
diff --git a/TS660_DLL.sln b/TS660_DLL.sln
new file mode 100644
index 0000000..2c844fe
--- /dev/null
+++ b/TS660_DLL.sln
@@ -0,0 +1,28 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 18
+VisualStudioVersion = 18.0.0.0
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TS660_DLL", "TS660_DLL\TS660_DLL.vcxproj", "{0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Debug|x64.ActiveCfg = Debug|x64
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Debug|x64.Build.0 = Debug|x64
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Debug|x86.ActiveCfg = Debug|Win32
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Debug|x86.Build.0 = Debug|Win32
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Release|x64.ActiveCfg = Release|x64
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Release|x64.Build.0 = Release|x64
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Release|x86.ActiveCfg = Release|Win32
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}.Release|x86.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/TS660_DLL/TS660_DLL.vcxproj b/TS660_DLL/TS660_DLL.vcxproj
new file mode 100644
index 0000000..168a37c
--- /dev/null
+++ b/TS660_DLL/TS660_DLL.vcxproj
@@ -0,0 +1,191 @@
+
+
+
+
+ Debug
+ Win32
+
+
+ Release
+ Win32
+
+
+ Debug
+ x64
+
+
+ Release
+ x64
+
+
+
+ 17.0
+ {0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}
+ TS660Bridge
+ TS660_DLL
+ 10.0
+
+
+
+ DynamicLibrary
+ true
+ v145
+ MultiByte
+
+
+ DynamicLibrary
+ false
+ v145
+ false
+ MultiByte
+
+
+ DynamicLibrary
+ true
+ v145
+ MultiByte
+
+
+ DynamicLibrary
+ false
+ v145
+ false
+ MultiByte
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ TS660_DLL
+ $(ProjectDir)..\bin\$(Platform)\$(Configuration)\
+ $(ProjectDir)..\obj\$(Platform)\$(Configuration)\
+
+
+
+ Level4
+ false
+ WIN32;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
+ true
+ stdcpp17
+ /utf-8 %(AdditionalOptions)
+ $(ProjectDir)src;%(AdditionalIncludeDirectories)
+ NotUsing
+ Disabled
+ MultiThreadedDebug
+ true
+ ProgramDatabase
+
+
+ Windows
+ true
+ $(ProjectDir)src\TS660_DLL.def
+ /NOIMPLIB /NOEXP %(AdditionalOptions)
+
+
+
+
+ Level4
+ false
+ WIN32;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
+ true
+ stdcpp17
+ /utf-8 %(AdditionalOptions)
+ $(ProjectDir)src;%(AdditionalIncludeDirectories)
+ NotUsing
+ MaxSpeed
+ true
+ true
+ MultiThreaded
+ true
+
+
+ Windows
+ false
+ true
+ true
+ $(ProjectDir)src\TS660_DLL.def
+ /NOIMPLIB /NOEXP %(AdditionalOptions)
+
+
+
+
+ Level4
+ false
+ _WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
+ true
+ stdcpp17
+ /utf-8 %(AdditionalOptions)
+ $(ProjectDir)src;%(AdditionalIncludeDirectories)
+ NotUsing
+ Disabled
+ MultiThreadedDebug
+ true
+ ProgramDatabase
+
+
+ Windows
+ true
+ $(ProjectDir)src\TS660_DLL.def
+ /NOIMPLIB /NOEXP %(AdditionalOptions)
+
+
+
+
+ Level4
+ false
+ _WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
+ true
+ stdcpp17
+ /utf-8 %(AdditionalOptions)
+ $(ProjectDir)src;%(AdditionalIncludeDirectories)
+ NotUsing
+ MaxSpeed
+ true
+ true
+ MultiThreaded
+ true
+
+
+ Windows
+ false
+ true
+ true
+ $(ProjectDir)src\TS660_DLL.def
+ /NOIMPLIB /NOEXP %(AdditionalOptions)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/TS660_DLL/TS660_DLL.vcxproj.filters b/TS660_DLL/TS660_DLL.vcxproj.filters
new file mode 100644
index 0000000..9c0925c
--- /dev/null
+++ b/TS660_DLL/TS660_DLL.vcxproj.filters
@@ -0,0 +1,62 @@
+
+
+
+
+ {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
+ cpp;c;cc;cxx
+
+
+ {93995380-89BD-4b04-88EB-625FBE52EBFB}
+ h;hpp;hxx
+
+
+ {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
+ def;rc
+
+
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+ Header Files
+
+
+
+
+ Resource Files
+
+
+
diff --git a/TS660_DLL/src/TS660_DLL.def b/TS660_DLL/src/TS660_DLL.def
new file mode 100644
index 0000000..73a3b60
--- /dev/null
+++ b/TS660_DLL/src/TS660_DLL.def
@@ -0,0 +1,12 @@
+LIBRARY TS660_DLL
+EXPORTS
+ ts660_init
+ ts660_close
+ ts660_read_temperature
+ ts660_set_trigger
+ ts660_set_trigger_freq
+ ts660_set_output_channel
+ ts660_set_delay
+ ts660_set_global_output
+ ts660_software_trigger
+ ts660_set_pulse_width
diff --git a/TS660_DLL/src/bridge.cpp b/TS660_DLL/src/bridge.cpp
new file mode 100644
index 0000000..589fb02
--- /dev/null
+++ b/TS660_DLL/src/bridge.cpp
@@ -0,0 +1,257 @@
+#include "bridge.h"
+
+#include "log.h"
+
+#include
+
+#include
+#include
+
+namespace ts660b
+{
+ namespace
+ {
+ std::wstring AnsiToWide(const std::string& text)
+ {
+ if (text.empty())
+ return std::wstring();
+
+ const int length = ::MultiByteToWideChar(CP_ACP, 0, text.c_str(), (int)text.size(), nullptr, 0);
+ if (length <= 0)
+ return std::wstring();
+
+ std::wstring result((size_t)length, L'\0');
+ ::MultiByteToWideChar(CP_ACP, 0, text.c_str(), (int)text.size(), &result[0], length);
+ return result;
+ }
+
+ void Trim(std::wstring& text)
+ {
+ size_t begin = 0;
+ while (begin < text.size() && (text[begin] == L' ' || text[begin] == L'\t' || text[begin] == L'"'))
+ ++begin;
+ size_t end = text.size();
+ while (end > begin && (text[end - 1] == L' ' || text[end - 1] == L'\t' || text[end - 1] == L'"'))
+ --end;
+ text = text.substr(begin, end - begin);
+ }
+ }
+
+ Bridge::Bridge(std::unique_ptr link, const BridgeConfig& config)
+ : device_(std::move(link)), config_(config)
+ {
+ device_.SetTimeoutMs(config_.readTimeoutMs);
+ device_.SetSettleMs(config_.writeSettleMs);
+ device_.SetVerifyReadback(config_.verifyReadback);
+ }
+
+ Bridge::~Bridge()
+ {
+ Close();
+ }
+
+ bool Bridge::Open(const std::string& portAnsi, int baudRate)
+ {
+ std::lock_guard guard(mutex_);
+
+ std::wstring port = config_.portOverride;
+ if (port.empty())
+ port = AnsiToWide(portAnsi);
+ Trim(port);
+
+ int baud = config_.baudRate;
+ if (baud <= 0)
+ baud = (baudRate > 0) ? baudRate : 9600;
+
+ if (!device_.Open(port, baud))
+ return false;
+
+ // 与 Tdg7ChlDriver.Open 一致:7 个通道分频统一置 1(忽略单条结果)
+ for (int b = 1; b <= 7; ++b)
+ device_.SetFrequencyDivider(b, 1);
+
+ // 上电先把所有通道拉到关闭电平,避免残留输出
+ if (config_.silenceAllChannelsOnOpen)
+ {
+ for (int b = 1; b <= 7; ++b)
+ device_.SetOutputMode(b, config_.offMode);
+ }
+
+ globalOutput_ = false;
+ explicitStop_ = false;
+ for (int a = 1; a <= 4; ++a)
+ channels_[a].enabled = false;
+
+ Logger::Instance().Write("bridge opened: %ls @ %d, map A1->B%d A2->B%d A3->B%d A4->B%d",
+ port.c_str(), baud,
+ config_.map[1], config_.map[2], config_.map[3], config_.map[4]);
+ return true;
+ }
+
+ void Bridge::Close()
+ {
+ std::lock_guard guard(mutex_);
+ device_.Close();
+ }
+
+ bool Bridge::IsOpen() const
+ {
+ return device_.IsOpen();
+ }
+
+ int Bridge::ToHardwareChannel(int aChannel)
+ {
+ if (aChannel < 1 || aChannel > 4)
+ {
+ Logger::Instance().Write("ERR 通道号 %d 超出 A 设备 1..4", aChannel);
+ return -1;
+ }
+ return config_.map[aChannel];
+ }
+
+ bool Bridge::ApplyChannelOutput(int aChannel, int bChannel)
+ {
+ const bool on = globalOutput_ && channels_[aChannel].enabled;
+ return device_.SetOutputMode(bChannel, on ? config_.onMode : config_.offMode);
+ }
+
+ int Bridge::ReadTemperature(float* outCelsius)
+ {
+ if (outCelsius == nullptr)
+ return -1;
+ std::lock_guard guard(mutex_);
+ // B 设备没有温度传感器:返回配置值(默认 25℃)
+ *outCelsius = config_.temperatureCelsius;
+ return 0;
+ }
+
+ int Bridge::SetTrigger(int mode)
+ {
+ std::lock_guard guard(mutex_);
+ if (mode < 0 || mode > 4)
+ {
+ Logger::Instance().Write("ERR 触发模式 %d 超出 0..4", mode);
+ return -1;
+ }
+
+ const int trigSel = config_.trigSel[mode];
+ const int fireMode = config_.fireMode[mode];
+ Logger::Instance().Write("TRIGGER A mode=%d -> B TrigSel=%d FireMode=%d", mode, trigSel, fireMode);
+
+ const bool ok = device_.SetTrigger(trigSel, fireMode);
+ if (ok)
+ lastTriggerMode_ = mode;
+ else
+ Logger::Instance().Write("ERR 触发模式设置失败(A mode=%d)", mode);
+ return ok ? 0 : -1;
+ }
+
+ int Bridge::SetTriggerFrequency(double hz)
+ {
+ std::lock_guard guard(mutex_);
+ if (!(hz > 0.0) || hz > 999999.0)
+ {
+ Logger::Instance().Write("ERR 触发频率 %.3f 超出 1..999999Hz", hz);
+ return -1;
+ }
+
+ const int value = (int)std::llround(hz);
+ bool ok = true;
+
+ // A 的 4 个通道必须设置成功
+ for (int a = 1; a <= 4; ++a)
+ {
+ if (!device_.SetFrequency(config_.map[a], value))
+ ok = false;
+ }
+ // B 上未使用的通道尽力设置,失败不影响结果
+ for (int b = 1; b <= 7; ++b)
+ {
+ if (!config_.IsMappedChannel(b))
+ device_.SetFrequency(b, value);
+ }
+ return ok ? 0 : -1;
+ }
+
+ int Bridge::SetOutputChannel(int aChannel, int enable)
+ {
+ std::lock_guard guard(mutex_);
+ const int bChannel = ToHardwareChannel(aChannel);
+ if (bChannel < 0)
+ return -1;
+
+ channels_[aChannel].enabled = (enable != 0);
+ return ApplyChannelOutput(aChannel, bChannel) ? 0 : -1;
+ }
+
+ int Bridge::SetDelay(int aChannel, long long delayNs)
+ {
+ std::lock_guard guard(mutex_);
+ const int bChannel = ToHardwareChannel(aChannel);
+ if (bChannel < 0)
+ return -1;
+ return device_.SetDelayNs(bChannel, delayNs) ? 0 : -1;
+ }
+
+ int Bridge::SetPulseWidth(int aChannel, long long widthNs)
+ {
+ std::lock_guard guard(mutex_);
+ const int bChannel = ToHardwareChannel(aChannel);
+ if (bChannel < 0)
+ return -1;
+ return device_.SetPulseWidthNs(bChannel, widthNs) ? 0 : -1;
+ }
+
+ int Bridge::SetGlobalOutput(int enable)
+ {
+ std::lock_guard guard(mutex_);
+ if (!IsOpen())
+ return -1;
+
+ globalOutput_ = (enable != 0);
+ explicitStop_ = !globalOutput_;
+
+ int result = 0;
+ for (int a = 1; a <= 4; ++a)
+ {
+ if (!ApplyChannelOutput(a, config_.map[a]))
+ result = -1;
+ }
+ return result;
+ }
+
+ int Bridge::SoftwareTrigger()
+ {
+ std::lock_guard guard(mutex_);
+ if (!IsOpen())
+ return -1;
+
+ // “发射”是单次动作:若此时总输出还没打开(例如只点了“应用”、没点“开始工作”),
+ // 先把已使能的通道切到输出电平,否则设备收到 Fire 也不会出脉冲。
+ // 但如果操作员显式点过“停止工作”,就不自动恢复输出。
+ if (!globalOutput_)
+ {
+ if (lastTriggerMode_ == 2 && !explicitStop_)
+ {
+ Logger::Instance().Write("WARN 发射前输出未使能,自动开启(软件触发模式)");
+ globalOutput_ = true;
+ for (int a = 1; a <= 4; ++a)
+ {
+ if (!ApplyChannelOutput(a, config_.map[a]))
+ {
+ Logger::Instance().Write("ERR 自动开启输出失败:A%d -> B%d", a, config_.map[a]);
+ return -1;
+ }
+ }
+ }
+ else
+ {
+ Logger::Instance().Write("WARN 发射时全局输出未开启(当前 A 触发模式 %d,显式停止=%d)",
+ lastTriggerMode_, explicitStop_ ? 1 : 0);
+ }
+ }
+
+ Logger::Instance().Write("FIRE global=%d A-mode=%d", globalOutput_ ? 1 : 0, lastTriggerMode_);
+ return device_.Fire(1) ? 0 : -1;
+ }
+}
diff --git a/TS660_DLL/src/bridge.h b/TS660_DLL/src/bridge.h
new file mode 100644
index 0000000..f90055b
--- /dev/null
+++ b/TS660_DLL/src/bridge.h
@@ -0,0 +1,56 @@
+#pragma once
+
+#include "bridge_config.h"
+#include "tdg7_device.h"
+
+#include
+#include
+#include
+
+namespace ts660b
+{
+ // A 设备(TS660)语义 -> B 设备(TDG-7)语义的桥。
+ //
+ // 内部保留 A 的 4 个通道状态;B 的其余通道在打开时统一拉到 offMode,
+ // 避免未接线的通道继续输出脉冲。
+ class Bridge
+ {
+ public:
+ Bridge(std::unique_ptr link, const BridgeConfig& config);
+ ~Bridge();
+
+ bool Open(const std::string& portAnsi, int baudRate);
+ void Close();
+ bool IsOpen() const;
+
+ // 返回值遵循 DelayerAPI.DELAYER_OK(0) / 非 0 失败
+ int ReadTemperature(float* outCelsius);
+ int SetTrigger(int mode);
+ int SetTriggerFrequency(double hz);
+ int SetOutputChannel(int aChannel, int enable);
+ int SetDelay(int aChannel, long long delayNs);
+ int SetPulseWidth(int aChannel, long long widthNs);
+ int SetGlobalOutput(int enable);
+ int SoftwareTrigger();
+
+ const BridgeConfig& Config() const { return config_; }
+ std::string LastError() const { return device_.LastError(); }
+
+ private:
+ int ToHardwareChannel(int aChannel);
+ bool ApplyChannelOutput(int aChannel, int bChannel);
+
+ struct ChannelState
+ {
+ bool enabled = false;
+ };
+
+ Tdg7Device device_;
+ BridgeConfig config_;
+ std::mutex mutex_;
+ ChannelState channels_[5];
+ bool globalOutput_ = false;
+ bool explicitStop_ = false;
+ int lastTriggerMode_ = -1;
+ };
+}
diff --git a/TS660_DLL/src/bridge_config.cpp b/TS660_DLL/src/bridge_config.cpp
new file mode 100644
index 0000000..b03a5d5
--- /dev/null
+++ b/TS660_DLL/src/bridge_config.cpp
@@ -0,0 +1,182 @@
+#include "bridge_config.h"
+
+#include
+
+#include
+#include
+#include
+
+namespace ts660b
+{
+ namespace
+ {
+ bool FileExists(const std::wstring& path)
+ {
+ if (path.empty())
+ return false;
+ const DWORD attrs = ::GetFileAttributesW(path.c_str());
+ return attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY) == 0;
+ }
+
+ std::wstring ReadString(const std::wstring& ini, const wchar_t* section, const wchar_t* key, const wchar_t* defaultValue)
+ {
+ wchar_t buffer[512] = {};
+ ::GetPrivateProfileStringW(section, key, defaultValue, buffer, (DWORD)(sizeof(buffer) / sizeof(buffer[0])), ini.c_str());
+ return std::wstring(buffer);
+ }
+
+ int ReadInt(const std::wstring& ini, const wchar_t* section, const wchar_t* key, int defaultValue)
+ {
+ const std::wstring text = ReadString(ini, section, key, L"");
+ if (text.empty())
+ return defaultValue;
+ return (int)::wcstol(text.c_str(), nullptr, 10);
+ }
+
+ bool ReadBool(const std::wstring& ini, const wchar_t* section, const wchar_t* key, bool defaultValue)
+ {
+ const std::wstring text = ReadString(ini, section, key, L"");
+ if (text.empty())
+ return defaultValue;
+ return text != L"0" && text != L"false" && text != L"FALSE" && text != L"False";
+ }
+
+ float ReadFloat(const std::wstring& ini, const wchar_t* section, const wchar_t* key, float defaultValue)
+ {
+ const std::wstring text = ReadString(ini, section, key, L"");
+ if (text.empty())
+ return defaultValue;
+ return (float)::wcstod(text.c_str(), nullptr);
+ }
+
+ // 解析 "B5" / "5" / "b5" 形式的 B 设备通道号
+ bool ParseChannel(const std::wstring& text, int& channel)
+ {
+ const wchar_t* p = text.c_str();
+ while (*p == L' ' || *p == L'\t')
+ ++p;
+ if (*p == L'B' || *p == L'b')
+ ++p;
+ wchar_t* end = nullptr;
+ const long value = std::wcstol(p, &end, 10);
+ if (end == p || value < 1 || value > 7)
+ return false;
+ channel = (int)value;
+ return true;
+ }
+
+ std::wstring DirectoryOf(const std::wstring& filePath)
+ {
+ const size_t pos = filePath.find_last_of(L"\\/");
+ if (pos == std::wstring::npos)
+ return std::wstring();
+ return filePath.substr(0, pos + 1);
+ }
+
+ bool IsAbsolute(const std::wstring& path)
+ {
+ if (path.size() >= 2 && path[1] == L':')
+ return true;
+ return path.size() >= 2 && path[0] == L'\\' && path[1] == L'\\';
+ }
+ }
+
+ bool BridgeConfig::IsMappedChannel(int bChannel) const
+ {
+ for (int a = 1; a <= 4; ++a)
+ {
+ if (map[a] == bChannel)
+ return true;
+ }
+ return false;
+ }
+
+ BridgeConfig BridgeConfig::Load(const std::wstring& iniPath)
+ {
+ BridgeConfig config;
+ if (!FileExists(iniPath))
+ return config;
+
+ // ---- [Bridge] ----
+ config.portOverride = ReadString(iniPath, L"Bridge", L"Port", L"");
+ config.baudRate = ReadInt(iniPath, L"Bridge", L"Baud", config.baudRate);
+ config.readTimeoutMs = ReadInt(iniPath, L"Bridge", L"ReadTimeoutMs", config.readTimeoutMs);
+ config.writeSettleMs = ReadInt(iniPath, L"Bridge", L"WriteSettleMs", config.writeSettleMs);
+ config.verifyReadback = ReadBool(iniPath, L"Bridge", L"VerifyReadback", config.verifyReadback);
+ config.silenceAllChannelsOnOpen = ReadBool(iniPath, L"Bridge", L"SilenceOnOpen", config.silenceAllChannelsOnOpen);
+
+ if (config.baudRate <= 0)
+ config.baudRate = 9600;
+ if (config.readTimeoutMs <= 0)
+ config.readTimeoutMs = 600;
+ if (config.writeSettleMs < 0)
+ config.writeSettleMs = 0;
+
+ // ---- [ChannelMap] ----
+ const wchar_t* mapKeys[4] = { L"A1", L"A2", L"A3", L"A4" };
+ const wchar_t* mapDefaults[4] = { L"B4", L"B5", L"B1", L"B2" };
+ int parsed[5] = { 0, config.map[1], config.map[2], config.map[3], config.map[4] };
+ bool mapOk = true;
+ for (int a = 1; a <= 4; ++a)
+ {
+ const std::wstring text = ReadString(iniPath, L"ChannelMap", mapKeys[a - 1], mapDefaults[a - 1]);
+ int channel = 0;
+ if (!ParseChannel(text, channel))
+ {
+ mapOk = false;
+ break;
+ }
+ parsed[a] = channel;
+ }
+ if (mapOk)
+ {
+ for (int a = 1; a <= 4 && mapOk; ++a)
+ {
+ for (int b = a + 1; b <= 4; ++b)
+ {
+ if (parsed[a] == parsed[b])
+ mapOk = false;
+ }
+ }
+ }
+ if (mapOk)
+ {
+ for (int a = 1; a <= 4; ++a)
+ config.map[a] = parsed[a];
+ }
+
+ // ---- [Trigger] ----
+ for (int mode = 0; mode <= 4; ++mode)
+ {
+ wchar_t keySel[32] = {};
+ wchar_t keyFire[32] = {};
+ std::swprintf(keySel, 32, L"Mode%dTrigSel", mode);
+ std::swprintf(keyFire, 32, L"Mode%dFireMode", mode);
+ int sel = ReadInt(iniPath, L"Trigger", keySel, config.trigSel[mode]);
+ int fire = ReadInt(iniPath, L"Trigger", keyFire, config.fireMode[mode]);
+ if (sel >= 0 && sel <= 2)
+ config.trigSel[mode] = sel;
+ if (fire == 0 || fire == 1)
+ config.fireMode[mode] = fire;
+ }
+
+ // ---- [Output] ----
+ const int onMode = ReadInt(iniPath, L"Output", L"OnMode", config.onMode);
+ const int offMode = ReadInt(iniPath, L"Output", L"OffMode", config.offMode);
+ if (onMode >= 0 && onMode <= 3)
+ config.onMode = onMode;
+ if (offMode >= 0 && offMode <= 3)
+ config.offMode = offMode;
+
+ // ---- [Temperature] ----
+ config.temperatureCelsius = ReadFloat(iniPath, L"Temperature", L"Celsius", config.temperatureCelsius);
+
+ // ---- [Log] ----
+ config.logEnabled = ReadBool(iniPath, L"Log", L"Enable", config.logEnabled);
+ config.logPath = ReadString(iniPath, L"Log", L"File", L"");
+ if (!config.logPath.empty() && !IsAbsolute(config.logPath))
+ config.logPath = DirectoryOf(iniPath) + config.logPath;
+
+ return config;
+ }
+}
diff --git a/TS660_DLL/src/bridge_config.h b/TS660_DLL/src/bridge_config.h
new file mode 100644
index 0000000..e8db0d0
--- /dev/null
+++ b/TS660_DLL/src/bridge_config.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include
+
+namespace ts660b
+{
+ // A 设备(TS660)接口到 B 设备(TDG-7)的桥接配置。
+ // 全部项都有内置默认值;只有同目录存在 TS660_Bridge.ini 时才覆盖。
+ struct BridgeConfig
+ {
+ // ---- 串口 ----
+ std::wstring portOverride; // 非空时忽略 ts660_init 传入的端口号
+ int baudRate = 9600; // ts660_init 传入 0 时使用
+ int readTimeoutMs = 600; // 单条命令等待应答的超时
+ int writeSettleMs = 10; // 写命令后等待仪器处理的固定延时
+
+ // ---- A 通道 -> B 通道 ----
+ // map[A] = B;A1->B4, A2->B5, A3->B1, A4->B2
+ int map[5] = { 0, 4, 5, 1, 2 };
+
+ // ---- A 触发模式(0..4) -> B (TrigSel, FireMode) ----
+ // A: 0=内部触发, 2=软件触发(Aurora 只用这两档)
+ // B: TrigSel 0=内触发 1=外触发上升沿 2=外触发下降沿;FireMode 0=连续 1=单次
+ int trigSel[5] = { 0, 0, 1, 2, 2 };
+ int fireMode[5] = { 0, 0, 1, 0, 1 };
+
+ // ---- 通道输出电平(B 的 Ch{n}Out 取值)----
+ int onMode = 0; // 0=正脉冲
+ int offMode = 3; // 3=常低 GND(关闭输出)
+
+ bool silenceAllChannelsOnOpen = true; // 打开串口时先把 7 个通道全部置为 offMode
+ bool verifyReadback = true; // 写参数后回读校验
+
+ float temperatureCelsius = 25.0f; // B 无温度传感器,读取温度时返回该值
+
+ // ---- 日志 ----
+ bool logEnabled = false;
+ std::wstring logPath; // 为空则使用 DLL 同目录 TS660_Bridge.log
+
+ static BridgeConfig Load(const std::wstring& iniPath);
+
+ // B 通道是否被 A 的 4 个通道占用
+ bool IsMappedChannel(int bChannel) const;
+ };
+}
diff --git a/TS660_DLL/src/exports.cpp b/TS660_DLL/src/exports.cpp
new file mode 100644
index 0000000..0b3a96a
--- /dev/null
+++ b/TS660_DLL/src/exports.cpp
@@ -0,0 +1,169 @@
+// TS660_DLL.dll (B device edition)
+//
+// 对外导出与 A 设备原厂 TS660_DLL.dll 完全相同的 9 个 C 接口,
+// 内部把调用翻译成 B 设备(TDG-7 七通道时序发生器)的串口 ASCII 协议。
+// 上层 SpectroVision 不感知任何差异:只替换 DLL 即可。
+
+#include "bridge.h"
+#include "bridge_config.h"
+#include "log.h"
+#include "win32_link.h"
+
+#include
+
+#include
+#include
+#include
+
+namespace
+{
+ const unsigned kHandleMagic = 0x36363054u; // 'T066'
+
+ struct BridgeHandle
+ {
+ unsigned magic;
+ ts660b::Bridge bridge;
+
+ BridgeHandle(std::unique_ptr link, const ts660b::BridgeConfig& config)
+ : magic(kHandleMagic), bridge(std::move(link), config)
+ {
+ }
+ };
+
+ void ModuleAnchor()
+ {
+ }
+
+ std::wstring ModuleDirectory()
+ {
+ HMODULE module = nullptr;
+ ::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+ reinterpret_cast(&ModuleAnchor),
+ &module);
+
+ wchar_t path[MAX_PATH] = {};
+ if (::GetModuleFileNameW(module, path, MAX_PATH) == 0)
+ return std::wstring();
+
+ std::wstring full(path);
+ const size_t pos = full.find_last_of(L"\\/");
+ if (pos == std::wstring::npos)
+ return std::wstring();
+ return full.substr(0, pos + 1);
+ }
+
+ ts660b::Bridge* Validate(void* pointer)
+ {
+ if (pointer == nullptr)
+ return nullptr;
+ BridgeHandle* handle = static_cast(pointer);
+ if (handle->magic != kHandleMagic)
+ return nullptr;
+ return &handle->bridge;
+ }
+}
+
+extern "C" void* ts660_init(const char* comPort, int baudRate)
+{
+ try
+ {
+ if (comPort == nullptr)
+ return nullptr;
+
+ const std::wstring directory = ModuleDirectory();
+ const ts660b::BridgeConfig config = ts660b::BridgeConfig::Load(directory + L"TS660_Bridge.ini");
+
+ const std::wstring logPath = config.logPath.empty() ? (directory + L"TS660_Bridge.log") : config.logPath;
+ ts660b::Logger::Instance().Configure(config.logEnabled, logPath);
+
+ auto* handle = new BridgeHandle(std::unique_ptr(new ts660b::Win32ByteLink()), config);
+ if (!handle->bridge.Open(comPort, baudRate))
+ {
+ ts660b::Logger::Instance().Write("ts660_init failed: %s", handle->bridge.LastError().c_str());
+ delete handle;
+ return nullptr;
+ }
+ return handle;
+ }
+ catch (...)
+ {
+ return nullptr;
+ }
+}
+
+extern "C" void ts660_close(void* pointer)
+{
+ if (pointer == nullptr)
+ return;
+
+ BridgeHandle* handle = static_cast(pointer);
+ if (handle->magic != kHandleMagic)
+ return;
+
+ handle->magic = 0;
+ delete handle;
+}
+
+extern "C" int ts660_read_temperature(void* pointer, float* outTemperature)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->ReadTemperature(outTemperature);
+}
+
+extern "C" int ts660_set_trigger(void* pointer, int mode)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SetTrigger(mode);
+}
+
+extern "C" int ts660_set_trigger_freq(void* pointer, double frequencyHz)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SetTriggerFrequency(frequencyHz);
+}
+
+extern "C" int ts660_set_output_channel(void* pointer, int channel, int enable)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SetOutputChannel(channel, enable);
+}
+
+extern "C" int ts660_set_delay(void* pointer, int channel, long long delayNs)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SetDelay(channel, delayNs);
+}
+
+extern "C" int ts660_set_global_output(void* pointer, int enable)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SetGlobalOutput(enable);
+}
+
+extern "C" int ts660_software_trigger(void* pointer)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SoftwareTrigger();
+}
+
+extern "C" int ts660_set_pulse_width(void* pointer, int channel, long long widthNs)
+{
+ ts660b::Bridge* bridge = Validate(pointer);
+ if (bridge == nullptr)
+ return -1;
+ return bridge->SetPulseWidth(channel, widthNs);
+}
diff --git a/TS660_DLL/src/link.h b/TS660_DLL/src/link.h
new file mode 100644
index 0000000..cbba6bc
--- /dev/null
+++ b/TS660_DLL/src/link.h
@@ -0,0 +1,24 @@
+#pragma once
+
+namespace ts660b
+{
+ // 字节链路抽象:生产环境是 Win32 串口,测试环境是模拟设备。
+ class IByteLink
+ {
+ public:
+ virtual ~IByteLink() {}
+
+ virtual bool Open(const wchar_t* portName, int baudRate) = 0;
+ virtual void Close() = 0;
+ virtual bool IsOpen() const = 0;
+
+ // 写入全部字节;失败返回 false。
+ virtual bool Write(const char* data, int length) = 0;
+
+ // 读取最多 capacity 字节;返回实际字节数,0 表示本次超时无数据,-1 表示链路错误。
+ virtual int Read(char* buffer, int capacity, int timeoutMs) = 0;
+
+ // 清空收发缓冲区。
+ virtual void Purge() = 0;
+ };
+}
diff --git a/TS660_DLL/src/log.cpp b/TS660_DLL/src/log.cpp
new file mode 100644
index 0000000..a8811de
--- /dev/null
+++ b/TS660_DLL/src/log.cpp
@@ -0,0 +1,78 @@
+#include "log.h"
+
+#include
+#include
+
+namespace ts660b
+{
+ Logger& Logger::Instance()
+ {
+ static Logger instance;
+ return instance;
+ }
+
+ Logger::~Logger()
+ {
+ if (file_ != nullptr)
+ {
+ std::fclose(file_);
+ file_ = nullptr;
+ }
+ }
+
+ void Logger::Configure(bool enabled, const std::wstring& filePath)
+ {
+ std::lock_guard guard(mutex_);
+
+ if (file_ != nullptr)
+ {
+ std::fclose(file_);
+ file_ = nullptr;
+ }
+
+ enabled_ = enabled;
+ if (!enabled_ || filePath.empty())
+ return;
+
+ FILE* fp = nullptr;
+ if (::_wfopen_s(&fp, filePath.c_str(), L"ab") == 0)
+ {
+ file_ = fp;
+ SYSTEMTIME st = {};
+ ::GetLocalTime(&st);
+ char header[128] = {};
+ std::snprintf(header, sizeof(header) - 1,
+ "\r\n===== TS660 bridge log %04d-%02d-%02d %02d:%02d:%02d =====\r\n",
+ st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
+ std::fputs(header, file_);
+ std::fflush(file_);
+ }
+ }
+
+ void Logger::Write(const char* format, ...)
+ {
+ if (!enabled_ || format == nullptr)
+ return;
+
+ char buffer[2048] = {};
+ va_list args;
+ va_start(args, format);
+ std::vsnprintf(buffer, sizeof(buffer) - 1, format, args);
+ va_end(args);
+
+ SYSTEMTIME st = {};
+ ::GetLocalTime(&st);
+
+ char line[2304] = {};
+ std::snprintf(line, sizeof(line) - 1, "[%02d:%02d:%02d.%03d] %s\r\n",
+ st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, buffer);
+
+ std::lock_guard guard(mutex_);
+ if (file_ != nullptr)
+ {
+ std::fputs(line, file_);
+ std::fflush(file_);
+ }
+ ::OutputDebugStringA(line);
+ }
+}
diff --git a/TS660_DLL/src/log.h b/TS660_DLL/src/log.h
new file mode 100644
index 0000000..f296433
--- /dev/null
+++ b/TS660_DLL/src/log.h
@@ -0,0 +1,29 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace ts660b
+{
+ // 极简日志:默认关闭;开启后同时写文件与 OutputDebugString。
+ class Logger
+ {
+ public:
+ static Logger& Instance();
+
+ void Configure(bool enabled, const std::wstring& filePath);
+ void Write(const char* format, ...);
+
+ private:
+ Logger() = default;
+ ~Logger();
+ Logger(const Logger&) = delete;
+ Logger& operator=(const Logger&) = delete;
+
+ std::mutex mutex_;
+ bool enabled_ = false;
+ FILE* file_ = nullptr;
+ };
+}
diff --git a/TS660_DLL/src/tdg7_device.cpp b/TS660_DLL/src/tdg7_device.cpp
new file mode 100644
index 0000000..9f71f97
--- /dev/null
+++ b/TS660_DLL/src/tdg7_device.cpp
@@ -0,0 +1,709 @@
+#include "tdg7_device.h"
+
+#include "log.h"
+
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+namespace ts660b
+{
+ namespace
+ {
+ bool ParseNumber(const std::string& text, size_t& position, double& value)
+ {
+ const size_t start = position;
+ size_t i = position;
+
+ if (i < text.size() && (text[i] == '+' || text[i] == '-'))
+ ++i;
+
+ size_t integerDigits = 0;
+ while (i < text.size() && std::isdigit((unsigned char)text[i]))
+ {
+ ++i;
+ ++integerDigits;
+ }
+
+ size_t fractionDigits = 0;
+ if (i < text.size() && text[i] == '.')
+ {
+ size_t j = i + 1;
+ size_t digits = 0;
+ while (j < text.size() && std::isdigit((unsigned char)text[j]))
+ {
+ ++j;
+ ++digits;
+ }
+ if (digits > 0)
+ {
+ i = j;
+ fractionDigits = digits;
+ }
+ }
+
+ if (integerDigits == 0 && fractionDigits == 0)
+ return false;
+
+ const std::string literal = text.substr(start, i - start);
+ char* end = nullptr;
+ const double parsed = std::strtod(literal.c_str(), &end);
+ if (end == literal.c_str())
+ return false;
+
+ value = parsed;
+ position = i;
+ return true;
+ }
+
+ // 在应答文本里查找 "KEY[ch][:|=]VALUE[unit]"。
+ // 与 Tdg7ChlDriver 的正则等价,容忍前导 '?'、':'、大小写与通道号。
+ bool Extract(const std::string& text, const char* key, double& value, std::string& unit)
+ {
+ const size_t keyLength = std::strlen(key);
+ if (keyLength == 0)
+ return false;
+
+ for (size_t i = 0; i + keyLength <= text.size(); ++i)
+ {
+ if (i > 0 && std::isalpha((unsigned char)text[i - 1]))
+ continue;
+
+ bool matched = true;
+ for (size_t k = 0; k < keyLength; ++k)
+ {
+ if (std::tolower((unsigned char)text[i + k]) != std::tolower((unsigned char)key[k]))
+ {
+ matched = false;
+ break;
+ }
+ }
+ if (!matched)
+ continue;
+
+ size_t j = i + keyLength;
+ while (j < text.size() && (text[j] == ' ' || text[j] == '\t'))
+ ++j;
+
+ // 可选的通道号
+ const size_t digitsStart = j;
+ while (j < text.size() && std::isdigit((unsigned char)text[j]))
+ ++j;
+ if (j > digitsStart)
+ {
+ while (j < text.size() && (text[j] == ' ' || text[j] == '\t'))
+ ++j;
+ }
+
+ if (j >= text.size() || (text[j] != ':' && text[j] != '='))
+ continue;
+ ++j;
+ while (j < text.size() && (text[j] == ' ' || text[j] == '\t'))
+ ++j;
+
+ double parsed = 0;
+ size_t numberEnd = j;
+ if (!ParseNumber(text, numberEnd, parsed))
+ continue;
+ j = numberEnd;
+
+ while (j < text.size() && (text[j] == ' ' || text[j] == '\t'))
+ ++j;
+
+ unit.clear();
+ if (j < text.size() && std::isalpha((unsigned char)text[j]))
+ {
+ const size_t unitStart = j;
+ while (j < text.size() && std::isalpha((unsigned char)text[j]))
+ ++j;
+ unit.assign(text, unitStart, j - unitStart);
+ }
+
+ value = parsed;
+ return true;
+ }
+ return false;
+ }
+
+ double UnitToNanoseconds(double value, const std::string& unit)
+ {
+ std::string lowered;
+ lowered.reserve(unit.size());
+ for (char c : unit)
+ lowered.push_back((char)std::tolower((unsigned char)c));
+
+ if (lowered == "s")
+ return value * 1e9;
+ if (lowered == "ms")
+ return value * 1e6;
+ if (lowered == "us")
+ return value * 1e3;
+ return value; // ns 或缺省
+ }
+
+ const char* UnitSuffix(int timeUnit)
+ {
+ switch (timeUnit)
+ {
+ case 1: return "ms";
+ case 2: return "us";
+ default: return "ns";
+ }
+ }
+
+ double UnitFactor(int timeUnit)
+ {
+ switch (timeUnit)
+ {
+ case 1: return 1e6;
+ case 2: return 1e3;
+ default: return 1.0;
+ }
+ }
+
+ bool ValidChannel(int channel)
+ {
+ return channel >= 1 && channel <= 7;
+ }
+ }
+
+ Tdg7Device::Tdg7Device(std::unique_ptr link)
+ : link_(std::move(link))
+ {
+ }
+
+ Tdg7Device::~Tdg7Device()
+ {
+ Close();
+ }
+
+ bool Tdg7Device::Open(const std::wstring& portName, int baudRate)
+ {
+ if (!link_)
+ {
+ SetError("串口链路未创建");
+ return false;
+ }
+ if (!link_->Open(portName.c_str(), baudRate))
+ {
+ SetError("打开串口失败");
+ return false;
+ }
+ Logger::Instance().Write("OPEN %ls @ %d", portName.c_str(), baudRate);
+ return true;
+ }
+
+ void Tdg7Device::Close()
+ {
+ if (link_ && link_->IsOpen())
+ {
+ link_->Close();
+ Logger::Instance().Write("CLOSE");
+ }
+ }
+
+ bool Tdg7Device::IsOpen() const
+ {
+ return link_ && link_->IsOpen();
+ }
+
+ std::string Tdg7Device::LastError() const
+ {
+ return lastError_;
+ }
+
+ void Tdg7Device::SetError(const std::string& message)
+ {
+ lastError_ = message;
+ Logger::Instance().Write("ERR %s", message.c_str());
+ }
+
+ bool Tdg7Device::Write(const std::string& text)
+ {
+ if (!link_ || !link_->IsOpen())
+ {
+ SetError("串口未打开");
+ return false;
+ }
+
+ Logger::Instance().Write("TX %s", text.c_str());
+ if (!link_->Write(text.data(), (int)text.size()))
+ {
+ SetError("发送失败:" + text);
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::Exchange(const char* key,
+ const std::string& setCommand,
+ const std::string& queryCommand,
+ std::string& response,
+ bool allowNoResponse)
+ {
+ std::lock_guard guard(ioMutex_);
+
+ response.clear();
+ if (!link_ || !link_->IsOpen())
+ {
+ SetError("串口未打开");
+ return false;
+ }
+
+ link_->Purge();
+
+ if (!setCommand.empty())
+ {
+ if (!Write(setCommand))
+ return false;
+ if (settleMs_ > 0)
+ ::Sleep((DWORD)settleMs_);
+ }
+
+ if (queryCommand.empty())
+ return true;
+
+ if (!Write(queryCommand))
+ return false;
+
+ const DWORD start = ::GetTickCount();
+ bool matched = false;
+ char buffer[512] = {};
+ int guardCounter = 0;
+
+ for (;;)
+ {
+ if (++guardCounter > 2000)
+ break;
+
+ if (matched)
+ {
+ // 已解析出数值,再确认没有后续字节(避免把半截数字当成最终值)
+ const int extra = link_->Read(buffer, (int)sizeof(buffer) - 1, 8);
+ if (extra > 0)
+ {
+ response.append(buffer, (size_t)extra);
+ double value = 0;
+ std::string unit;
+ matched = Extract(response, key, value, unit);
+ continue;
+ }
+ break;
+ }
+
+ if ((DWORD)(::GetTickCount() - start) >= (DWORD)timeoutMs_)
+ break;
+
+ const int read = link_->Read(buffer, (int)sizeof(buffer) - 1, 30);
+ if (read > 0)
+ {
+ response.append(buffer, (size_t)read);
+ double value = 0;
+ std::string unit;
+ matched = Extract(response, key, value, unit);
+ }
+ else if (read < 0)
+ {
+ break;
+ }
+ }
+
+ if (matched)
+ {
+ Logger::Instance().Write("RX %s", response.c_str());
+ return true;
+ }
+
+ if (allowNoResponse && response.empty())
+ {
+ Logger::Instance().Write("RX (无应答,按可接受处理)");
+ return true;
+ }
+
+ SetError(std::string("等待应答超时或无法解析:") + queryCommand + ",收到:" + response);
+ return false;
+ }
+
+ bool Tdg7Device::ExtractValue(const std::string& text, const char* key, double& value, std::string& unit) const
+ {
+ return Extract(text, key, value, unit);
+ }
+
+ bool Tdg7Device::SetOutputMode(int hwChannel, int mode)
+ {
+ if (!ValidChannel(hwChannel))
+ {
+ SetError("通道号超出 1..7");
+ return false;
+ }
+ if (mode < 0 || mode > 3)
+ {
+ SetError("输出模式超出 0..3");
+ return false;
+ }
+
+ char command[64] = {};
+ char query[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "Ch%dOut:%d", hwChannel, mode);
+ std::snprintf(query, sizeof(query) - 1, "?Ch%dOut", hwChannel);
+
+ std::string response;
+ if (!Exchange("Out", command, query, response))
+ return false;
+ if (!verify_)
+ return true;
+
+ double value = 0;
+ std::string unit;
+ if (!ExtractValue(response, "Out", value, unit))
+ {
+ SetError("无法解析输出模式应答:" + response);
+ return false;
+ }
+ if ((int)std::llround(value) != mode)
+ {
+ char message[160] = {};
+ std::snprintf(message, sizeof(message) - 1,
+ "设置通道<%d>输出模式失败:期望 %d,回读 %d", hwChannel, mode, (int)std::llround(value));
+ SetError(message);
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::SetGated(int hwChannel, bool enabled)
+ {
+ if (!ValidChannel(hwChannel))
+ {
+ SetError("通道号超出 1..7");
+ return false;
+ }
+
+ const int value = enabled ? 1 : 0;
+ char command[64] = {};
+ char query[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "Ch%dGtd:%d", hwChannel, value);
+ std::snprintf(query, sizeof(query) - 1, "?Ch%dGtd", hwChannel);
+
+ std::string response;
+ if (!Exchange("Gtd", command, query, response))
+ return false;
+ if (!verify_)
+ return true;
+
+ double back = 0;
+ std::string unit;
+ if (!ExtractValue(response, "Gtd", back, unit))
+ {
+ SetError("无法解析门控应答:" + response);
+ return false;
+ }
+ if ((int)std::llround(back) != value)
+ {
+ SetError("设置通道门控失败");
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::SetFrequency(int hwChannel, int hz)
+ {
+ if (!ValidChannel(hwChannel))
+ {
+ SetError("通道号超出 1..7");
+ return false;
+ }
+ if (hz <= 0 || hz > 999999)
+ {
+ SetError("频率必须在 1..999999 Hz");
+ return false;
+ }
+
+ char command[64] = {};
+ char query[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "F%d:%06dHz", hwChannel, hz);
+ std::snprintf(query, sizeof(query) - 1, "?F%d", hwChannel);
+
+ std::string response;
+ if (!Exchange("F", command, query, response))
+ return false;
+ if (!verify_)
+ return true;
+
+ double value = 0;
+ std::string unit;
+ if (!ExtractValue(response, "F", value, unit))
+ {
+ SetError("无法解析频率应答:" + response);
+ return false;
+ }
+ if ((int)std::llround(value) != hz)
+ {
+ char message[160] = {};
+ std::snprintf(message, sizeof(message) - 1,
+ "设置通道<%d>频率失败:期望 %dHz,回读 %dHz", hwChannel, hz, (int)std::llround(value));
+ SetError(message);
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::SetFrequencyDivider(int hwChannel, int divider)
+ {
+ if (!ValidChannel(hwChannel))
+ {
+ SetError("通道号超出 1..7");
+ return false;
+ }
+ if (divider < 0 || divider >= 1000)
+ {
+ SetError("分频需在 0..999");
+ return false;
+ }
+
+ char command[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "Fdiv%d:%04d", hwChannel, divider);
+
+ std::string response;
+ return Exchange(nullptr, command, std::string(), response);
+ }
+
+ bool Tdg7Device::SetPulseWidthNs(int hwChannel, long long widthNs)
+ {
+ if (!ValidChannel(hwChannel))
+ {
+ SetError("通道号超出 1..7");
+ return false;
+ }
+
+ const double ns = (double)widthNs;
+ if (ns < 0.1 || ns >= 1000000000.0)
+ {
+ SetError("脉宽超出 0.1ns..1s");
+ return false;
+ }
+
+ // 自动挑选单位,并按 0.1 的最小刻度量化(与 Tdg7ChlDriver 一致)
+ int timeUnit = 3;
+ double value = ns;
+ if (value / 1000.0 >= 1.0)
+ {
+ timeUnit = 2;
+ value /= 1000.0;
+ if (value / 1000.0 >= 1.0)
+ {
+ timeUnit = 1;
+ value /= 1000.0;
+ }
+ }
+ value = std::floor(value * 10.0 + 1e-9) / 10.0;
+
+ const double expectedNs = value * UnitFactor(timeUnit);
+
+ char command[64] = {};
+ char query[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "W%d:%05.1f%s", hwChannel, value, UnitSuffix(timeUnit));
+ std::snprintf(query, sizeof(query) - 1, "?W%d", hwChannel);
+
+ std::string response;
+ if (!Exchange("W", command, query, response))
+ return false;
+ if (!verify_)
+ return true;
+
+ double back = 0;
+ std::string unit;
+ if (!ExtractValue(response, "W", back, unit))
+ {
+ SetError("无法解析脉宽应答:" + response);
+ return false;
+ }
+ const double backNs = UnitToNanoseconds(back, unit);
+ if (std::fabs(backNs - expectedNs) > 0.05)
+ {
+ char message[200] = {};
+ std::snprintf(message, sizeof(message) - 1,
+ "设置通道<%d>脉宽失败:期望 %.1fns,回读 %.1fns", hwChannel, expectedNs, backNs);
+ SetError(message);
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::SetDelayNs(int hwChannel, long long delayNs)
+ {
+ if (!ValidChannel(hwChannel))
+ {
+ SetError("通道号超出 1..7");
+ return false;
+ }
+ if (delayNs < 0)
+ {
+ SetError("延时不能为负");
+ return false;
+ }
+
+ double value = (double)delayNs;
+ char command[64] = {};
+ char query[64] = {};
+
+ if (hwChannel <= 4)
+ {
+ // Ch1~Ch4:< 1ms,0.25ns 分辨率
+ if (value >= 1000000.0)
+ {
+ SetError("B 设备 Ch1~Ch4 延时必须 < 1ms");
+ return false;
+ }
+ std::snprintf(command, sizeof(command) - 1, "D%d:%09.2fns", hwChannel, value);
+ }
+ else
+ {
+ // Ch5~Ch7:< 10s,100ns 分辨率,命令按 us 下发
+ if (value >= 10000000000.0)
+ {
+ SetError("B 设备 Ch5~Ch7 延时必须 < 10s");
+ return false;
+ }
+ value = std::llround(value / 100.0) * 100.0;
+ std::snprintf(command, sizeof(command) - 1, "D%d:%09.1fus", hwChannel, value / 1000.0);
+ }
+
+ std::snprintf(query, sizeof(query) - 1, "?D%d", hwChannel);
+
+ std::string response;
+ if (!Exchange("D", command, query, response))
+ return false;
+ if (!verify_)
+ return true;
+
+ double back = 0;
+ std::string unit;
+ if (!ExtractValue(response, "D", back, unit))
+ {
+ SetError("无法解析延时应答:" + response);
+ return false;
+ }
+ const double backNs = UnitToNanoseconds(back, unit);
+ if (std::fabs(backNs - value) > 0.05)
+ {
+ char message[200] = {};
+ std::snprintf(message, sizeof(message) - 1,
+ "设置通道<%d>延时失败:期望 %.1fns,回读 %.1fns", hwChannel, value, backNs);
+ SetError(message);
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::SetTrigger(int trigSel, int fireMode)
+ {
+ if (trigSel < 0 || trigSel > 2)
+ {
+ SetError("TrigSel 超出 0..2");
+ return false;
+ }
+ if (fireMode != 0 && fireMode != 1)
+ {
+ SetError("FireMode 超出 0..1");
+ return false;
+ }
+
+ // 与 Tdg7ChlDriver 的联动顺序一致
+ if (fireMode == 0)
+ {
+ if (!SetFireMode(0))
+ return false;
+ return SetTrigSel(trigSel);
+ }
+
+ if (!SetTrigSel(trigSel))
+ return false;
+ return SetFireMode(1);
+ }
+
+ bool Tdg7Device::SetTrigSel(int value)
+ {
+ char command[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "TrigSel:%d", value);
+
+ std::string response;
+ if (!Exchange("TrigSel", command, "?TrigSel", response))
+ return false;
+ if (!verify_)
+ return true;
+
+ double back = 0;
+ std::string unit;
+ if (!ExtractValue(response, "TrigSel", back, unit))
+ {
+ SetError("无法解析触发模式应答:" + response);
+ return false;
+ }
+ if ((int)std::llround(back) != value)
+ {
+ SetError("设置触发模式失败");
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::SetFireMode(int value)
+ {
+ char command[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "FireMode=%d", value);
+
+ std::string response;
+ // 部分固件不回显 FireMode(或只回非数值应答),此时按写入成功处理
+ if (!Exchange("FireMode", command, "?FireMode", response, true))
+ {
+ Logger::Instance().Write("WARN FireMode 无有效应答,按写入成功处理");
+ return true;
+ }
+ if (!verify_)
+ return true;
+ if (response.empty())
+ {
+ Logger::Instance().Write("WARN FireMode 无回读,无法确认单次模式已生效");
+ return true;
+ }
+
+ double back = 0;
+ std::string unit;
+ if (!ExtractValue(response, "FireMode", back, unit))
+ return true; // 有应答但不含可解析值,按可接受处理
+
+ if ((int)std::llround(back) != value)
+ {
+ SetError("设置 FireMode 失败");
+ return false;
+ }
+ return true;
+ }
+
+ bool Tdg7Device::Fire(int count)
+ {
+ if (count <= 0 || count > 9999)
+ {
+ SetError("发射次数必须在 1..9999");
+ return false;
+ }
+
+ char command[64] = {};
+ std::snprintf(command, sizeof(command) - 1, "Fire=%04d", count);
+
+ // 与 Tdg7ChlDriver.Fire 一致:只写不等待,避免给触发增加额外延时
+ std::lock_guard guard(ioMutex_);
+ if (!link_ || !link_->IsOpen())
+ {
+ SetError("串口未打开");
+ return false;
+ }
+ link_->Purge();
+ return Write(command);
+ }
+}
diff --git a/TS660_DLL/src/tdg7_device.h b/TS660_DLL/src/tdg7_device.h
new file mode 100644
index 0000000..0347627
--- /dev/null
+++ b/TS660_DLL/src/tdg7_device.h
@@ -0,0 +1,60 @@
+#pragma once
+
+#include "link.h"
+
+#include
+#include
+#include
+
+namespace ts660b
+{
+ // TDG-7 七通道时序发生器的串口协议实现。
+ // 与 SpectroVision/DllApi/Tdg7ChlDriver.cs 的行为保持一致:
+ // 写命令 -> 等待 10ms -> 查询回读 -> 比对。
+ // 所有事务串行化。
+ class Tdg7Device
+ {
+ public:
+ explicit Tdg7Device(std::unique_ptr link);
+ ~Tdg7Device();
+
+ bool Open(const std::wstring& portName, int baudRate);
+ void Close();
+ bool IsOpen() const;
+
+ void SetTimeoutMs(int value) { timeoutMs_ = value; }
+ void SetSettleMs(int value) { settleMs_ = value; }
+ void SetVerifyReadback(bool value) { verify_ = value; }
+
+ // 以下 hwChannel 均为 B 设备物理通道号 1..7
+ bool SetOutputMode(int hwChannel, int mode); // 0=POS 1=NEG 2=+5V 3=GND
+ bool SetGated(int hwChannel, bool enabled);
+ bool SetFrequency(int hwChannel, int hz);
+ bool SetFrequencyDivider(int hwChannel, int divider); // 协议无回读
+ bool SetPulseWidthNs(int hwChannel, long long widthNs);
+ bool SetDelayNs(int hwChannel, long long delayNs);
+ bool SetTrigger(int trigSel, int fireMode);
+ bool Fire(int count);
+
+ std::string LastError() const;
+
+ private:
+ bool Write(const std::string& text);
+ bool Exchange(const char* key,
+ const std::string& setCommand,
+ const std::string& queryCommand,
+ std::string& response,
+ bool allowNoResponse = false);
+ bool ExtractValue(const std::string& text, const char* key, double& value, std::string& unit) const;
+ bool SetTrigSel(int value);
+ bool SetFireMode(int value);
+ void SetError(const std::string& message);
+
+ std::unique_ptr link_;
+ std::mutex ioMutex_;
+ int timeoutMs_ = 600;
+ int settleMs_ = 10;
+ bool verify_ = true;
+ std::string lastError_;
+ };
+}
diff --git a/TS660_DLL/src/win32_link.cpp b/TS660_DLL/src/win32_link.cpp
new file mode 100644
index 0000000..4326e4e
--- /dev/null
+++ b/TS660_DLL/src/win32_link.cpp
@@ -0,0 +1,158 @@
+#include "win32_link.h"
+
+#include
+
+namespace ts660b
+{
+ namespace
+ {
+ std::wstring NormalizePortName(const wchar_t* portName)
+ {
+ std::wstring s = portName ? portName : L"";
+
+ // 去掉首尾空白和引号
+ size_t begin = 0;
+ while (begin < s.size() && (s[begin] == L' ' || s[begin] == L'\t' || s[begin] == L'"'))
+ ++begin;
+ size_t end = s.size();
+ while (end > begin && (s[end - 1] == L' ' || s[end - 1] == L'\t' || s[end - 1] == L'"'))
+ --end;
+ s = s.substr(begin, end - begin);
+
+ if (s.empty())
+ return s;
+
+ // 已经是 \\.\COMx 形式
+ if (s.size() >= 4 && s[0] == L'\\' && s[1] == L'\\' && s[2] == L'.' && s[3] == L'\\')
+ return s;
+
+ return L"\\\\.\\" + s;
+ }
+ }
+
+ bool Win32ByteLink::Open(const wchar_t* portName, int baudRate)
+ {
+ Close();
+
+ const std::wstring path = NormalizePortName(portName);
+ if (path.empty())
+ return false;
+
+ handle_ = ::CreateFileW(path.c_str(),
+ GENERIC_READ | GENERIC_WRITE,
+ 0,
+ nullptr,
+ OPEN_EXISTING,
+ 0,
+ nullptr);
+ if (handle_ == INVALID_HANDLE_VALUE)
+ return false;
+
+ ::SetupComm(handle_, 4096, 4096);
+
+ DCB dcb = {};
+ dcb.DCBlength = sizeof(DCB);
+ if (!::GetCommState(handle_, &dcb))
+ {
+ Close();
+ return false;
+ }
+
+ dcb.BaudRate = (baudRate > 0) ? (DWORD)baudRate : 9600;
+ dcb.ByteSize = 8;
+ dcb.Parity = NOPARITY;
+ dcb.StopBits = ONESTOPBIT;
+ dcb.fBinary = TRUE;
+ dcb.fParity = FALSE;
+ dcb.fOutxCtsFlow = FALSE;
+ dcb.fOutxDsrFlow = FALSE;
+ dcb.fDsrSensitivity = FALSE;
+ dcb.fDtrControl = DTR_CONTROL_DISABLE;
+ dcb.fRtsControl = RTS_CONTROL_DISABLE;
+ dcb.fOutX = FALSE;
+ dcb.fInX = FALSE;
+ dcb.fErrorChar = FALSE;
+ dcb.fNull = FALSE;
+ dcb.fAbortOnError = FALSE;
+
+ if (!::SetCommState(handle_, &dcb))
+ {
+ Close();
+ return false;
+ }
+
+ COMMTIMEOUTS timeouts = {};
+ timeouts.ReadIntervalTimeout = 20;
+ timeouts.ReadTotalTimeoutMultiplier = 0;
+ timeouts.ReadTotalTimeoutConstant = 50;
+ timeouts.WriteTotalTimeoutMultiplier = 0;
+ timeouts.WriteTotalTimeoutConstant = 500;
+ if (!::SetCommTimeouts(handle_, &timeouts))
+ {
+ Close();
+ return false;
+ }
+
+ Purge();
+ return true;
+ }
+
+ void Win32ByteLink::Close()
+ {
+ if (handle_ != INVALID_HANDLE_VALUE)
+ {
+ ::CloseHandle(handle_);
+ handle_ = INVALID_HANDLE_VALUE;
+ }
+ }
+
+ bool Win32ByteLink::Write(const char* data, int length)
+ {
+ if (handle_ == INVALID_HANDLE_VALUE || data == nullptr || length <= 0)
+ return false;
+
+ int offset = 0;
+ while (offset < length)
+ {
+ DWORD written = 0;
+ if (!::WriteFile(handle_, data + offset, (DWORD)(length - offset), &written, nullptr))
+ return false;
+ if (written == 0)
+ return false;
+ offset += (int)written;
+ }
+ return true;
+ }
+
+ int Win32ByteLink::Read(char* buffer, int capacity, int timeoutMs)
+ {
+ if (handle_ == INVALID_HANDLE_VALUE || buffer == nullptr || capacity <= 0)
+ return -1;
+
+ COMMTIMEOUTS timeouts = {};
+ timeouts.ReadIntervalTimeout = 20;
+ timeouts.ReadTotalTimeoutMultiplier = 0;
+ timeouts.ReadTotalTimeoutConstant = (timeoutMs > 0) ? (DWORD)timeoutMs : 50;
+ ::SetCommTimeouts(handle_, &timeouts);
+
+ DWORD read = 0;
+ if (!::ReadFile(handle_, buffer, (DWORD)capacity, &read, nullptr))
+ {
+ const DWORD error = ::GetLastError();
+ if (error == ERROR_OPERATION_ABORTED)
+ return 0;
+ return -1;
+ }
+ return (int)read;
+ }
+
+ void Win32ByteLink::Purge()
+ {
+ if (handle_ == INVALID_HANDLE_VALUE)
+ return;
+
+ // 只清接收缓冲。清发送缓冲(PURGE_TXCLEAR/PURGE_TXABORT)会把刚写入、
+ // 尚未发送完的命令截断——9600bps 下 9 个字节要 ~9.4ms 才发完。
+ ::PurgeComm(handle_, PURGE_RXCLEAR);
+ }
+}
diff --git a/TS660_DLL/src/win32_link.h b/TS660_DLL/src/win32_link.h
new file mode 100644
index 0000000..da19efb
--- /dev/null
+++ b/TS660_DLL/src/win32_link.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include "link.h"
+
+#include
+
+namespace ts660b
+{
+ // 基于 Win32 通信 API 的串口链路。
+ // 参数与 Tdg7ChlDriver 保持一致:8N1、无流控、DTR/RTS 关闭。
+ class Win32ByteLink : public IByteLink
+ {
+ public:
+ Win32ByteLink() = default;
+ ~Win32ByteLink() override { Close(); }
+
+ bool Open(const wchar_t* portName, int baudRate) override;
+ void Close() override;
+ bool IsOpen() const override { return handle_ != INVALID_HANDLE_VALUE; }
+
+ bool Write(const char* data, int length) override;
+ int Read(char* buffer, int capacity, int timeoutMs) override;
+ void Purge() override;
+
+ private:
+ HANDLE handle_ = INVALID_HANDLE_VALUE;
+ };
+}
diff --git a/build.cmd b/build.cmd
new file mode 100644
index 0000000..dd109c3
--- /dev/null
+++ b/build.cmd
@@ -0,0 +1,29 @@
+@echo off
+setlocal
+set "SLN=%~dp0TS660_DLL.sln"
+set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
+set "MSBUILD="
+
+for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe`) do set "MSBUILD=%%i"
+
+if not defined MSBUILD if exist "%ProgramFiles%\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\MSBuild.exe" set "MSBUILD=%ProgramFiles%\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\MSBuild.exe"
+if not defined MSBUILD if exist "%ProgramFiles%\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe" set "MSBUILD=%ProgramFiles%\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe"
+
+if not defined MSBUILD (
+ echo [ERROR] MSBuild not found. Install Visual Studio with "Desktop development with C++".
+ exit /b 1
+)
+
+echo Using MSBuild: %MSBUILD%
+echo.
+
+"%MSBUILD%" "%SLN%" /m /p:Configuration=Release /p:Platform=x64 /v:minimal
+if errorlevel 1 exit /b 1
+
+"%MSBUILD%" "%SLN%" /m /p:Configuration=Release /p:Platform=x86 /v:minimal
+if errorlevel 1 exit /b 1
+
+echo.
+echo Built:
+echo %~dp0bin\x64\Release\TS660_DLL.dll
+echo %~dp0bin\Win32\Release\TS660_DLL.dll