添加项目文件。
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>17.0</VCProjectVersion>
|
||||
<ProjectGuid>{0A7C3E52-6B1D-4C9A-9E44-1F5B2D8A6C71}</ProjectGuid>
|
||||
<RootNamespace>TS660Bridge</RootNamespace>
|
||||
<ProjectName>TS660_DLL</ProjectName>
|
||||
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<WholeProgramOptimization>false</WholeProgramOptimization>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<WholeProgramOptimization>false</WholeProgramOptimization>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings" />
|
||||
<ImportGroup Label="Shared" />
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<TargetName>TS660_DLL</TargetName>
|
||||
<OutDir>$(ProjectDir)..\bin\$(Platform)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(ProjectDir)..\obj\$(Platform)\$(Configuration)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<SDLCheck>false</SDLCheck>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
||||
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<ModuleDefinitionFile>$(ProjectDir)src\TS660_DLL.def</ModuleDefinitionFile>
|
||||
<AdditionalOptions>/NOIMPLIB /NOEXP %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<SDLCheck>false</SDLCheck>
|
||||
<PreprocessorDefinitions>WIN32;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
||||
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<ModuleDefinitionFile>$(ProjectDir)src\TS660_DLL.def</ModuleDefinitionFile>
|
||||
<AdditionalOptions>/NOIMPLIB /NOEXP %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<SDLCheck>false</SDLCheck>
|
||||
<PreprocessorDefinitions>_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
||||
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<ModuleDefinitionFile>$(ProjectDir)src\TS660_DLL.def</ModuleDefinitionFile>
|
||||
<AdditionalOptions>/NOIMPLIB /NOEXP %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level4</WarningLevel>
|
||||
<SDLCheck>false</SDLCheck>
|
||||
<PreprocessorDefinitions>_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
||||
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<ModuleDefinitionFile>$(ProjectDir)src\TS660_DLL.def</ModuleDefinitionFile>
|
||||
<AdditionalOptions>/NOIMPLIB /NOEXP %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="src\bridge.cpp" />
|
||||
<ClCompile Include="src\bridge_config.cpp" />
|
||||
<ClCompile Include="src\exports.cpp" />
|
||||
<ClCompile Include="src\log.cpp" />
|
||||
<ClCompile Include="src\tdg7_device.cpp" />
|
||||
<ClCompile Include="src\win32_link.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="src\bridge.h" />
|
||||
<ClInclude Include="src\bridge_config.h" />
|
||||
<ClInclude Include="src\link.h" />
|
||||
<ClInclude Include="src\log.h" />
|
||||
<ClInclude Include="src\tdg7_device.h" />
|
||||
<ClInclude Include="src\win32_link.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="src\TS660_DLL.def" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets" />
|
||||
</Project>
|
||||
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="Source Files">
|
||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Header Files">
|
||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||
<Extensions>h;hpp;hxx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Resource Files">
|
||||
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
||||
<Extensions>def;rc</Extensions>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="src\bridge.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\bridge_config.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\exports.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\log.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\tdg7_device.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="src\win32_link.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="src\bridge.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="src\bridge_config.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="src\link.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="src\log.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="src\tdg7_device.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="src\win32_link.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="src\TS660_DLL.def">
|
||||
<Filter>Resource Files</Filter>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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
|
||||
@@ -0,0 +1,257 @@
|
||||
#include "bridge.h"
|
||||
|
||||
#include "log.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
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<IByteLink> 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<std::mutex> 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<std::mutex> 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<std::mutex> guard(mutex_);
|
||||
// B 设备没有温度传感器:返回配置值(默认 25℃)
|
||||
*outCelsius = config_.temperatureCelsius;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Bridge::SetTrigger(int mode)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include "bridge_config.h"
|
||||
#include "tdg7_device.h"
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
namespace ts660b
|
||||
{
|
||||
// A 设备(TS660)语义 -> B 设备(TDG-7)语义的桥。
|
||||
//
|
||||
// 内部保留 A 的 4 个通道状态;B 的其余通道在打开时统一拉到 offMode,
|
||||
// 避免未接线的通道继续输出脉冲。
|
||||
class Bridge
|
||||
{
|
||||
public:
|
||||
Bridge(std::unique_ptr<IByteLink> 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;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
#include "bridge_config.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
@@ -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 <windows.h>
|
||||
|
||||
#include <memory>
|
||||
#include <new>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
const unsigned kHandleMagic = 0x36363054u; // 'T066'
|
||||
|
||||
struct BridgeHandle
|
||||
{
|
||||
unsigned magic;
|
||||
ts660b::Bridge bridge;
|
||||
|
||||
BridgeHandle(std::unique_ptr<ts660b::IByteLink> 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<LPCWSTR>(&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<BridgeHandle*>(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<ts660b::IByteLink>(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<BridgeHandle*>(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);
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "log.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <windows.h>
|
||||
|
||||
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<std::mutex> 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<std::mutex> guard(mutex_);
|
||||
if (file_ != nullptr)
|
||||
{
|
||||
std::fputs(line, file_);
|
||||
std::fflush(file_);
|
||||
}
|
||||
::OutputDebugStringA(line);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,709 @@
|
||||
#include "tdg7_device.h"
|
||||
|
||||
#include "log.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
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<IByteLink> 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<std::mutex> 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<std::mutex> guard(ioMutex_);
|
||||
if (!link_ || !link_->IsOpen())
|
||||
{
|
||||
SetError("串口未打开");
|
||||
return false;
|
||||
}
|
||||
link_->Purge();
|
||||
return Write(command);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include "link.h"
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
namespace ts660b
|
||||
{
|
||||
// TDG-7 七通道时序发生器的串口协议实现。
|
||||
// 与 SpectroVision/DllApi/Tdg7ChlDriver.cs 的行为保持一致:
|
||||
// 写命令 -> 等待 10ms -> 查询回读 -> 比对。
|
||||
// 所有事务串行化。
|
||||
class Tdg7Device
|
||||
{
|
||||
public:
|
||||
explicit Tdg7Device(std::unique_ptr<IByteLink> 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<IByteLink> link_;
|
||||
std::mutex ioMutex_;
|
||||
int timeoutMs_ = 600;
|
||||
int settleMs_ = 10;
|
||||
bool verify_ = true;
|
||||
std::string lastError_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
#include "win32_link.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "link.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user