初始化版本控制:TS660 DLL 源码、构建脚本与 SDK(Release) 产物

This commit is contained in:
roxin
2026-11-21 12:00:13 +08:00
commit e832938129
42 changed files with 4201 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
# 生成目录 / 编译中间产物
/.vs/
/[Rr]elease/
/[Dd]ebug/
/x64/
/x86/
/Debug/
# 编译中间文件
*.obj
*.iobj
*.ipdb
*.pdb
*.ilk
*.exp
*.pch
*.idb
*.tlog
*.recipe
*.lastbuildstate
*.Build.CppClean.log
# 根目录下的零散构建产物
/TS660_Debug.exe
/TS660_Debug.exp
/TS660_Debug.lib
/TS660_UnitTest.exe
/TS660_UnitTest.exp
/TS660_UnitTest.lib
# Visual Studio 用户配置
*.vcxproj.user
*.suo
*.user
*.sln.docstates
+241
View File
@@ -0,0 +1,241 @@
// SerialPort.cpp: 串口通信封装实现
#include "pch.h"
#include "SerialPort.h"
SerialPort::SerialPort()
: m_hCom(INVALID_HANDLE_VALUE)
{
ZeroMemory(&m_readOl, sizeof(m_readOl));
ZeroMemory(&m_writeOl, sizeof(m_writeOl));
}
SerialPort::~SerialPort()
{
Close();
DestroyOverlappedEvents();
}
bool SerialPort::CreateOverlappedEvents()
{
m_readOl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_readOl.hEvent == NULL) {
return false;
}
m_writeOl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (m_writeOl.hEvent == NULL) {
CloseHandle(m_readOl.hEvent);
m_readOl.hEvent = NULL;
return false;
}
return true;
}
void SerialPort::DestroyOverlappedEvents()
{
if (m_readOl.hEvent != NULL) {
CloseHandle(m_readOl.hEvent);
m_readOl.hEvent = NULL;
}
if (m_writeOl.hEvent != NULL) {
CloseHandle(m_writeOl.hEvent);
m_writeOl.hEvent = NULL;
}
}
bool SerialPort::Open(const wchar_t* comPort,
int baudRate,
int dataBits,
StopBits stopBits,
Parity parity)
{
if (IsOpen()) {
Close();
}
if (comPort == nullptr) {
return false;
}
if (!CreateOverlappedEvents()) {
return false;
}
// FILE_FLAG_OVERLAPPED 必须设置,用于异步 I/O
m_hCom = CreateFileW(comPort,
GENERIC_READ | GENERIC_WRITE,
0, // 独占
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (m_hCom == INVALID_HANDLE_VALUE) {
DestroyOverlappedEvents();
return false;
}
// 配置 DCB
DCB dcb = { 0 };
dcb.DCBlength = sizeof(DCB);
if (!GetCommState(m_hCom, &dcb)) {
Close();
return false;
}
dcb.BaudRate = static_cast<DWORD>(baudRate);
dcb.ByteSize = static_cast<BYTE>(dataBits);
switch (parity) {
case Parity::None: dcb.Parity = NOPARITY; break;
case Parity::Odd: dcb.Parity = ODDPARITY; break;
case Parity::Even: dcb.Parity = EVENPARITY; break;
case Parity::Mark: dcb.Parity = MARKPARITY; break;
case Parity::Space: dcb.Parity = SPACEPARITY; break;
default: dcb.Parity = NOPARITY; break;
}
switch (stopBits) {
case StopBits::One: dcb.StopBits = ONESTOPBIT; break;
case StopBits::OnePointFive: dcb.StopBits = ONE5STOPBITS; break;
case StopBits::Two: dcb.StopBits = TWOSTOPBITS; break;
default: dcb.StopBits = ONESTOPBIT; break;
}
// 关闭硬件流控(可按需修改)
dcb.fBinary = TRUE;
dcb.fParity = (parity != Parity::None) ? TRUE : FALSE;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
if (!SetCommState(m_hCom, &dcb)) {
Close();
return false;
}
// 清空缓冲区
PurgeComm(m_hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
// 默认超时: 无超时(由 Read/Write 内部 WaitForSingleObject 控制)
COMMTIMEOUTS to = { 0 };
to.ReadIntervalTimeout = MAXDWORD;
to.ReadTotalTimeoutMultiplier = 0;
to.ReadTotalTimeoutConstant = 0;
to.WriteTotalTimeoutMultiplier = 0;
to.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(m_hCom, &to);
return true;
}
void SerialPort::Close()
{
if (m_hCom != INVALID_HANDLE_VALUE) {
// 取消未完成的异步 I/O
CancelIo(m_hCom);
CloseHandle(m_hCom);
m_hCom = INVALID_HANDLE_VALUE;
}
DestroyOverlappedEvents();
}
bool SerialPort::SetTimeouts(const COMMTIMEOUTS& timeouts)
{
if (!IsOpen()) return false;
COMMTIMEOUTS to = timeouts;
return SetCommTimeouts(m_hCom, &to) != 0;
}
bool SerialPort::SetTimeout(int readTimeoutMs, int writeTimeoutMs)
{
if (!IsOpen()) return false;
COMMTIMEOUTS to = { 0 };
// MAXDWORD 表示无驱动级总间隔限制, ReadFile 立即返回由 overlapped 控制
to.ReadIntervalTimeout = MAXDWORD;
to.ReadTotalTimeoutMultiplier = 0;
to.ReadTotalTimeoutConstant = 0;
to.WriteTotalTimeoutMultiplier = 0;
to.WriteTotalTimeoutConstant = static_cast<DWORD>(writeTimeoutMs);
// 注: readTimeoutMs 由 Read() 中 WaitForSingleObject 的 timeoutMs 控制, 不写入 COMMTIMEOUTS
(void)readTimeoutMs;
return SetCommTimeouts(m_hCom, &to) != 0;
}
int SerialPort::Read(unsigned char* buf, int size, int timeoutMs)
{
if (!IsOpen() || buf == nullptr || size <= 0) return -1;
if (m_readOl.hEvent == NULL) {
if (!CreateOverlappedEvents()) return -1;
}
ResetEvent(m_readOl.hEvent);
m_readOl.Offset = 0;
m_readOl.OffsetHigh = 0;
DWORD bytesRead = 0;
BOOL ok = ReadFile(m_hCom, buf, static_cast<DWORD>(size),
&bytesRead, &m_readOl);
if (!ok) {
DWORD err = GetLastError();
if (err != ERROR_IO_PENDING) {
return -1;
}
// 异步等待
DWORD wait = WaitForSingleObject(m_readOl.hEvent, timeoutMs < 0 ? INFINITE : static_cast<DWORD>(timeoutMs));
if (wait == WAIT_TIMEOUT) {
// 取消未完成的 I/O, 仍可获取已读字节
CancelIo(m_hCom);
GetOverlappedResult(m_hCom, &m_readOl, &bytesRead, FALSE);
return static_cast<int>(bytesRead);
} else if (wait != WAIT_OBJECT_0) {
return -1;
}
if (!GetOverlappedResult(m_hCom, &m_readOl, &bytesRead, FALSE)) {
DWORD e = GetLastError();
if (e == ERROR_HANDLE_EOF || e == ERROR_IO_INCOMPLETE) {
return static_cast<int>(bytesRead);
}
return -1;
}
}
return static_cast<int>(bytesRead);
}
int SerialPort::Write(const unsigned char* buf, int size, int timeoutMs)
{
if (!IsOpen() || buf == nullptr || size <= 0) return -1;
if (m_writeOl.hEvent == NULL) {
if (!CreateOverlappedEvents()) return -1;
}
ResetEvent(m_writeOl.hEvent);
m_writeOl.Offset = 0;
m_writeOl.OffsetHigh = 0;
DWORD bytesWritten = 0;
BOOL ok = WriteFile(m_hCom, buf, static_cast<DWORD>(size),
&bytesWritten, &m_writeOl);
if (!ok) {
DWORD err = GetLastError();
if (err != ERROR_IO_PENDING) {
return -1;
}
DWORD wait = WaitForSingleObject(m_writeOl.hEvent, timeoutMs < 0 ? INFINITE : static_cast<DWORD>(timeoutMs));
if (wait == WAIT_TIMEOUT) {
CancelIo(m_hCom);
GetOverlappedResult(m_hCom, &m_writeOl, &bytesWritten, FALSE);
return static_cast<int>(bytesWritten);
} else if (wait != WAIT_OBJECT_0) {
return -1;
}
if (!GetOverlappedResult(m_hCom, &m_writeOl, &bytesWritten, FALSE)) {
return -1;
}
}
return static_cast<int>(bytesWritten);
}
+74
View File
@@ -0,0 +1,74 @@
// SerialPort.h: 串口通信封装类(异步 Overlapped I/O)
#pragma once
#include <windows.h>
// 导出宏定义
#ifdef TS660_DLL_EXPORTS
#define TS660_DLL_API __declspec(dllexport)
#else
#define TS660_DLL_API __declspec(dllimport)
#endif
// 停止位
enum class StopBits : int {
One = 0, // 1
OnePointFive = 1, // 1.5
Two = 2 // 2
};
// 校验位
enum class Parity : int {
None = 0,
Odd = 1,
Even = 2,
Mark = 3,
Space = 4
};
class TS660_DLL_API SerialPort {
public:
SerialPort();
~SerialPort();
SerialPort(const SerialPort&) = delete;
SerialPort& operator=(const SerialPort&) = delete;
// 打开串口
// comPort: 如 L"COM1"
// 返回 true 成功
bool Open(const wchar_t* comPort,
int baudRate = 9600,
int dataBits = 8,
StopBits stopBits = StopBits::One,
Parity parity = Parity::None);
// 关闭串口
void Close();
// 是否已打开
bool IsOpen() const { return m_hCom != INVALID_HANDLE_VALUE; }
// 直接设置 COMMTIMEOUTS
bool SetTimeouts(const COMMTIMEOUTS& timeouts);
// 简化版: 设置读/写总超时(毫秒)
bool SetTimeout(int readTimeoutMs, int writeTimeoutMs);
// 异步读: 返回读取字节数; 失败/出错返回 -1; 超时返回已读字节数(可能为0)
int Read(unsigned char* buf, int size, int timeoutMs);
// 异步写: 返回写入字节数; 失败返回 -1
int Write(const unsigned char* buf, int size, int timeoutMs);
// 获取底层句柄
HANDLE GetHandle() const { return m_hCom; }
private:
HANDLE m_hCom;
OVERLAPPED m_readOl; // 读 overlapped
OVERLAPPED m_writeOl; // 写 overlapped
bool CreateOverlappedEvents();
void DestroyOverlappedEvents();
};
+151
View File
@@ -0,0 +1,151 @@
// TS660API.cpp: TS660 C 接口实现,桥接到 TS660DDG 类
#include "pch.h"
#include "TS660API.h"
#include "TS660DDG.h"
#include <string>
#include <cwctype>
// ASCII -> wchar_t
static std::wstring AnsiToWide(const char* s)
{
if (s == nullptr) return std::wstring();
int len = MultiByteToWideChar(CP_ACP, 0, s, -1, nullptr, 0);
if (len <= 0) return std::wstring();
std::wstring out(len, L'\0');
MultiByteToWideChar(CP_ACP, 0, s, -1, &out[0], len);
if (out.size() && out.back() == L'\0') out.pop_back();
return out;
}
// 规范化 COM 端口名: COM10+ 必须用 \\.\COMxx 格式, 否则 CreateFileW 失败
// 已带 \\.\ 或 \\?\ 前缀的直接返回, 不重复处理
static std::wstring NormalizeComPort(const std::wstring& port)
{
if (port.size() >= 4 && port.substr(0, 4) == L"\\\\.\\") return port;
if (port.size() >= 4 && port.substr(0, 4) == L"\\\\?\\") return port;
// 大小写不敏感地匹配 "COM" 前缀 + 纯数字后缀
if (port.size() > 3) {
if (std::towupper(port[0]) == L'C' &&
std::towupper(port[1]) == L'O' &&
std::towupper(port[2]) == L'M') {
const std::wstring numStr = port.substr(3);
bool allDigit = !numStr.empty();
for (wchar_t c : numStr) {
if (!std::iswdigit(c)) { allDigit = false; break; }
}
if (allDigit) {
int num = std::stoi(numStr);
if (num > 9) {
return L"\\\\.\\" + port;
}
}
}
}
return port;
}
static TS660DDG* ToPtr(void* h)
{
return static_cast<TS660DDG*>(h);
}
TS660_DLL_API void* ts660_init(const char* com_port, int baud_rate)
{
if (com_port == nullptr) return nullptr;
std::wstring port = NormalizeComPort(AnsiToWide(com_port));
if (port.empty()) return nullptr;
TS660DDG* ddg = new (std::nothrow) TS660DDG();
if (ddg == nullptr) return nullptr;
int baud = (baud_rate > 0) ? baud_rate : 115200;
if (!ddg->Open(port.c_str(), baud)) {
delete ddg;
return nullptr;
}
return ddg;
}
TS660_DLL_API void ts660_close(void* handle)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return;
p->Close();
delete p;
}
TS660_DLL_API int ts660_read_timing_config(void* handle, int channel,
long long* out_delay_ns,
long long* out_width_ns,
int* out_trigger_mode,
double* out_trig_freq_hz)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
TS660TimingConfig cfg = {};
if (!p->ReadTimingConfig(channel, &cfg)) return -2;
if (out_delay_ns) *out_delay_ns = cfg.delayNs;
if (out_width_ns) *out_width_ns = cfg.widthNs;
if (out_trigger_mode) *out_trigger_mode = cfg.triggerMode;
if (out_trig_freq_hz) *out_trig_freq_hz = cfg.trigFreqHz;
return 0;
}
TS660_DLL_API int ts660_read_temperature(void* handle, float* out_temp)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->ReadTemperature(out_temp) ? 0 : -2;
}
TS660_DLL_API int ts660_set_trigger(void* handle, int mode)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SetTrigger(static_cast<TS660TriggerMode>(mode)) ? 0 : -2;
}
TS660_DLL_API int ts660_set_trigger_freq(void* handle, double freq_hz)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SetInternalTriggerFreq(freq_hz) ? 0 : -2;
}
TS660_DLL_API int ts660_set_output_channel(void* handle, int channel, int enable)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SetOutputChannel(channel, enable != 0) ? 0 : -2;
}
TS660_DLL_API int ts660_set_delay(void* handle, int channel, long long delay_ns)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SetDelay(channel, static_cast<int64_t>(delay_ns)) ? 0 : -2;
}
TS660_DLL_API int ts660_set_pulse_width(void* handle, int channel, long long width_ns)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SetPulseWidth(channel, static_cast<int64_t>(width_ns)) ? 0 : -2;
}
TS660_DLL_API int ts660_set_global_output(void* handle, int enable)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SetGlobalOutput(enable != 0) ? 0 : -2;
}
TS660_DLL_API int ts660_software_trigger(void* handle)
{
TS660DDG* p = ToPtr(handle);
if (p == nullptr) return -1;
return p->SoftwareTrigger() ? 0 : -2;
}
+83
View File
@@ -0,0 +1,83 @@
// TS660API.h: 数字延迟发生器 TS660 的 C 接口(extern "C")
// 通过 void* 不透明句柄使用,适合跨语言调用
// 用户只需本头文件 + TS660_DLL.lib,无需 TS660DDG.h/SerialPort.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
#ifdef TS660_DLL_EXPORTS
#define TS660_DLL_API __declspec(dllexport)
#else
#define TS660_DLL_API __declspec(dllimport)
#endif
#else
#define TS660_DLL_API
#endif
// === 初始化 ===
// com_port: ASCII 串口名,如 "COM3" 或 "COM10"(COM10+ 会自动加 \\.\ 前缀)
// baud_rate: 波特率,0 或负数使用默认值 115200
// 返回: 不透明句柄; 失败返回 NULL
TS660_DLL_API void* ts660_init(const char* com_port, int baud_rate);
// 关闭并释放资源
TS660_DLL_API void ts660_close(void* handle);
// === 读取时序配置参数 ===
// channel: 通道号 1~8(四通道卡仅 1~4 有效)
// out_delay_ns, out_width_ns: 输出延时/脉宽(ns)
// out_trigger_mode: 输出触发模式(1=内触发计数器, 2=外触发, 3=软件触发, 4=内触发DDS)
// out_trig_freq_hz: 输出内触发频率(Hz)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_read_timing_config(void* handle, int channel,
long long* out_delay_ns,
long long* out_width_ns,
int* out_trigger_mode,
double* out_trig_freq_hz);
// === 读取温度 ===
// out_temp: 输出温度(摄氏度)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_read_temperature(void* handle, float* out_temp);
// === 触发设置 ===
// mode: 0=内部触发, 1=外部触发, 2=软件触发(API值,内部映射为协议值1/2/3)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_trigger(void* handle, int mode);
// === 内触发频率设置 ===
// freq_hz: 频率(Hz),内部按 周期/4ns 换算为控制字
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_trigger_freq(void* handle, double freq_hz);
// === 输出通道设置 ===
// channel: 通道号 1~8, enable: 1=启用, 0=关闭
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_output_channel(void* handle, int channel, int enable);
// === 延时调节 ===
// channel: 通道号 1~8, delay_ns: 延时(ns,内部按 ns*100 换算为 10ps 控制字)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_delay(void* handle, int channel, long long delay_ns);
// === 脉宽调节 ===
// channel: 通道号 1~8, width_ns: 脉宽(ns,内部按 ns*100 换算为 10ps 控制字)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_pulse_width(void* handle, int channel, long long width_ns);
// === 全局输出设置 ===
// enable: 1=启用所有通道输出, 0=关闭
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_global_output(void* handle, int enable);
// === 软件触发发射 ===
// 注意: 需先调用 ts660_set_trigger(mode=2) 切换到软件触发模式
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_software_trigger(void* handle);
#ifdef __cplusplus
} // extern "C"
#endif
+428
View File
@@ -0,0 +1,428 @@
// TS660DDG.cpp: 数字延迟发生器 TS660 封装实现
//
// 协议帧结构:
// 帧头(2) | 帧长(2) | CMD(1) | OPT(2) | PA*(可变) | 校验和(2) | 帧尾(1)
//
// LEN = DATA + CHK(2) + TAIL(1) = DATA + 3
// DATA = CMD + OPT + PA*
// 校验和 = HEAD + LEN + DATA 所有字节求和取低16位, 小端
// 帧尾 = 0xCC
#include "pch.h"
#include "TS660DDG.h"
#include <cstring>
// ============= 基础构造/析构/Open/Close =============
TS660DDG::TS660DDG() {}
TS660DDG::~TS660DDG() {
Close();
}
bool TS660DDG::Open(const wchar_t* comPort, int baudRate) {
return m_serial.Open(comPort, baudRate, 8, StopBits::One, Parity::None);
}
void TS660DDG::Close() {
m_serial.Close();
}
bool TS660DDG::IsOpen() const {
return m_serial.IsOpen();
}
// ============= 协议工具 =============
// 校验和: 对 buffer[0..length] 所有字节求和, 取低16位
uint16_t TS660DDG::Checksum(const uint8_t* buffer, int length) {
uint32_t sum = 0;
for (int i = 0; i < length; ++i) {
sum += buffer[i];
}
return static_cast<uint16_t>(sum & 0xFFFF);
}
// 组装帧(使用原始 PA 字节)
void TS660DDG::BuildFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
std::vector<uint8_t>& frame) {
int dataLen = 1 + 2 + paLen; // CMD + OPT + PA
int lenField = dataLen + TS660_CHK_SIZE + TS660_TAIL_SIZE; // LEN = DATA + CHK + TAIL
int totalLen = 2 + 2 + dataLen + TS660_CHK_SIZE + TS660_TAIL_SIZE; // HEAD + LEN + DATA + CHK + TAIL
frame.resize(static_cast<size_t>(totalLen));
int pos = 0;
// 帧头
frame[pos++] = TS660_FRAME_HEAD0;
frame[pos++] = TS660_FRAME_HEAD1;
// 帧长 (小端)
frame[pos++] = static_cast<uint8_t>(lenField & 0xFF);
frame[pos++] = static_cast<uint8_t>((lenField >> 8) & 0xFF);
// CMD
frame[pos++] = cmd;
// OPT (小端)
frame[pos++] = static_cast<uint8_t>(opt & 0xFF);
frame[pos++] = static_cast<uint8_t>((opt >> 8) & 0xFF);
// PA* (原始字节, 按顺序)
if (paData != nullptr && paLen > 0) {
std::memcpy(frame.data() + pos, paData, static_cast<size_t>(paLen));
pos += paLen;
}
// 校验和: 从帧头开始到 DATA 结束(即 HEAD+LEN+dataLen 个字节)
int chkDataLen = 2 + 2 + dataLen;
uint16_t chk = Checksum(frame.data(), chkDataLen);
frame[pos++] = static_cast<uint8_t>(chk & 0xFF); // CHK_L
frame[pos++] = static_cast<uint8_t>((chk >> 8) & 0xFF); // CHK_H
// 帧尾
frame[pos++] = TS660_FRAME_TAIL;
}
// 便捷构造: 传入 uint32 参数, 自动打包为 4 字节小端
void TS660DDG::BuildFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
std::vector<uint8_t>& frame) {
std::vector<uint8_t> paBytes;
paBytes.reserve(params.size() * 4);
for (uint32_t v : params) {
paBytes.push_back(static_cast<uint8_t>(v & 0xFF));
paBytes.push_back(static_cast<uint8_t>((v >> 8) & 0xFF));
paBytes.push_back(static_cast<uint8_t>((v >> 16) & 0xFF));
paBytes.push_back(static_cast<uint8_t>((v >> 24) & 0xFF));
}
BuildFrame(cmd, opt, paBytes.data(), static_cast<int>(paBytes.size()), frame);
}
// 解析帧
bool TS660DDG::ParseFrame(const uint8_t* data, int length, TS660Frame& outFrame) {
outFrame.valid = false;
outFrame.cmd = 0;
outFrame.opt = 0;
outFrame.pa.clear();
if (data == nullptr || length < 7) return false; // 最小帧: HEAD+LEN+CMD+OPT+CHK+TAIL
// 检查帧头
if (data[0] != TS660_FRAME_HEAD0 || data[1] != TS660_FRAME_HEAD1) return false;
// 读取帧长(LEN = DATA + CHK + TAIL)
int lenField = static_cast<int>(data[2]) | (static_cast<int>(data[3]) << 8);
// LEN = dataLen + CHK(2) + TAIL(1), 所以 dataLen = lenField - 3
int dataLen = lenField - TS660_CHK_SIZE - TS660_TAIL_SIZE;
if (dataLen < 3) return false; // 至少 CMD(1) + OPT(2)
int expectedLen = 2 + 2 + dataLen + TS660_CHK_SIZE + TS660_TAIL_SIZE;
if (length < expectedLen) return false;
// 检查帧尾
int tailPos = 2 + 2 + dataLen + TS660_CHK_SIZE;
if (data[tailPos] != TS660_FRAME_TAIL) return false;
// 校验和校验: 对 HEAD+LEN+DATA 求和
int chkDataLen = 2 + 2 + dataLen;
uint16_t chkCalc = Checksum(data, chkDataLen);
int chkPos = 2 + 2 + dataLen;
uint16_t chkRecv = static_cast<uint16_t>(data[chkPos]) |
(static_cast<uint16_t>(data[chkPos + 1]) << 8);
if (chkCalc != chkRecv) return false;
// 解析字段
outFrame.cmd = data[4];
outFrame.opt = static_cast<uint16_t>(data[5]) |
(static_cast<uint16_t>(data[6]) << 8);
// PA 字节: DATA 中去掉 CMD(1)+OPT(2) 的剩余部分
int paLen = dataLen - 1 - 2;
if (paLen > 0) {
outFrame.pa.assign(data + 7, data + 7 + paLen);
}
outFrame.valid = true;
return true;
}
// 调试: 打印帧内容(十六进制)
void TS660DDG::DumpFrame(const std::vector<uint8_t>& frame, const char* prefix) {
if (frame.empty()) return;
if (prefix) std::printf("%s: ", prefix);
for (size_t i = 0; i < frame.size(); ++i) {
std::printf("%02X ", frame[i]);
}
std::printf("(%zu bytes)\n", frame.size());
}
// ============= 底层通信 =============
// 发送帧并接收响应(使用原始 PA 字节)
bool TS660DDG::SendFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
TS660Frame* respFrame,
int timeoutMs) {
if (!IsOpen()) return false;
// 构造发送帧
std::vector<uint8_t> frame;
BuildFrame(cmd, opt, paData, paLen, frame);
// 清空输入缓冲
PurgeComm(m_serial.GetHandle(), PURGE_RXCLEAR | PURGE_RXABORT);
// 发送
int n = m_serial.Write(frame.data(), static_cast<int>(frame.size()), timeoutMs);
if (n != static_cast<int>(frame.size())) return false;
// 如果不需要响应
if (respFrame == nullptr) return true;
// 接收响应
return RecvFrame(*respFrame, timeoutMs);
}
// 便捷发送: 传入 uint32 参数
bool TS660DDG::SendFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
TS660Frame* respFrame,
int timeoutMs) {
std::vector<uint8_t> paBytes;
paBytes.reserve(params.size() * 4);
for (uint32_t v : params) {
paBytes.push_back(static_cast<uint8_t>(v & 0xFF));
paBytes.push_back(static_cast<uint8_t>((v >> 8) & 0xFF));
paBytes.push_back(static_cast<uint8_t>((v >> 16) & 0xFF));
paBytes.push_back(static_cast<uint8_t>((v >> 24) & 0xFF));
}
return SendFrame(cmd, opt, paBytes.data(), static_cast<int>(paBytes.size()),
respFrame, timeoutMs);
}
// 接收并解析一帧响应
bool TS660DDG::RecvFrame(TS660Frame& outFrame, int timeoutMs) {
outFrame.valid = false;
// 用 GetTickCount 做总超时控制
// (COMMTIMEOUTS 设为立即返回模式, Read 无数据时返回 0 而非阻塞等待)
DWORD startTick = GetTickCount();
DWORD deadline = startTick + static_cast<DWORD>(timeoutMs);
// 阶段 1: 逐字节读取, 寻找帧头 EB 90
bool head0Found = false;
bool head1Found = false;
uint8_t byte = 0;
while (GetTickCount() < deadline) {
int r = m_serial.Read(&byte, 1, 50);
if (r < 0) return false;
if (r == 0) continue;
if (!head0Found) {
if (byte == TS660_FRAME_HEAD0) head0Found = true;
} else {
if (byte == TS660_FRAME_HEAD1) {
head1Found = true;
break;
}
if (byte != TS660_FRAME_HEAD0) head0Found = false;
}
}
if (!head1Found) return false;
// 阶段 2: 读取 LEN_L, LEN_H
uint8_t lenBytes[2];
int got = 0;
while (got < 2 && GetTickCount() < deadline) {
int r = m_serial.Read(lenBytes + got, 2 - got, 50);
if (r < 0) return false;
if (r > 0) got += r;
}
if (got < 2) return false;
int lenField = static_cast<int>(lenBytes[0]) | (static_cast<int>(lenBytes[1]) << 8);
int dataLen = lenField - TS660_CHK_SIZE - TS660_TAIL_SIZE;
if (dataLen < 3) return false; // 至少 CMD(1) + OPT(2)
int totalLen = 2 + 2 + dataLen + TS660_CHK_SIZE + TS660_TAIL_SIZE;
// 阶段 3: 读取剩余字节
int remain = totalLen - 4; // 已读 HEAD(2) + LEN(2)
std::vector<uint8_t> buffer(static_cast<size_t>(totalLen));
buffer[0] = TS660_FRAME_HEAD0;
buffer[1] = TS660_FRAME_HEAD1;
buffer[2] = lenBytes[0];
buffer[3] = lenBytes[1];
got = 0;
while (got < remain && GetTickCount() < deadline) {
int r = m_serial.Read(buffer.data() + 4 + got, remain - got, 100);
if (r < 0) return false;
if (r > 0) got += r;
}
if (got < remain) return false;
return ParseFrame(buffer.data(), static_cast<int>(buffer.size()), outFrame);
}
// ============= 各功能实现 =============
// 读取温度(使用实际协议: 无PA发送, 4字节浮点接收)
bool TS660DDG::ReadTemperature(float* outTemp) {
if (outTemp == nullptr) return false;
// 发送: 无 PA 参数
TS660Frame resp;
if (!SendFrame(TS660_RD | TS660Cmd::READ_TEMPERATURE, 0x0000, nullptr, 0, &resp)) return false;
if (!resp.valid || resp.pa.size() < 4) return false;
// PA0: 4字节 IEEE754 浮点数
*outTemp = resp.ReadFloat(0);
return true;
}
// 读取时序配置: 发送 CMD=0xC1 无PA, 接收87个uint32参数
// 四通道卡有效字段: PA0~PA7(延时), PA16~PA23(脉宽), PA32(触发设置), PA33(频率计数), PA69(温度)
bool TS660DDG::ReadTimingConfig(int channel, TS660TimingConfig* outCfg) {
if (outCfg == nullptr) return false;
if (channel < 1 || channel > CHANNEL_COUNT) return false;
// 发送: 无 PA
TS660Frame resp;
if (!SendFrame(TS660_RD | TS660Cmd::READ_TIMING, 0x0000, nullptr, 0, &resp)) return false;
// 期望 PA 字节数 = 87 * 4 = 348
const int kExpectedPaSize = 87 * 4;
if (!resp.valid || static_cast<int>(resp.pa.size()) < kExpectedPaSize) return false;
// 按通道号计算偏移(单位: 字节)
// 延时: PA[(ch-1)*2] + PA[(ch-1)*2+1] = 64位控制字, lsb=10ps → ns = ctrlWord / 100
int delayOff = (channel - 1) * 2 * 4;
// 脉宽: PA[16 + (ch-1)*2] + PA[16 + (ch-1)*2+1]
int widthOff = (16 + (channel - 1) * 2) * 4;
// 序列步进: PA[35 + (ch-1)*2] + PA[35 + (ch-1)*2+1]
int seqStepOff = (35 + (channel - 1) * 2) * 4;
// 序列起始: PA[51 + (ch-1)*2] + PA[51 + (ch-1)*2+1]
int seqStartOff = (51 + (channel - 1) * 2) * 4;
uint64_t delayCtrl = resp.ReadU64(delayOff);
uint64_t widthCtrl = resp.ReadU64(widthOff);
// PA32: 触发设置(低16位=电压mV, 字节2=边沿, 字节3=模式)
uint32_t pa32 = resp.ReadU32(32 * 4);
int trigVoltage = static_cast<int>(pa32 & 0xFFFF);
int trigEdge = static_cast<int>((pa32 >> 16) & 0xFF);
int trigMode = static_cast<int>((pa32 >> 24) & 0xFF);
// PA33: 内触发频率计数器值, lsb=4ns → 周期 = count*4ns → 频率 = 1e9 / (count*4)
uint32_t pa33 = resp.ReadU32(33 * 4);
double trigFreqHz = (pa33 > 0) ? (1e9 / (static_cast<double>(pa33) * 4.0)) : 0.0;
// PA34: 高16位=GATE设置, 低16位=通道+全局输出状态
uint32_t pa34 = resp.ReadU32(34 * 4);
int gateMode = static_cast<int>((pa34 >> 16) & 0xFFFF);
int chOutStat = static_cast<int>(pa34 & 0xFF);
int glbOutStat = static_cast<int>((pa34 >> 8) & 0xFF);
// PA69: 板卡温度(浮点)
float temperature = resp.ReadFloat(69 * 4);
// 填充返回结构
outCfg->channel = channel;
outCfg->delayNs = static_cast<int64_t>(delayCtrl / 100);
outCfg->widthNs = static_cast<int64_t>(widthCtrl / 100);
outCfg->triggerMode = trigMode;
outCfg->trigFreqHz = trigFreqHz;
outCfg->triggerEdge = trigEdge;
outCfg->trigVoltageMv = trigVoltage;
outCfg->gateMode = gateMode;
outCfg->channelOutStat = chOutStat;
outCfg->globalOutStat = glbOutStat;
outCfg->seqStep = static_cast<int64_t>(resp.ReadU64(seqStepOff) / 100);
outCfg->seqStart = static_cast<int64_t>(resp.ReadU64(seqStartOff) / 100);
outCfg->temperature = temperature;
return true;
}
// 设置触发模式: OPT=模式值(1=内, 2=外, 3=软件), 无PA
bool TS660DDG::SetTrigger(TS660TriggerMode mode) {
uint16_t opt = TS660Proto::TriggerModeOpt(mode);
TS660Frame resp;
if (!SendFrame(TS660_WR | TS660Cmd::SET_TRIGGER, opt, nullptr, 0, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
// 设置内触发频率: PA0=32位控制字(周期/4ns)
// 例如: 1kHz → 周期=1000000ns → 控制字=250000=0x0003D090
bool TS660DDG::SetInternalTriggerFreq(double freqHz) {
if (freqHz <= 0.0) return false;
// 计算周期(ns)
double periodNs = 1e9 / freqHz;
// 控制字 = 周期 / 4ns (取整)
uint32_t ctrlWord = static_cast<uint32_t>(periodNs / 4.0);
std::vector<uint32_t> params = { ctrlWord };
TS660Frame resp;
if (!SendFrameU32(TS660_WR | TS660Cmd::SET_TRIG_FREQ, 0x0000, params, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
// 使能/禁用通道输出: OPT=(通道<<8)|状态, 无PA
bool TS660DDG::SetOutputChannel(int channel, bool enable) {
if (channel < 1 || channel > CHANNEL_COUNT) return false;
uint16_t opt = TS660Proto::ChannelOpt(channel, enable);
TS660Frame resp;
if (!SendFrame(TS660_WR | TS660Cmd::SET_CHANNEL, opt, nullptr, 0, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
// 设置通道延时: OPT=通道号, PA0=低32位, PA1=高32位(控制字=ns/10ps)
bool TS660DDG::SetDelay(int channel, int64_t delayNs) {
if (channel < 1 || channel > CHANNEL_COUNT) return false;
if (delayNs < 0) return false;
// 控制字 = 延时ns / 10ps = delayNs * 100
uint64_t ctrlWord = static_cast<uint64_t>(delayNs) * 100;
uint32_t pa0 = static_cast<uint32_t>(ctrlWord & 0xFFFFFFFF);
uint32_t pa1 = static_cast<uint32_t>((ctrlWord >> 32) & 0xFFFFFFFF);
std::vector<uint32_t> params = { pa0, pa1 };
TS660Frame resp;
if (!SendFrameU32(TS660_WR | TS660Cmd::SET_DELAY,
static_cast<uint16_t>(channel), params, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
// 设置通道脉宽: OPT=通道号, PA0=低32位, PA1=高32位(控制字=ns/10ps)
bool TS660DDG::SetPulseWidth(int channel, int64_t widthNs) {
if (channel < 1 || channel > CHANNEL_COUNT) return false;
if (widthNs < 0) return false;
// 控制字 = 脉宽ns / 10ps = widthNs * 100
uint64_t ctrlWord = static_cast<uint64_t>(widthNs) * 100;
uint32_t pa0 = static_cast<uint32_t>(ctrlWord & 0xFFFFFFFF);
uint32_t pa1 = static_cast<uint32_t>((ctrlWord >> 32) & 0xFFFFFFFF);
std::vector<uint32_t> params = { pa0, pa1 };
TS660Frame resp;
if (!SendFrameU32(TS660_WR | TS660Cmd::SET_PULSE_WIDTH,
static_cast<uint16_t>(channel), params, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
// 使能/禁用全局输出: OPT=1(使能)/0(除能), 无PA
bool TS660DDG::SetGlobalOutput(bool enable) {
uint16_t opt = enable ? 1u : 0u;
TS660Frame resp;
if (!SendFrame(TS660_WR | TS660Cmd::SET_GLOBAL_OUT, opt, nullptr, 0, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
// 软件触发: 无PA, 无OPT(0x0000)
bool TS660DDG::SoftwareTrigger() {
TS660Frame resp;
if (!SendFrame(TS660_WR | TS660Cmd::SOFTWARE_TRIG, 0x0000, nullptr, 0, &resp)) return false;
return TS660Proto::IsWriteSuccess(resp);
}
+194
View File
@@ -0,0 +1,194 @@
// TS660DDG.h: 数字延迟发生器 TS660 封装类
//
// 协议帧结构:
// 帧头 [2字节] | 帧长 [2字节] | CMD [1字节] | OPT [2字节] | PA* [可变] | 校验和 [2字节] | 帧尾 [1字节]
// EB 90 | Num | | | | 低字节在前 | CC
//
// Num = DATA长度 + CHK(2) + TAIL(1) = DATA + 3
// DATA = CMD(1) + OPT(2) + PA*(可变)
// CMD: bit7=读写标志(0=写, 1=读), bit0-6=命令码
// OPT: 功能字
// PA*: 可变长度参数, 按小端发送
// 校验和: HEAD + LEN + DATA 所有字节求和取低16位, 低字节在前
// 帧尾: 0xCC
//
// 示例(读取温度):
// 发送: EB 90 06 00 93 00 00 14 02 CC (LEN=6, DATA=3, 无PA)
// 接收: EB 90 0A 00 93 01 00 00 C0 EC 41 06 04 CC (LEN=10, DATA=7, PA=4字节浮点温度)
#pragma once
#include "SerialPort.h"
#include <stdint.h>
#include <vector>
#include <string>
#include <cstring>
// ===== 帧常量 =====
constexpr uint8_t TS660_FRAME_HEAD0 = 0xEB;
constexpr uint8_t TS660_FRAME_HEAD1 = 0x90;
constexpr uint8_t TS660_FRAME_TAIL = 0xCC;
constexpr int TS660_CHK_SIZE = 2;
constexpr int TS660_TAIL_SIZE = 1;
// ===== 读写标志 =====
constexpr uint8_t TS660_WR = 0x00; // 写
constexpr uint8_t TS660_RD = 0x80; // 读 (bit7=1)
// ===== 命令码 (bit0-6, 不含bit7读写位) =====
namespace TS660Cmd {
constexpr uint8_t READ_TIMING = 0x41; // 读取时序配置
constexpr uint8_t READ_TEMPERATURE = 0x13; // 读取温度
constexpr uint8_t SET_TRIGGER = 0x01; // 设置触发模式
constexpr uint8_t SET_TRIG_FREQ = 0x05; // 设置内触发频率
constexpr uint8_t SET_CHANNEL = 0x06; // 使能/禁用通道输出
constexpr uint8_t SET_DELAY = 0x08; // 设置通道延时
constexpr uint8_t SET_PULSE_WIDTH = 0x09; // 设置通道脉宽
constexpr uint8_t SET_GLOBAL_OUT = 0x07; // 使能/禁用全局输出
constexpr uint8_t SOFTWARE_TRIG = 0x14; // 软件触发
}
// ===== 触发模式 (API值 0/1/2, 映射到协议值 1/2/3) =====
enum class TS660TriggerMode : int {
Internal = 0, // API=0 → 协议OPT=1
External = 1, // API=1 → 协议OPT=2
Software = 2, // API=2 → 协议OPT=3
};
// ===== 时序配置参数 =====
struct TS660TimingConfig {
int channel; // 通道号 1~8
int64_t delayNs; // 延时(ns, lsb=10ps → ctrlWord/100)
int64_t widthNs; // 脉宽(ns, lsb=10ps → ctrlWord/100)
int triggerMode; // 触发模式: 1=内触发计数器, 2=外触发, 3=软件触发, 4=内触发DDS
double trigFreqHz; // 内触发频率(Hz, 由 PA33 计数器值 lsb=4ns 换算)
int triggerEdge; // 触发边沿: 1=上升沿, 2=下降沿
int trigVoltageMv; // 触发电平电压(mV, 250~3300)
int gateMode; // GATE设置: 1=除能, 2=高电平使能, 3=低电平使能
int channelOutStat; // 通道输出状态: bit0~7 通道1~8, 1输出0不输出
int globalOutStat; // 全局输出状态: 1输出 0不输出
int64_t seqStep; // 通道序列步进
int64_t seqStart; // 通道序列起始
float temperature; // 板卡温度(摄氏度, 来自 PA69)
};
// ===== 响应帧解析结果 =====
struct TS660Frame {
bool valid;
uint8_t cmd; // 命令字(含bit7)
uint16_t opt; // 功能字
std::vector<uint8_t> pa; // PA 原始字节(可变长度)
// 辅助: 从 pa 中按小端读取 uint32
uint32_t ReadU32(int offset) const {
if (offset + 4 > static_cast<int>(pa.size())) return 0;
return pa[offset] | (pa[offset+1] << 8) |
(pa[offset+2] << 16) | (pa[offset+3] << 24);
}
// 辅助: 从 pa 中按小端读取 uint64 (低32位+高32位)
uint64_t ReadU64(int offset) const {
uint32_t lo = ReadU32(offset);
uint32_t hi = ReadU32(offset + 4);
return (static_cast<uint64_t>(hi) << 32) | lo;
}
// 辅助: 从 pa 中按小端读取 IEEE754 浮点
float ReadFloat(int offset) const {
uint32_t raw = ReadU32(offset);
float f;
std::memcpy(&f, &raw, sizeof(f));
return f;
}
};
// ===== 协议值转换 (依赖 TS660Frame, 故定义在此) =====
namespace TS660Proto {
// 触发模式 API值 → 协议值
inline uint16_t TriggerModeOpt(TS660TriggerMode mode) {
switch (mode) {
case TS660TriggerMode::Internal: return 1;
case TS660TriggerMode::External: return 2;
case TS660TriggerMode::Software: return 3;
default: return 1;
}
}
// 通道+状态 → OPT(高字节=通道号, 低字节=状态)
inline uint16_t ChannelOpt(int channel, bool enable) {
return (static_cast<uint16_t>(channel) << 8) | (enable ? 0x01 : 0x00);
}
// 检查写命令响应: OPT低字节=1成功/2失败
inline bool IsWriteSuccess(const TS660Frame& resp) {
return resp.valid && (resp.opt & 0xFF) == 0x01;
}
}
class TS660_DLL_API TS660DDG {
public:
static const int CHANNEL_COUNT = 8;
TS660DDG();
~TS660DDG();
TS660DDG(const TS660DDG&) = delete;
TS660DDG& operator=(const TS660DDG&) = delete;
// === 基础操作 ===
bool Open(const wchar_t* comPort, int baudRate = 115200);
void Close();
bool IsOpen() const;
// === 协议工具 ===
// 构造帧: cmd含bit7读写位, opt为功能字, paData/paLen为原始PA字节
static void BuildFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
std::vector<uint8_t>& frame);
// 便捷构造: 传入 uint32 参数(自动打包为4字节小端)
static void BuildFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
std::vector<uint8_t>& frame);
// 校验和: HEAD + LEN + DATA 所有字节求和取低16位
static uint16_t Checksum(const uint8_t* buffer, int length);
// 解析响应帧
static bool ParseFrame(const uint8_t* data, int length, TS660Frame& outFrame);
// 调试: 打印帧内容(十六进制)
static void DumpFrame(const std::vector<uint8_t>& frame, const char* prefix = nullptr);
// === 设备操作 ===
bool ReadTimingConfig(int channel, TS660TimingConfig* outCfg);
bool ReadTemperature(float* outTemp);
bool SetTrigger(TS660TriggerMode mode);
bool SetInternalTriggerFreq(double freqHz);
bool SetOutputChannel(int channel, bool enable);
bool SetDelay(int channel, int64_t delayNs);
bool SetPulseWidth(int channel, int64_t widthNs);
bool SetGlobalOutput(bool enable);
bool SoftwareTrigger();
// === 底层 ===
bool SendFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
TS660Frame* respFrame = nullptr,
int timeoutMs = 1000);
// 便捷发送: 传入 uint32 参数
bool SendFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
TS660Frame* respFrame = nullptr,
int timeoutMs = 1000);
SerialPort& Port() { return m_serial; }
private:
SerialPort m_serial;
// 接收并解析响应帧
bool RecvFrame(TS660Frame& outFrame, int timeoutMs);
};
+54
View File
@@ -0,0 +1,54 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.34114.132
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TS660_DLL", "TS660_DLL.vcxproj", "{9AD27BF0-EA15-427F-8984-1CB2C92C6215}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TS660_Test", "TS660_Test.vcxproj", "{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}"
ProjectSection(ProjectDependencies) = postProject
{9AD27BF0-EA15-427F-8984-1CB2C92C6215} = {9AD27BF0-EA15-427F-8984-1CB2C92C6215}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TS660_UnitTest", "TS660_UnitTest.vcxproj", "{3A3B3C3D-4E4F-4050-9090-101010101010}"
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
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Debug|x64.ActiveCfg = Debug|x64
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Debug|x64.Build.0 = Debug|x64
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Debug|x86.ActiveCfg = Debug|Win32
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Debug|x86.Build.0 = Debug|Win32
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Release|x64.ActiveCfg = Release|x64
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Release|x64.Build.0 = Release|x64
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Release|x86.ActiveCfg = Release|Win32
{9AD27BF0-EA15-427F-8984-1CB2C92C6215}.Release|x86.Build.0 = Release|Win32
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Debug|x64.ActiveCfg = Debug|x64
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Debug|x64.Build.0 = Debug|x64
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Debug|x86.ActiveCfg = Debug|Win32
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Debug|x86.Build.0 = Debug|Win32
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Release|x64.ActiveCfg = Release|x64
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Release|x64.Build.0 = Release|x64
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Release|x86.ActiveCfg = Release|Win32
{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}.Release|x86.Build.0 = Release|Win32
{3A3B3C3D-4E4F-4050-9090-101010101010}.Debug|x64.ActiveCfg = Debug|x64
{3A3B3C3D-4E4F-4050-9090-101010101010}.Debug|x64.Build.0 = Debug|x64
{3A3B3C3D-4E4F-4050-9090-101010101010}.Debug|x86.ActiveCfg = Debug|Win32
{3A3B3C3D-4E4F-4050-9090-101010101010}.Debug|x86.Build.0 = Debug|Win32
{3A3B3C3D-4E4F-4050-9090-101010101010}.Release|x64.ActiveCfg = Release|x64
{3A3B3C3D-4E4F-4050-9090-101010101010}.Release|x64.Build.0 = Release|x64
{3A3B3C3D-4E4F-4050-9090-101010101010}.Release|x86.ActiveCfg = Release|Win32
{3A3B3C3D-4E4F-4050-9090-101010101010}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8593BFB4-EAA1-46CB-8EAD-BFD89000730C}
EndGlobalSection
EndGlobal
+181
View File
@@ -0,0 +1,181 @@
<?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>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{9ad27bf0-ea15-427f-8984-1cb2c92c6215}</ProjectGuid>
<RootNamespace>TS660_DLL</RootNamespace>
<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>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<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 Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;TS660_DLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;TS660_DLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;TS660_DLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;TS660_DLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="framework.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="SerialPort.h" />
<ClInclude Include="TS660DDG.h" />
<ClInclude Include="TS660API.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="SerialPort.cpp" />
<ClCompile Include="TS660DDG.cpp" />
<ClCompile Include="TS660API.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+51
View File
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="framework.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="pch.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="SerialPort.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="TS660DDG.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="TS660API.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="SerialPort.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="TS660DDG.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="TS660API.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>
+353
View File
@@ -0,0 +1,353 @@
# TS660_DLL API 使用说明
数字延迟发生器 TS660 串口通信动态链接库
## 1. 概述
TS660_DLL 是数字延迟发生器 TS660 的 Windows 串口通信封装库,提供 C 语言接口(`extern "C"`),可通过 C/C++/C#/Python 等语言调用。
主要功能:
- 读取板卡温度
- 读取时序配置参数(延时、脉宽、触发模式、频率等)
- 设置触发模式(内部/外部/软件)
- 设置内触发频率
- 控制通道输出使能
- 调节通道延时和脉宽(10ps 分辨率)
- 控制全局输出
- 软件触发
## 2. 运行环境
- 操作系统: Windows 7/10/11 (x64)
- 通信接口: RS-232 串口(或 USB 转串口)
- 波特率: 115200(设备默认)
- 无额外运行时依赖
## 3. 交付文件清单
```
TS660_DLL_SDK/
├── TS660_DLL.dll 动态链接库(x64, Release)
├── TS660_DLL.lib 导入库(链接时使用)
├── TS660API.h C 接口头文件
├── TS660DDG.h 协议常量与数据结构定义
├── TS660_DLL_API.md 本文档
├── example/
│ └── example.c C 调用示例
├── TS660_Test.exe 硬件测试程序(可选)
└── TS660_UnitTest.exe 单元测试程序(可选)
```
## 4. 快速开始
### 4.1 C/C++ 调用
```c
#include "TS660API.h"
int main() {
/* 1. 打开设备 */
void* handle = ts660_init("COM10", 0); /* 0 = 使用默认波特率 115200 */
if (!handle) {
printf("打开失败\n");
return -1;
}
/* 2. 读取温度 */
float temp;
if (ts660_read_temperature(handle, &temp) == 0) {
printf("温度: %.2f°C\n", temp);
}
/* 3. 设置触发模式为内部触发 */
ts660_set_trigger(handle, 0); /* 0=内部, 1=外部, 2=软件 */
/* 4. 设置内触发频率 1kHz */
ts660_set_trigger_freq(handle, 1000.0);
/* 5. 设置通道1延时 10ns、脉宽 100ns */
ts660_set_delay(handle, 1, 10);
ts660_set_pulse_width(handle, 1, 100);
/* 6. 使能通道1输出 */
ts660_set_output_channel(handle, 1, 1);
/* 7. 使能全局输出 */
ts660_set_global_output(handle, 1);
/* 8. 关闭设备 */
ts660_close(handle);
return 0;
}
```
编译命令(MSVC):
```cmd
cl /I. example.c /link TS660_DLL.lib /OUT:example.exe
```
### 4.2 C# 调用
```csharp
using System;
using System.Runtime.InteropServices;
class TS660 {
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ts660_init(string com_port, int baud_rate);
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void ts660_close(IntPtr handle);
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ts660_read_temperature(IntPtr handle, ref float out_temp);
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ts660_set_delay(IntPtr handle, int channel, long delay_ns);
static void Main() {
IntPtr handle = ts660_init("COM10", 0);
if (handle == IntPtr.Zero) { Console.WriteLine("打开失败"); return; }
float temp = 0;
ts660_read_temperature(handle, ref temp);
Console.WriteLine($"温度: {temp:F2}°C");
ts660_set_delay(handle, 1, 10); // 通道1延时10ns
ts660_set_pulse_width(handle, 1, 100); // 通道1脉宽100ns
ts660_close(handle);
}
}
```
### 4.3 Python 调用
```python
from ctypes import *
dll = CDLL("TS660_DLL.dll")
# 打开设备
handle = dll.ts660_init(b"COM10", 0)
if not handle:
print("打开失败"); exit(-1)
# 读取温度
temp = c_float()
dll.ts660_read_temperature(handle, byref(temp))
print(f"温度: {temp.value:.2f}°C")
# 设置通道1延时10ns、脉宽100ns
dll.ts660_set_delay(handle, 1, 10)
dll.ts660_set_pulse_width(handle, 1, 100)
# 关闭
dll.ts660_close(handle)
```
## 5. 接口函数详解
所有函数返回 `int`: `0` 表示成功,`-1` 表示句柄无效,`-2` 表示通信失败(超时或校验错误)。
### 5.1 ts660_init - 打开设备
```c
void* ts660_init(const char* com_port, int baud_rate);
```
| 参数 | 类型 | 说明 |
|---|---|---|
| com_port | const char* | 串口名,如 `"COM3"`、`"COM10"`。COM10 以上会自动加 `\\.\` 前缀 |
| baud_rate | int | 波特率。传 `0` 或负数使用默认值 115200 |
**返回**: 成功返回不透明句柄(非 NULL),失败返回 NULL。
### 5.2 ts660_close - 关闭设备
```c
void ts660_close(void* handle);
```
关闭串口并释放资源。调用后句柄失效,不可再用。
### 5.3 ts660_read_temperature - 读取温度
```c
int ts660_read_temperature(void* handle, float* out_temp);
```
| 参数 | 说明 |
|---|---|
| out_temp | 输出:板卡温度(摄氏度,IEEE754 浮点) |
### 5.4 ts660_read_timing_config - 读取时序配置
```c
int ts660_read_timing_config(void* handle, int channel,
long long* out_delay_ns, long long* out_width_ns,
int* out_trigger_mode, double* out_trig_freq_hz);
```
| 参数 | 说明 |
|---|---|
| channel | 通道号 1~8(四通道卡仅 1~4 有效) |
| out_delay_ns | 输出:该通道延时(ns) |
| out_width_ns | 输出:该通道脉宽(ns) |
| out_trigger_mode | 输出:触发模式(1=内触发计数器, 2=外触发, 3=软件, 4=内触发DDS) |
| out_trig_freq_hz | 输出:内触发频率(Hz) |
### 5.5 ts660_set_trigger - 设置触发模式
```c
int ts660_set_trigger(void* handle, int mode);
```
| mode 值 | 说明 | 协议 OPT 值 |
|---|---|---|
| 0 | 内部触发 | 1 |
| 1 | 外部触发 | 2 |
| 2 | 软件触发 | 3 |
### 5.6 ts660_set_trigger_freq - 设置内触发频率
```c
int ts660_set_trigger_freq(void* handle, double freq_hz);
```
内部按 `周期(ns) / 4ns` 换算为控制字。例如 1kHz → 周期 1,000,000ns → 控制字 250,000。
### 5.7 ts660_set_output_channel - 通道输出控制
```c
int ts660_set_output_channel(void* handle, int channel, int enable);
```
| 参数 | 说明 |
|---|---|
| channel | 通道号 1~8 |
| enable | 1=使能输出, 0=关闭 |
### 5.8 ts660_set_delay - 设置通道延时
```c
int ts660_set_delay(void* handle, int channel, long long delay_ns);
```
分辨率 10ps。内部按 `delay_ns × 100` 换算为 64 位控制字。
### 5.9 ts660_set_pulse_width - 设置通道脉宽
```c
int ts660_set_pulse_width(void* handle, int channel, long long width_ns);
```
分辨率 10ps。内部按 `width_ns × 100` 换算为 64 位控制字。
### 5.10 ts660_set_global_output - 全局输出控制
```c
int ts660_set_global_output(void* handle, int enable);
```
`enable=1` 使能所有通道输出,`enable=0` 关闭。
### 5.11 ts660_software_trigger - 软件触发
```c
int ts660_software_trigger(void* handle);
```
**注意**: 需先调用 `ts660_set_trigger(mode=2)` 切换到软件触发模式,否则设备返回操作失败。
## 6. 错误码
| 返回值 | 含义 |
|---|---|
| 0 | 成功 |
| -1 | 句柄无效(未初始化或已关闭) |
| -2 | 通信失败(超时、校验错误、设备无响应) |
## 7. 通信协议
### 7.1 帧结构
```
┌──────────┬──────────┬─────┬─────┬─────┬──────────┬──────┐
│ 帧头 │ 帧长 │ CMD │ OPT │ PA* │ 校验和 │ 帧尾 │
│ 2 字节 │ 2 字节 │1字节│2字节│可变 │ 2 字节 │1字节 │
│ EB 90 │ Num │ │ │ │ 低字节在前│ CC │
└──────────┴──────────┴─────┴─────┴─────┴──────────┴──────┘
```
- **Num** = CMD(1) + OPT(2) + PA 字节数 + CHK(2) + TAIL(1)
- **CMD**: bit7=读写(0=写, 1=读), bit0-6=命令码
- **OPT**: 功能字,2 字节小端
- **PA***: 参数,可变长度,小端
- **校验和**: 帧头到校验和前所有字节求和取低16位,小端
- **帧尾**: 0xCC
- 两字节间发送间隔不得超过 10ms
### 7.2 命令码表
| 命令 | CMD 码 | 读写 | OPT | PA | 说明 |
|---|---|---|---|---|---|
| READ_TEMP | 0x13 | 读(0x93) | 无效 | 无 | 读取温度 |
| READ_TIMING | 0x41 | 读(0xC1) | 无效 | 无 | 读取全部时序配置 |
| SET_TRIGGER | 0x01 | 写 | 触发模式(1/2/3) | 无 | 设置触发模式 |
| SET_TRIG_FREQ | 0x05 | 写 | 0x0000 | 4字节控制字 | 设置内触发频率 |
| SET_CHANNEL | 0x06 | 写 | (ch<<8)\|en | 无 | 通道输出控制 |
| SET_DELAY | 0x08 | 写 | 通道号 | 8字节控制字 | 设置延时 |
| SET_PULSE_WIDTH | 0x09 | 写 | 通道号 | 8字节控制字 | 设置脉宽 |
| SET_GLOBAL_OUT | 0x07 | 写 | 1/0 | 无 | 全局输出控制 |
| SOFTWARE_TRIG | 0x14 | 写 | 0x0000 | 无 | 软件触发 |
### 7.3 READ_TIMING 响应参数
响应帧 DATA = 351 字节 = CMD(1) + OPT(2) + 87 个 uint32 参数(PA0~PA86)
| PA 编号 | 说明 |
|---|---|
| PA0~PA15 | 通道1~8 延时(低32位+高32位,64位控制字,÷100→ns) |
| PA16~PA31 | 通道1~8 脉宽(低32位+高32位) |
| PA32 | 触发设置(字节3)、触发边沿(字节2)、触发电平mV(低16位) |
| PA33 | 内触发频率计数器值(lsb=4ns) |
| PA34 | GATE设置(高16位)、通道输出状态(bit0~7)、全局输出(bit8~15) |
| PA35~PA50 | 通道1~8 序列步进(64位控制字) |
| PA51~PA66 | 通道1~8 序列起始(64位控制字) |
| PA67 | 序列使能控制 |
| PA69 | 板卡温度(32位浮点) |
| PA70~PA86 | 其他参数(极性、自检、阻抗、DDS、分频等) |
四通道卡中 PA8~PA15、PA24~PA31、PA43~PA50、PA59~PA66 对应通道5~8 的参数无效。
## 8. 典型工作流程
```
1. ts660_init() 打开设备
2. ts660_read_temperature() 读取温度(可选,检查设备状态)
3. ts660_set_trigger(0) 设置为内部触发模式
4. ts660_set_trigger_freq() 设置内触发频率
5. ts660_set_delay() 设置各通道延时
6. ts660_set_pulse_width() 设置各通道脉宽
7. ts660_set_output_channel() 使能需要输出的通道
8. ts660_set_global_output(1) 开启全局输出
9. (可选) 切换软件触发模式后 ts660_software_trigger()
10. ts660_close() 关闭设备
```
## 9. 注意事项
1. **波特率**: 设备默认 115200,不是 9600。`baud_rate` 传 0 使用默认值。
2. **COM10+ 端口**: 传 `"COM10"` 即可,DLL 自动加 `\\.\` 前缀。
3. **软件触发**: 调用 `ts660_software_trigger()` 前必须先用 `ts660_set_trigger(2)` 切换到软件触发模式,否则设备返回失败。
4. **延时/脉宽分辨率**: 内部按 10ps 控制(`ns × 100`)。设置 10ns 实际控制字为 1000。
5. **多线程**: 句柄非线程安全,多线程访问需外部加锁。
6. **超时**: 默认通信超时 1000ms,设备无响应时函数返回 -2。
7. **DLL 部署**: 运行时需将 `TS660_DLL.dll` 放在可执行文件同目录或系统路径中。
## 10. 版本历史
| 版本 | 日期 | 说明 |
|---|---|---|
| 1.0 | 2026-08 | 初版,完整协议实现 |
+83
View File
@@ -0,0 +1,83 @@
// TS660API.h: 数字延迟发生器 TS660 的 C 接口(extern "C")
// 通过 void* 不透明句柄使用,适合跨语言调用
// 用户只需本头文件 + TS660_DLL.lib,无需 TS660DDG.h/SerialPort.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
#ifdef TS660_DLL_EXPORTS
#define TS660_DLL_API __declspec(dllexport)
#else
#define TS660_DLL_API __declspec(dllimport)
#endif
#else
#define TS660_DLL_API
#endif
// === 初始化 ===
// com_port: ASCII 串口名,如 "COM3" 或 "COM10"(COM10+ 会自动加 \\.\ 前缀)
// baud_rate: 波特率,0 或负数使用默认值 115200
// 返回: 不透明句柄; 失败返回 NULL
TS660_DLL_API void* ts660_init(const char* com_port, int baud_rate);
// 关闭并释放资源
TS660_DLL_API void ts660_close(void* handle);
// === 读取时序配置参数 ===
// channel: 通道号 1~8(四通道卡仅 1~4 有效)
// out_delay_ns, out_width_ns: 输出延时/脉宽(ns)
// out_trigger_mode: 输出触发模式(1=内触发计数器, 2=外触发, 3=软件触发, 4=内触发DDS)
// out_trig_freq_hz: 输出内触发频率(Hz)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_read_timing_config(void* handle, int channel,
long long* out_delay_ns,
long long* out_width_ns,
int* out_trigger_mode,
double* out_trig_freq_hz);
// === 读取温度 ===
// out_temp: 输出温度(摄氏度)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_read_temperature(void* handle, float* out_temp);
// === 触发设置 ===
// mode: 0=内部触发, 1=外部触发, 2=软件触发(API值,内部映射为协议值1/2/3)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_trigger(void* handle, int mode);
// === 内触发频率设置 ===
// freq_hz: 频率(Hz),内部按 周期/4ns 换算为控制字
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_trigger_freq(void* handle, double freq_hz);
// === 输出通道设置 ===
// channel: 通道号 1~8, enable: 1=启用, 0=关闭
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_output_channel(void* handle, int channel, int enable);
// === 延时调节 ===
// channel: 通道号 1~8, delay_ns: 延时(ns,内部按 ns*100 换算为 10ps 控制字)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_delay(void* handle, int channel, long long delay_ns);
// === 脉宽调节 ===
// channel: 通道号 1~8, width_ns: 脉宽(ns,内部按 ns*100 换算为 10ps 控制字)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_pulse_width(void* handle, int channel, long long width_ns);
// === 全局输出设置 ===
// enable: 1=启用所有通道输出, 0=关闭
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_global_output(void* handle, int enable);
// === 软件触发发射 ===
// 注意: 需先调用 ts660_set_trigger(mode=2) 切换到软件触发模式
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_software_trigger(void* handle);
#ifdef __cplusplus
} // extern "C"
#endif
+194
View File
@@ -0,0 +1,194 @@
// TS660DDG.h: 数字延迟发生器 TS660 封装类
//
// 协议帧结构:
// 帧头 [2字节] | 帧长 [2字节] | CMD [1字节] | OPT [2字节] | PA* [可变] | 校验和 [2字节] | 帧尾 [1字节]
// EB 90 | Num | | | | 低字节在前 | CC
//
// Num = DATA长度 + CHK(2) + TAIL(1) = DATA + 3
// DATA = CMD(1) + OPT(2) + PA*(可变)
// CMD: bit7=读写标志(0=写, 1=读), bit0-6=命令码
// OPT: 功能字
// PA*: 可变长度参数, 按小端发送
// 校验和: HEAD + LEN + DATA 所有字节求和取低16位, 低字节在前
// 帧尾: 0xCC
//
// 示例(读取温度):
// 发送: EB 90 06 00 93 00 00 14 02 CC (LEN=6, DATA=3, 无PA)
// 接收: EB 90 0A 00 93 01 00 00 C0 EC 41 06 04 CC (LEN=10, DATA=7, PA=4字节浮点温度)
#pragma once
#include "SerialPort.h"
#include <stdint.h>
#include <vector>
#include <string>
#include <cstring>
// ===== 帧常量 =====
constexpr uint8_t TS660_FRAME_HEAD0 = 0xEB;
constexpr uint8_t TS660_FRAME_HEAD1 = 0x90;
constexpr uint8_t TS660_FRAME_TAIL = 0xCC;
constexpr int TS660_CHK_SIZE = 2;
constexpr int TS660_TAIL_SIZE = 1;
// ===== 读写标志 =====
constexpr uint8_t TS660_WR = 0x00; // 写
constexpr uint8_t TS660_RD = 0x80; // 读 (bit7=1)
// ===== 命令码 (bit0-6, 不含bit7读写位) =====
namespace TS660Cmd {
constexpr uint8_t READ_TIMING = 0x41; // 读取时序配置
constexpr uint8_t READ_TEMPERATURE = 0x13; // 读取温度
constexpr uint8_t SET_TRIGGER = 0x01; // 设置触发模式
constexpr uint8_t SET_TRIG_FREQ = 0x05; // 设置内触发频率
constexpr uint8_t SET_CHANNEL = 0x06; // 使能/禁用通道输出
constexpr uint8_t SET_DELAY = 0x08; // 设置通道延时
constexpr uint8_t SET_PULSE_WIDTH = 0x09; // 设置通道脉宽
constexpr uint8_t SET_GLOBAL_OUT = 0x07; // 使能/禁用全局输出
constexpr uint8_t SOFTWARE_TRIG = 0x14; // 软件触发
}
// ===== 触发模式 (API值 0/1/2, 映射到协议值 1/2/3) =====
enum class TS660TriggerMode : int {
Internal = 0, // API=0 → 协议OPT=1
External = 1, // API=1 → 协议OPT=2
Software = 2, // API=2 → 协议OPT=3
};
// ===== 时序配置参数 =====
struct TS660TimingConfig {
int channel; // 通道号 1~8
int64_t delayNs; // 延时(ns, lsb=10ps → ctrlWord/100)
int64_t widthNs; // 脉宽(ns, lsb=10ps → ctrlWord/100)
int triggerMode; // 触发模式: 1=内触发计数器, 2=外触发, 3=软件触发, 4=内触发DDS
double trigFreqHz; // 内触发频率(Hz, 由 PA33 计数器值 lsb=4ns 换算)
int triggerEdge; // 触发边沿: 1=上升沿, 2=下降沿
int trigVoltageMv; // 触发电平电压(mV, 250~3300)
int gateMode; // GATE设置: 1=除能, 2=高电平使能, 3=低电平使能
int channelOutStat; // 通道输出状态: bit0~7 通道1~8, 1输出0不输出
int globalOutStat; // 全局输出状态: 1输出 0不输出
int64_t seqStep; // 通道序列步进
int64_t seqStart; // 通道序列起始
float temperature; // 板卡温度(摄氏度, 来自 PA69)
};
// ===== 响应帧解析结果 =====
struct TS660Frame {
bool valid;
uint8_t cmd; // 命令字(含bit7)
uint16_t opt; // 功能字
std::vector<uint8_t> pa; // PA 原始字节(可变长度)
// 辅助: 从 pa 中按小端读取 uint32
uint32_t ReadU32(int offset) const {
if (offset + 4 > static_cast<int>(pa.size())) return 0;
return pa[offset] | (pa[offset+1] << 8) |
(pa[offset+2] << 16) | (pa[offset+3] << 24);
}
// 辅助: 从 pa 中按小端读取 uint64 (低32位+高32位)
uint64_t ReadU64(int offset) const {
uint32_t lo = ReadU32(offset);
uint32_t hi = ReadU32(offset + 4);
return (static_cast<uint64_t>(hi) << 32) | lo;
}
// 辅助: 从 pa 中按小端读取 IEEE754 浮点
float ReadFloat(int offset) const {
uint32_t raw = ReadU32(offset);
float f;
std::memcpy(&f, &raw, sizeof(f));
return f;
}
};
// ===== 协议值转换 (依赖 TS660Frame, 故定义在此) =====
namespace TS660Proto {
// 触发模式 API值 → 协议值
inline uint16_t TriggerModeOpt(TS660TriggerMode mode) {
switch (mode) {
case TS660TriggerMode::Internal: return 1;
case TS660TriggerMode::External: return 2;
case TS660TriggerMode::Software: return 3;
default: return 1;
}
}
// 通道+状态 → OPT(高字节=通道号, 低字节=状态)
inline uint16_t ChannelOpt(int channel, bool enable) {
return (static_cast<uint16_t>(channel) << 8) | (enable ? 0x01 : 0x00);
}
// 检查写命令响应: OPT低字节=1成功/2失败
inline bool IsWriteSuccess(const TS660Frame& resp) {
return resp.valid && (resp.opt & 0xFF) == 0x01;
}
}
class TS660_DLL_API TS660DDG {
public:
static const int CHANNEL_COUNT = 8;
TS660DDG();
~TS660DDG();
TS660DDG(const TS660DDG&) = delete;
TS660DDG& operator=(const TS660DDG&) = delete;
// === 基础操作 ===
bool Open(const wchar_t* comPort, int baudRate = 115200);
void Close();
bool IsOpen() const;
// === 协议工具 ===
// 构造帧: cmd含bit7读写位, opt为功能字, paData/paLen为原始PA字节
static void BuildFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
std::vector<uint8_t>& frame);
// 便捷构造: 传入 uint32 参数(自动打包为4字节小端)
static void BuildFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
std::vector<uint8_t>& frame);
// 校验和: HEAD + LEN + DATA 所有字节求和取低16位
static uint16_t Checksum(const uint8_t* buffer, int length);
// 解析响应帧
static bool ParseFrame(const uint8_t* data, int length, TS660Frame& outFrame);
// 调试: 打印帧内容(十六进制)
static void DumpFrame(const std::vector<uint8_t>& frame, const char* prefix = nullptr);
// === 设备操作 ===
bool ReadTimingConfig(int channel, TS660TimingConfig* outCfg);
bool ReadTemperature(float* outTemp);
bool SetTrigger(TS660TriggerMode mode);
bool SetInternalTriggerFreq(double freqHz);
bool SetOutputChannel(int channel, bool enable);
bool SetDelay(int channel, int64_t delayNs);
bool SetPulseWidth(int channel, int64_t widthNs);
bool SetGlobalOutput(bool enable);
bool SoftwareTrigger();
// === 底层 ===
bool SendFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
TS660Frame* respFrame = nullptr,
int timeoutMs = 1000);
// 便捷发送: 传入 uint32 参数
bool SendFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
TS660Frame* respFrame = nullptr,
int timeoutMs = 1000);
SerialPort& Port() { return m_serial; }
private:
SerialPort m_serial;
// 接收并解析响应帧
bool RecvFrame(TS660Frame& outFrame, int timeoutMs);
};
Binary file not shown.
Binary file not shown.
+353
View File
@@ -0,0 +1,353 @@
# TS660_DLL API 使用说明
数字延迟发生器 TS660 串口通信动态链接库
## 1. 概述
TS660_DLL 是数字延迟发生器 TS660 的 Windows 串口通信封装库,提供 C 语言接口(`extern "C"`),可通过 C/C++/C#/Python 等语言调用。
主要功能:
- 读取板卡温度
- 读取时序配置参数(延时、脉宽、触发模式、频率等)
- 设置触发模式(内部/外部/软件)
- 设置内触发频率
- 控制通道输出使能
- 调节通道延时和脉宽(10ps 分辨率)
- 控制全局输出
- 软件触发
## 2. 运行环境
- 操作系统: Windows 7/10/11 (x64)
- 通信接口: RS-232 串口(或 USB 转串口)
- 波特率: 115200(设备默认)
- 无额外运行时依赖
## 3. 交付文件清单
```
TS660_DLL_SDK/
├── TS660_DLL.dll 动态链接库(x64, Release)
├── TS660_DLL.lib 导入库(链接时使用)
├── TS660API.h C 接口头文件
├── TS660DDG.h 协议常量与数据结构定义
├── TS660_DLL_API.md 本文档
├── example/
│ └── example.c C 调用示例
├── TS660_Test.exe 硬件测试程序(可选)
└── TS660_UnitTest.exe 单元测试程序(可选)
```
## 4. 快速开始
### 4.1 C/C++ 调用
```c
#include "TS660API.h"
int main() {
/* 1. 打开设备 */
void* handle = ts660_init("COM10", 0); /* 0 = 使用默认波特率 115200 */
if (!handle) {
printf("打开失败\n");
return -1;
}
/* 2. 读取温度 */
float temp;
if (ts660_read_temperature(handle, &temp) == 0) {
printf("温度: %.2f°C\n", temp);
}
/* 3. 设置触发模式为内部触发 */
ts660_set_trigger(handle, 0); /* 0=内部, 1=外部, 2=软件 */
/* 4. 设置内触发频率 1kHz */
ts660_set_trigger_freq(handle, 1000.0);
/* 5. 设置通道1延时 10ns、脉宽 100ns */
ts660_set_delay(handle, 1, 10);
ts660_set_pulse_width(handle, 1, 100);
/* 6. 使能通道1输出 */
ts660_set_output_channel(handle, 1, 1);
/* 7. 使能全局输出 */
ts660_set_global_output(handle, 1);
/* 8. 关闭设备 */
ts660_close(handle);
return 0;
}
```
编译命令(MSVC):
```cmd
cl /I. example.c /link TS660_DLL.lib /OUT:example.exe
```
### 4.2 C# 调用
```csharp
using System;
using System.Runtime.InteropServices;
class TS660 {
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ts660_init(string com_port, int baud_rate);
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void ts660_close(IntPtr handle);
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ts660_read_temperature(IntPtr handle, ref float out_temp);
[DllImport("TS660_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int ts660_set_delay(IntPtr handle, int channel, long delay_ns);
static void Main() {
IntPtr handle = ts660_init("COM10", 0);
if (handle == IntPtr.Zero) { Console.WriteLine("打开失败"); return; }
float temp = 0;
ts660_read_temperature(handle, ref temp);
Console.WriteLine($"温度: {temp:F2}°C");
ts660_set_delay(handle, 1, 10); // 通道1延时10ns
ts660_set_pulse_width(handle, 1, 100); // 通道1脉宽100ns
ts660_close(handle);
}
}
```
### 4.3 Python 调用
```python
from ctypes import *
dll = CDLL("TS660_DLL.dll")
# 打开设备
handle = dll.ts660_init(b"COM10", 0)
if not handle:
print("打开失败"); exit(-1)
# 读取温度
temp = c_float()
dll.ts660_read_temperature(handle, byref(temp))
print(f"温度: {temp.value:.2f}°C")
# 设置通道1延时10ns、脉宽100ns
dll.ts660_set_delay(handle, 1, 10)
dll.ts660_set_pulse_width(handle, 1, 100)
# 关闭
dll.ts660_close(handle)
```
## 5. 接口函数详解
所有函数返回 `int`: `0` 表示成功,`-1` 表示句柄无效,`-2` 表示通信失败(超时或校验错误)。
### 5.1 ts660_init - 打开设备
```c
void* ts660_init(const char* com_port, int baud_rate);
```
| 参数 | 类型 | 说明 |
|---|---|---|
| com_port | const char* | 串口名,如 `"COM3"`、`"COM10"`。COM10 以上会自动加 `\\.\` 前缀 |
| baud_rate | int | 波特率。传 `0` 或负数使用默认值 115200 |
**返回**: 成功返回不透明句柄(非 NULL),失败返回 NULL。
### 5.2 ts660_close - 关闭设备
```c
void ts660_close(void* handle);
```
关闭串口并释放资源。调用后句柄失效,不可再用。
### 5.3 ts660_read_temperature - 读取温度
```c
int ts660_read_temperature(void* handle, float* out_temp);
```
| 参数 | 说明 |
|---|---|
| out_temp | 输出:板卡温度(摄氏度,IEEE754 浮点) |
### 5.4 ts660_read_timing_config - 读取时序配置
```c
int ts660_read_timing_config(void* handle, int channel,
long long* out_delay_ns, long long* out_width_ns,
int* out_trigger_mode, double* out_trig_freq_hz);
```
| 参数 | 说明 |
|---|---|
| channel | 通道号 1~8(四通道卡仅 1~4 有效) |
| out_delay_ns | 输出:该通道延时(ns) |
| out_width_ns | 输出:该通道脉宽(ns) |
| out_trigger_mode | 输出:触发模式(1=内触发计数器, 2=外触发, 3=软件, 4=内触发DDS) |
| out_trig_freq_hz | 输出:内触发频率(Hz) |
### 5.5 ts660_set_trigger - 设置触发模式
```c
int ts660_set_trigger(void* handle, int mode);
```
| mode 值 | 说明 | 协议 OPT 值 |
|---|---|---|
| 0 | 内部触发 | 1 |
| 1 | 外部触发 | 2 |
| 2 | 软件触发 | 3 |
### 5.6 ts660_set_trigger_freq - 设置内触发频率
```c
int ts660_set_trigger_freq(void* handle, double freq_hz);
```
内部按 `周期(ns) / 4ns` 换算为控制字。例如 1kHz → 周期 1,000,000ns → 控制字 250,000。
### 5.7 ts660_set_output_channel - 通道输出控制
```c
int ts660_set_output_channel(void* handle, int channel, int enable);
```
| 参数 | 说明 |
|---|---|
| channel | 通道号 1~8 |
| enable | 1=使能输出, 0=关闭 |
### 5.8 ts660_set_delay - 设置通道延时
```c
int ts660_set_delay(void* handle, int channel, long long delay_ns);
```
分辨率 10ps。内部按 `delay_ns × 100` 换算为 64 位控制字。
### 5.9 ts660_set_pulse_width - 设置通道脉宽
```c
int ts660_set_pulse_width(void* handle, int channel, long long width_ns);
```
分辨率 10ps。内部按 `width_ns × 100` 换算为 64 位控制字。
### 5.10 ts660_set_global_output - 全局输出控制
```c
int ts660_set_global_output(void* handle, int enable);
```
`enable=1` 使能所有通道输出,`enable=0` 关闭。
### 5.11 ts660_software_trigger - 软件触发
```c
int ts660_software_trigger(void* handle);
```
**注意**: 需先调用 `ts660_set_trigger(mode=2)` 切换到软件触发模式,否则设备返回操作失败。
## 6. 错误码
| 返回值 | 含义 |
|---|---|
| 0 | 成功 |
| -1 | 句柄无效(未初始化或已关闭) |
| -2 | 通信失败(超时、校验错误、设备无响应) |
## 7. 通信协议
### 7.1 帧结构
```
┌──────────┬──────────┬─────┬─────┬─────┬──────────┬──────┐
│ 帧头 │ 帧长 │ CMD │ OPT │ PA* │ 校验和 │ 帧尾 │
│ 2 字节 │ 2 字节 │1字节│2字节│可变 │ 2 字节 │1字节 │
│ EB 90 │ Num │ │ │ │ 低字节在前│ CC │
└──────────┴──────────┴─────┴─────┴─────┴──────────┴──────┘
```
- **Num** = CMD(1) + OPT(2) + PA 字节数 + CHK(2) + TAIL(1)
- **CMD**: bit7=读写(0=写, 1=读), bit0-6=命令码
- **OPT**: 功能字,2 字节小端
- **PA***: 参数,可变长度,小端
- **校验和**: 帧头到校验和前所有字节求和取低16位,小端
- **帧尾**: 0xCC
- 两字节间发送间隔不得超过 10ms
### 7.2 命令码表
| 命令 | CMD 码 | 读写 | OPT | PA | 说明 |
|---|---|---|---|---|---|
| READ_TEMP | 0x13 | 读(0x93) | 无效 | 无 | 读取温度 |
| READ_TIMING | 0x41 | 读(0xC1) | 无效 | 无 | 读取全部时序配置 |
| SET_TRIGGER | 0x01 | 写 | 触发模式(1/2/3) | 无 | 设置触发模式 |
| SET_TRIG_FREQ | 0x05 | 写 | 0x0000 | 4字节控制字 | 设置内触发频率 |
| SET_CHANNEL | 0x06 | 写 | (ch<<8)\|en | 无 | 通道输出控制 |
| SET_DELAY | 0x08 | 写 | 通道号 | 8字节控制字 | 设置延时 |
| SET_PULSE_WIDTH | 0x09 | 写 | 通道号 | 8字节控制字 | 设置脉宽 |
| SET_GLOBAL_OUT | 0x07 | 写 | 1/0 | 无 | 全局输出控制 |
| SOFTWARE_TRIG | 0x14 | 写 | 0x0000 | 无 | 软件触发 |
### 7.3 READ_TIMING 响应参数
响应帧 DATA = 351 字节 = CMD(1) + OPT(2) + 87 个 uint32 参数(PA0~PA86)
| PA 编号 | 说明 |
|---|---|
| PA0~PA15 | 通道1~8 延时(低32位+高32位,64位控制字,÷100→ns) |
| PA16~PA31 | 通道1~8 脉宽(低32位+高32位) |
| PA32 | 触发设置(字节3)、触发边沿(字节2)、触发电平mV(低16位) |
| PA33 | 内触发频率计数器值(lsb=4ns) |
| PA34 | GATE设置(高16位)、通道输出状态(bit0~7)、全局输出(bit8~15) |
| PA35~PA50 | 通道1~8 序列步进(64位控制字) |
| PA51~PA66 | 通道1~8 序列起始(64位控制字) |
| PA67 | 序列使能控制 |
| PA69 | 板卡温度(32位浮点) |
| PA70~PA86 | 其他参数(极性、自检、阻抗、DDS、分频等) |
四通道卡中 PA8~PA15、PA24~PA31、PA43~PA50、PA59~PA66 对应通道5~8 的参数无效。
## 8. 典型工作流程
```
1. ts660_init() 打开设备
2. ts660_read_temperature() 读取温度(可选,检查设备状态)
3. ts660_set_trigger(0) 设置为内部触发模式
4. ts660_set_trigger_freq() 设置内触发频率
5. ts660_set_delay() 设置各通道延时
6. ts660_set_pulse_width() 设置各通道脉宽
7. ts660_set_output_channel() 使能需要输出的通道
8. ts660_set_global_output(1) 开启全局输出
9. (可选) 切换软件触发模式后 ts660_software_trigger()
10. ts660_close() 关闭设备
```
## 9. 注意事项
1. **波特率**: 设备默认 115200,不是 9600。`baud_rate` 传 0 使用默认值。
2. **COM10+ 端口**: 传 `"COM10"` 即可,DLL 自动加 `\\.\` 前缀。
3. **软件触发**: 调用 `ts660_software_trigger()` 前必须先用 `ts660_set_trigger(2)` 切换到软件触发模式,否则设备返回失败。
4. **延时/脉宽分辨率**: 内部按 10ps 控制(`ns × 100`)。设置 10ns 实际控制字为 1000。
5. **多线程**: 句柄非线程安全,多线程访问需外部加锁。
6. **超时**: 默认通信超时 1000ms,设备无响应时函数返回 -2。
7. **DLL 部署**: 运行时需将 `TS660_DLL.dll` 放在可执行文件同目录或系统路径中。
## 10. 版本历史
| 版本 | 日期 | 说明 |
|---|---|---|
| 1.0 | 2026-08 | 初版,完整协议实现 |
Binary file not shown.
Binary file not shown.
+51
View File
@@ -0,0 +1,51 @@
/* example.c: TS660_DLL 调用示例
*
* 编译: cl /I. example.c /link TS660_DLL.lib /OUT:example.exe
* 运行: example.exe COM10
*/
#include "TS660API.h"
#include <stdio.h>
int main(int argc, char** argv) {
const char* port = (argc >= 2) ? argv[1] : "COM3";
printf("=== TS660 Example ===\nPort: %s\n\n", port);
/* 1. 打开设备 */
void* h = ts660_init(port, 0); /* 0 = 默认波特率 115200 */
if (!h) { printf("[FAIL] 打开失败\n"); return -1; }
printf("[OK] 设备已打开\n");
/* 2. 读取温度 */
float temp = 0;
if (ts660_read_temperature(h, &temp) == 0)
printf("温度: %.2f C\n", temp);
else
printf("[FAIL] 读取温度失败\n");
/* 3. 读取时序配置(通道1) */
long long delay_ns = 0, width_ns = 0;
int trig_mode = 0;
double trig_freq = 0;
if (ts660_read_timing_config(h, 1, &delay_ns, &width_ns, &trig_mode, &trig_freq) == 0) {
printf("通道1: 延时=%lldns, 脉宽=%lldns\n", delay_ns, width_ns);
printf("触发模式=%d, 频率=%.1fHz\n", trig_mode, trig_freq);
}
/* 4. 配置: 内触发 1kHz, 通道1延时10ns/脉宽100ns */
ts660_set_trigger(h, 0); /* 内部触发 */
ts660_set_trigger_freq(h, 1000.0); /* 1kHz */
ts660_set_delay(h, 1, 10); /* 通道1延时10ns */
ts660_set_pulse_width(h, 1, 100); /* 通道1脉宽100ns */
ts660_set_output_channel(h, 1, 1); /* 使能通道1 */
ts660_set_global_output(h, 1); /* 开启全局输出 */
printf("[OK] 配置完成\n");
/* 5. (可选) 软件触发 */
/* ts660_set_trigger(h, 2); */ /* 先切到软件触发模式 */
/* ts660_software_trigger(h); */
/* 6. 关闭 */
ts660_close(h);
printf("[OK] 设备已关闭\n");
return 0;
}
Binary file not shown.
Binary file not shown.
+83
View File
@@ -0,0 +1,83 @@
// TS660API.h: 数字延迟发生器 TS660 的 C 接口(extern "C")
// 通过 void* 不透明句柄使用,适合跨语言调用
// 用户只需本头文件 + TS660_DLL.lib,无需 TS660DDG.h/SerialPort.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
#ifdef TS660_DLL_EXPORTS
#define TS660_DLL_API __declspec(dllexport)
#else
#define TS660_DLL_API __declspec(dllimport)
#endif
#else
#define TS660_DLL_API
#endif
// === 初始化 ===
// com_port: ASCII 串口名,如 "COM3" 或 "COM10"(COM10+ 会自动加 \\.\ 前缀)
// baud_rate: 波特率,0 或负数使用默认值 115200
// 返回: 不透明句柄; 失败返回 NULL
TS660_DLL_API void* ts660_init(const char* com_port, int baud_rate);
// 关闭并释放资源
TS660_DLL_API void ts660_close(void* handle);
// === 读取时序配置参数 ===
// channel: 通道号 1~8(四通道卡仅 1~4 有效)
// out_delay_ns, out_width_ns: 输出延时/脉宽(ns)
// out_trigger_mode: 输出触发模式(1=内触发计数器, 2=外触发, 3=软件触发, 4=内触发DDS)
// out_trig_freq_hz: 输出内触发频率(Hz)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_read_timing_config(void* handle, int channel,
long long* out_delay_ns,
long long* out_width_ns,
int* out_trigger_mode,
double* out_trig_freq_hz);
// === 读取温度 ===
// out_temp: 输出温度(摄氏度)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_read_temperature(void* handle, float* out_temp);
// === 触发设置 ===
// mode: 0=内部触发, 1=外部触发, 2=软件触发(API值,内部映射为协议值1/2/3)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_trigger(void* handle, int mode);
// === 内触发频率设置 ===
// freq_hz: 频率(Hz),内部按 周期/4ns 换算为控制字
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_trigger_freq(void* handle, double freq_hz);
// === 输出通道设置 ===
// channel: 通道号 1~8, enable: 1=启用, 0=关闭
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_output_channel(void* handle, int channel, int enable);
// === 延时调节 ===
// channel: 通道号 1~8, delay_ns: 延时(ns,内部按 ns*100 换算为 10ps 控制字)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_delay(void* handle, int channel, long long delay_ns);
// === 脉宽调节 ===
// channel: 通道号 1~8, width_ns: 脉宽(ns,内部按 ns*100 换算为 10ps 控制字)
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_pulse_width(void* handle, int channel, long long width_ns);
// === 全局输出设置 ===
// enable: 1=启用所有通道输出, 0=关闭
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_set_global_output(void* handle, int enable);
// === 软件触发发射 ===
// 注意: 需先调用 ts660_set_trigger(mode=2) 切换到软件触发模式
// 返回: 0 成功, 非0 失败
TS660_DLL_API int ts660_software_trigger(void* handle);
#ifdef __cplusplus
} // extern "C"
#endif
+194
View File
@@ -0,0 +1,194 @@
// TS660DDG.h: 数字延迟发生器 TS660 封装类
//
// 协议帧结构:
// 帧头 [2字节] | 帧长 [2字节] | CMD [1字节] | OPT [2字节] | PA* [可变] | 校验和 [2字节] | 帧尾 [1字节]
// EB 90 | Num | | | | 低字节在前 | CC
//
// Num = DATA长度 + CHK(2) + TAIL(1) = DATA + 3
// DATA = CMD(1) + OPT(2) + PA*(可变)
// CMD: bit7=读写标志(0=写, 1=读), bit0-6=命令码
// OPT: 功能字
// PA*: 可变长度参数, 按小端发送
// 校验和: HEAD + LEN + DATA 所有字节求和取低16位, 低字节在前
// 帧尾: 0xCC
//
// 示例(读取温度):
// 发送: EB 90 06 00 93 00 00 14 02 CC (LEN=6, DATA=3, 无PA)
// 接收: EB 90 0A 00 93 01 00 00 C0 EC 41 06 04 CC (LEN=10, DATA=7, PA=4字节浮点温度)
#pragma once
#include "SerialPort.h"
#include <stdint.h>
#include <vector>
#include <string>
#include <cstring>
// ===== 帧常量 =====
constexpr uint8_t TS660_FRAME_HEAD0 = 0xEB;
constexpr uint8_t TS660_FRAME_HEAD1 = 0x90;
constexpr uint8_t TS660_FRAME_TAIL = 0xCC;
constexpr int TS660_CHK_SIZE = 2;
constexpr int TS660_TAIL_SIZE = 1;
// ===== 读写标志 =====
constexpr uint8_t TS660_WR = 0x00; // 写
constexpr uint8_t TS660_RD = 0x80; // 读 (bit7=1)
// ===== 命令码 (bit0-6, 不含bit7读写位) =====
namespace TS660Cmd {
constexpr uint8_t READ_TIMING = 0x41; // 读取时序配置
constexpr uint8_t READ_TEMPERATURE = 0x13; // 读取温度
constexpr uint8_t SET_TRIGGER = 0x01; // 设置触发模式
constexpr uint8_t SET_TRIG_FREQ = 0x05; // 设置内触发频率
constexpr uint8_t SET_CHANNEL = 0x06; // 使能/禁用通道输出
constexpr uint8_t SET_DELAY = 0x08; // 设置通道延时
constexpr uint8_t SET_PULSE_WIDTH = 0x09; // 设置通道脉宽
constexpr uint8_t SET_GLOBAL_OUT = 0x07; // 使能/禁用全局输出
constexpr uint8_t SOFTWARE_TRIG = 0x14; // 软件触发
}
// ===== 触发模式 (API值 0/1/2, 映射到协议值 1/2/3) =====
enum class TS660TriggerMode : int {
Internal = 0, // API=0 → 协议OPT=1
External = 1, // API=1 → 协议OPT=2
Software = 2, // API=2 → 协议OPT=3
};
// ===== 时序配置参数 =====
struct TS660TimingConfig {
int channel; // 通道号 1~8
int64_t delayNs; // 延时(ns, lsb=10ps → ctrlWord/100)
int64_t widthNs; // 脉宽(ns, lsb=10ps → ctrlWord/100)
int triggerMode; // 触发模式: 1=内触发计数器, 2=外触发, 3=软件触发, 4=内触发DDS
double trigFreqHz; // 内触发频率(Hz, 由 PA33 计数器值 lsb=4ns 换算)
int triggerEdge; // 触发边沿: 1=上升沿, 2=下降沿
int trigVoltageMv; // 触发电平电压(mV, 250~3300)
int gateMode; // GATE设置: 1=除能, 2=高电平使能, 3=低电平使能
int channelOutStat; // 通道输出状态: bit0~7 通道1~8, 1输出0不输出
int globalOutStat; // 全局输出状态: 1输出 0不输出
int64_t seqStep; // 通道序列步进
int64_t seqStart; // 通道序列起始
float temperature; // 板卡温度(摄氏度, 来自 PA69)
};
// ===== 响应帧解析结果 =====
struct TS660Frame {
bool valid;
uint8_t cmd; // 命令字(含bit7)
uint16_t opt; // 功能字
std::vector<uint8_t> pa; // PA 原始字节(可变长度)
// 辅助: 从 pa 中按小端读取 uint32
uint32_t ReadU32(int offset) const {
if (offset + 4 > static_cast<int>(pa.size())) return 0;
return pa[offset] | (pa[offset+1] << 8) |
(pa[offset+2] << 16) | (pa[offset+3] << 24);
}
// 辅助: 从 pa 中按小端读取 uint64 (低32位+高32位)
uint64_t ReadU64(int offset) const {
uint32_t lo = ReadU32(offset);
uint32_t hi = ReadU32(offset + 4);
return (static_cast<uint64_t>(hi) << 32) | lo;
}
// 辅助: 从 pa 中按小端读取 IEEE754 浮点
float ReadFloat(int offset) const {
uint32_t raw = ReadU32(offset);
float f;
std::memcpy(&f, &raw, sizeof(f));
return f;
}
};
// ===== 协议值转换 (依赖 TS660Frame, 故定义在此) =====
namespace TS660Proto {
// 触发模式 API值 → 协议值
inline uint16_t TriggerModeOpt(TS660TriggerMode mode) {
switch (mode) {
case TS660TriggerMode::Internal: return 1;
case TS660TriggerMode::External: return 2;
case TS660TriggerMode::Software: return 3;
default: return 1;
}
}
// 通道+状态 → OPT(高字节=通道号, 低字节=状态)
inline uint16_t ChannelOpt(int channel, bool enable) {
return (static_cast<uint16_t>(channel) << 8) | (enable ? 0x01 : 0x00);
}
// 检查写命令响应: OPT低字节=1成功/2失败
inline bool IsWriteSuccess(const TS660Frame& resp) {
return resp.valid && (resp.opt & 0xFF) == 0x01;
}
}
class TS660_DLL_API TS660DDG {
public:
static const int CHANNEL_COUNT = 8;
TS660DDG();
~TS660DDG();
TS660DDG(const TS660DDG&) = delete;
TS660DDG& operator=(const TS660DDG&) = delete;
// === 基础操作 ===
bool Open(const wchar_t* comPort, int baudRate = 115200);
void Close();
bool IsOpen() const;
// === 协议工具 ===
// 构造帧: cmd含bit7读写位, opt为功能字, paData/paLen为原始PA字节
static void BuildFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
std::vector<uint8_t>& frame);
// 便捷构造: 传入 uint32 参数(自动打包为4字节小端)
static void BuildFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
std::vector<uint8_t>& frame);
// 校验和: HEAD + LEN + DATA 所有字节求和取低16位
static uint16_t Checksum(const uint8_t* buffer, int length);
// 解析响应帧
static bool ParseFrame(const uint8_t* data, int length, TS660Frame& outFrame);
// 调试: 打印帧内容(十六进制)
static void DumpFrame(const std::vector<uint8_t>& frame, const char* prefix = nullptr);
// === 设备操作 ===
bool ReadTimingConfig(int channel, TS660TimingConfig* outCfg);
bool ReadTemperature(float* outTemp);
bool SetTrigger(TS660TriggerMode mode);
bool SetInternalTriggerFreq(double freqHz);
bool SetOutputChannel(int channel, bool enable);
bool SetDelay(int channel, int64_t delayNs);
bool SetPulseWidth(int channel, int64_t widthNs);
bool SetGlobalOutput(bool enable);
bool SoftwareTrigger();
// === 底层 ===
bool SendFrame(uint8_t cmd, uint16_t opt,
const uint8_t* paData, int paLen,
TS660Frame* respFrame = nullptr,
int timeoutMs = 1000);
// 便捷发送: 传入 uint32 参数
bool SendFrameU32(uint8_t cmd, uint16_t opt,
const std::vector<uint32_t>& params,
TS660Frame* respFrame = nullptr,
int timeoutMs = 1000);
SerialPort& Port() { return m_serial; }
private:
SerialPort m_serial;
// 接收并解析响应帧
bool RecvFrame(TS660Frame& outFrame, int timeoutMs);
};
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+131
View File
@@ -0,0 +1,131 @@
// TS660_Debug.cpp: 串口通信调试程序 - 发送命令并显示原始响应字节
#include "pch.h"
#include "SerialPort.h"
#include "TS660DDG.h"
#include <cstdio>
#include <vector>
#include <string>
#include <windows.h>
static std::wstring A2W(const std::string& s) {
if (s.empty()) return std::wstring();
int n = MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, nullptr, 0);
std::wstring w(n ? n - 1 : 0, L'\0');
if (n) MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, w.data(), n);
return w;
}
static std::wstring NormalizeCom(const std::wstring& port) {
if (port.size() >= 4 && port.substr(0, 4) == L"\\\\.\\") return port;
if (port.size() >= 3) {
std::wstring prefix = port.substr(0, 3);
for (auto& c : prefix) c = static_cast<wchar_t>(towupper(c));
if (prefix == L"COM") {
std::wstring numStr = port.substr(3);
if (!numStr.empty()) {
bool allDigit = true;
for (auto c : numStr) if (!isdigit(c)) { allDigit = false; break; }
if (allDigit) {
int n = std::stoi(numStr);
if (n > 9) return L"\\\\.\\" + port;
}
}
}
}
return port;
}
static void DumpHex(const unsigned char* data, int len, const char* tag) {
std::printf("%s [%d bytes]: ", tag, len);
for (int i = 0; i < len; ++i) {
std::printf("%02X ", data[i]);
if ((i & 15) == 15) std::printf("\n ");
}
std::printf("\n");
}
int main(int argc, char** argv) {
std::string portName = (argc >= 2) ? argv[1] : "COM10";
int baudRate = (argc >= 3) ? std::atoi(argv[2]) : 9600;
std::printf("=== TS660 Serial Debug ===\n");
std::printf("Port=%s, Baud=%d\n\n", portName.c_str(), baudRate);
SerialPort serial;
std::wstring port = NormalizeCom(A2W(portName));
if (!serial.Open(port.c_str(), baudRate, 8, StopBits::One, Parity::None)) {
std::printf("[FAIL] Cannot open %s\n", portName.c_str());
Sleep(3000);
return -1;
}
std::printf("[OK] Serial opened: %S\n\n", port.c_str());
// 测试 1: 读取温度
{
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_RD | 0x13, 0x0000, nullptr, 0, frame);
DumpHex(frame.data(), static_cast<int>(frame.size()), "SEND READ_TEMP");
PurgeComm(serial.GetHandle(), PURGE_RXCLEAR | PURGE_RXABORT);
int n = serial.Write(frame.data(), static_cast<int>(frame.size()), 1000);
std::printf("Write returned: %d\n\n", n);
// 读取响应 - 循环读取 2 秒
std::printf("Reading response (2s window)...\n");
unsigned char buf[512];
int totalRead = 0;
DWORD startTick = GetTickCount();
while (GetTickCount() - startTick < 2000) {
int r = serial.Read(buf + totalRead, sizeof(buf) - totalRead, 200);
if (r > 0) {
totalRead += r;
std::printf(" Read %d bytes (total=%d)\n", r, totalRead);
}
}
if (totalRead > 0) {
DumpHex(buf, totalRead, "RECV RAW");
} else {
std::printf("[FAIL] No response within 2s\n");
}
}
std::printf("\n");
Sleep(500);
// 测试 2: 软件触发
{
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_WR | 0x14, 0x0000, nullptr, 0, frame);
DumpHex(frame.data(), static_cast<int>(frame.size()), "SEND SOFTWARE_TRIG");
PurgeComm(serial.GetHandle(), PURGE_RXCLEAR | PURGE_RXABORT);
int n = serial.Write(frame.data(), static_cast<int>(frame.size()), 1000);
std::printf("Write returned: %d\n\n", n);
std::printf("Reading response (2s window)...\n");
unsigned char buf[512];
int totalRead = 0;
DWORD startTick = GetTickCount();
while (GetTickCount() - startTick < 2000) {
int r = serial.Read(buf + totalRead, sizeof(buf) - totalRead, 200);
if (r > 0) {
totalRead += r;
std::printf(" Read %d bytes (total=%d)\n", r, totalRead);
}
}
if (totalRead > 0) {
DumpHex(buf, totalRead, "RECV RAW");
} else {
std::printf("[FAIL] No response within 2s\n");
}
}
serial.Close();
std::printf("\n=== Done ===\n");
Sleep(5000);
return 0;
}
+294
View File
@@ -0,0 +1,294 @@
// TS660_Test.cpp: TS660 DLL 简单测试程序
// 用法:
// TS660_Test.exe 交互式选择 COM 端口, 默认 9600
// TS660_Test.exe COM5 指定端口, 9600 波特率
// TS660_Test.exe COM5 115200 指定端口 + 波特率
//
// 说明: 本程序依次调用所有 C 接口, 每步打印结果。
// 无硬件时 ts660_init 会失败, 程序立即退出。
#include "TS660API.h"
#include "TS660DDG.h" // 仅用于调试: 验证帧格式
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
#include <windows.h>
// 每条命令发送后的延时(ms), 给设备处理时间
static const int kStepDelayMs = 500;
static void PrintOk(const char* name) {
std::printf(" [ OK ] %s\n", name);
}
static void PrintFail(const char* name, int code) {
std::printf(" [FAIL] %s (code=%d)\n", name, code);
}
static void Step(int n, const char* title) {
std::printf("\n[%d] %s\n", n, title);
// 从第 2 步起, 给上一条命令处理时间
if (n > 1) Sleep(kStepDelayMs);
}
// 等待用户按键(防止双击运行时窗口一闪而过)
static void Pause() {
std::printf("\n");
std::system("pause");
}
// 枚举系统中可用的 COM 端口(按端口号数字排序)
static std::vector<std::string> EnumerateComPorts() {
std::vector<std::string> ports;
std::vector<char> buf(64 * 1024);
DWORD ret = QueryDosDeviceA(nullptr, buf.data(), static_cast<DWORD>(buf.size()));
if (ret == 0) return ports;
// QueryDosDeviceA 返回以 \0 分隔的设备名列表, 以 \0\0 结尾
char* p = buf.data();
while (*p) {
std::string name(p);
// 严格匹配 "COM" + 纯数字(忽略大小写)
if (name.size() > 3 &&
std::toupper(static_cast<unsigned char>(name[0])) == 'C' &&
std::toupper(static_cast<unsigned char>(name[1])) == 'O' &&
std::toupper(static_cast<unsigned char>(name[2])) == 'M') {
bool allDigit = true;
for (size_t i = 3; i < name.size(); ++i) {
if (!std::isdigit(static_cast<unsigned char>(name[i]))) {
allDigit = false;
break;
}
}
if (allDigit) ports.push_back(name);
}
p += name.size() + 1; // 跳到下一个设备名
}
std::sort(ports.begin(), ports.end(),
[](const std::string& a, const std::string& b) {
int numA = std::stoi(a.substr(3));
int numB = std::stoi(b.substr(3));
return numA < numB;
});
return ports;
}
// 显示 COM 端口列表, 让用户选择; 返回选中的端口名(ASCII)
static std::string SelectComPort() {
auto ports = EnumerateComPorts();
if (ports.empty()) {
std::printf("No COM ports detected automatically.\n");
std::printf("Type port name manually (e.g. COM3, COM50): ");
char input[64];
if (std::fgets(input, sizeof(input), stdin)) {
size_t n = std::strlen(input);
while (n > 0 && (input[n - 1] == '\n' || input[n - 1] == '\r')) {
input[--n] = '\0';
}
if (n > 0) return std::string(input);
}
return "COM3";
}
std::printf("Available COM ports:\n");
for (size_t i = 0; i < ports.size(); ++i) {
std::printf(" [%zu] %s\n", i + 1, ports[i].c_str());
}
std::printf("Select port by number (Enter for default COM3): ");
char input[64];
if (!std::fgets(input, sizeof(input), stdin)) {
return "COM3";
}
if (input[0] == '\n' || input[0] == '\r' || input[0] == '\0') {
return "COM3";
}
int idx = std::atoi(input);
if (idx < 1 || idx > static_cast<int>(ports.size())) {
std::printf("Invalid selection, using COM3.\n");
return "COM3";
}
return ports[static_cast<size_t>(idx - 1)];
}
int main(int argc, char** argv)
{
std::string comPort;
int baudRate = 115200;
if (argc >= 2) {
comPort = argv[1];
} else {
comPort = SelectComPort();
}
if (argc >= 3) baudRate = std::atoi(argv[2]);
std::printf("=== TS660 DLL Test ===\n");
std::printf("Port=%s, Baud=%d\n", comPort.c_str(), baudRate);
// 0. 验证协议帧格式(不依赖硬件)
Step(0, "Verify Protocol Frame Format");
{
std::vector<uint8_t> frame;
// 测试 1: 读取温度(CMD=0x93, 无PA)
TS660DDG::BuildFrame(TS660_RD | 0x13, 0x0000, nullptr, 0, frame);
std::printf(" [Frame] READ_TEMP: ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 06 00 93 00 00 14 02 CC
// 测试 2: 读取时序配置(CMD=0xC1, 无PA, 返回87个uint32)
frame.clear();
TS660DDG::BuildFrame(TS660_RD | 0x41, 0x0000, nullptr, 0, frame);
std::printf(" [Frame] READ_TIMING: ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 06 00 C1 00 00 42 02 CC
// 测试 2: 触发设置-软件触发(CMD=0x01, OPT=3, 无PA)
frame.clear();
TS660DDG::BuildFrame(TS660_WR | 0x01, 3, nullptr, 0, frame);
std::printf(" [Frame] SET_TRIGGER(Software): ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 06 00 01 03 00 85 01 CC
// 测试 3: 内触发频率设置 1kHz(CMD=0x05, PA0=0x0003D090)
frame.clear();
std::vector<uint32_t> freqParams = { 0x0003D090 };
TS660DDG::BuildFrameU32(TS660_WR | 0x05, 0x0000, freqParams, frame);
std::printf(" [Frame] SET_TRIG_FREQ(1kHz): ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 0A 00 05 00 00 90 D0 03 00 ED 02 CC
// 测试 4: 通道输出设置-通道1打开(CMD=0x06, OPT=0x0101, 无PA)
frame.clear();
uint16_t chOpt = (1 << 8) | 1;
TS660DDG::BuildFrame(TS660_WR | 0x06, chOpt, nullptr, 0, frame);
std::printf(" [Frame] SET_CHANNEL(ch1,on): ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 06 00 06 01 01 89 01 CC
// 测试 5: 延时设置-通道1,10ns(CMD=0x08, OPT=1, PA0=0x3E8, PA1=0)
frame.clear();
std::vector<uint32_t> delayParams = { 0x000003E8, 0x00000000 }; // 10ns/10ps=1000
TS660DDG::BuildFrameU32(TS660_WR | 0x08, 1, delayParams, frame);
std::printf(" [Frame] SET_DELAY(ch1,10ns): ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 0E 00 08 01 00 E8 03 00 00 00 00 00 00 7D 02 CC
// 测试 6: 脉宽设置-通道1,100ns(CMD=0x09, OPT=1, PA0=0x2710, PA1=0)
frame.clear();
std::vector<uint32_t> widthParams = { 0x00002710, 0x00000000 }; // 100ns/10ps=10000
TS660DDG::BuildFrameU32(TS660_WR | 0x09, 1, widthParams, frame);
std::printf(" [Frame] SET_PULSE_WIDTH(ch1,100ns): ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 0E 00 09 01 00 10 27 00 00 00 00 00 00 CA 01 CC
// 测试 7: 全局输出-启用(CMD=0x07, OPT=1, 无PA)
frame.clear();
TS660DDG::BuildFrame(TS660_WR | 0x07, 1, nullptr, 0, frame);
std::printf(" [Frame] SET_GLOBAL_OUTPUT(enable): ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 06 00 07 01 00 89 01 CC
// 测试 8: 软件触发(CMD=0x14, 无PA)
frame.clear();
TS660DDG::BuildFrame(TS660_WR | 0x14, 0x0000, nullptr, 0, frame);
std::printf(" [Frame] SOFTWARE_TRIG: ");
TS660DDG::DumpFrame(frame);
// 期望: EB 90 06 00 14 00 00 95 01 CC
std::printf(" [ OK ] Frame format verified\n");
}
// 1. 打开设备
Step(1, "ts660_init (open serial)");
void* handle = ts660_init(comPort.c_str(), baudRate);
if (handle == nullptr) {
std::printf(" [FAIL] ts660_init returned NULL\n");
std::printf(" possible: wrong port name / port occupied / device not connected\n");
Pause();
return -1;
}
char buf[64];
std::snprintf(buf, sizeof(buf), "ts660_init, handle=%p", handle);
PrintOk(buf);
int r = 0;
// 2. 读取温度
Step(2, "ts660_read_temperature");
float temp = 0.0f;
r = ts660_read_temperature(handle, &temp);
if (r == 0) {
std::printf(" [ OK ] temperature = %.2f C\n", static_cast<double>(temp));
} else {
PrintFail("ts660_read_temperature", r);
}
// 3. 读取时序配置(通道 1)
Step(3, "ts660_read_timing_config (channel=1)");
long long delayNs = 0, widthNs = 0;
int trigMode = 0;
double trigFreq = 0.0;
r = ts660_read_timing_config(handle, 1, &delayNs, &widthNs, &trigMode, &trigFreq);
if (r == 0) {
std::printf(" [ OK ] delay=%lld ns, width=%lld ns, trigMode=%d, trigFreq=%.2f Hz\n",
delayNs, widthNs, trigMode, trigFreq);
} else {
PrintFail("ts660_read_timing_config", r);
}
// 4. 设置触发模式 = Internal(0)
Step(4, "ts660_set_trigger (Internal)");
r = ts660_set_trigger(handle, 0);
if (r == 0) PrintOk("ts660_set_trigger"); else PrintFail("ts660_set_trigger", r);
// 5. 设置内触发频率 1 kHz
Step(5, "ts660_set_trigger_freq (1000 Hz)");
r = ts660_set_trigger_freq(handle, 1000.0);
if (r == 0) PrintOk("ts660_set_trigger_freq"); else PrintFail("ts660_set_trigger_freq", r);
// 6. 启用通道 1 输出
Step(6, "ts660_set_output_channel (ch=1, enable)");
r = ts660_set_output_channel(handle, 1, 1);
if (r == 0) PrintOk("ts660_set_output_channel"); else PrintFail("ts660_set_output_channel", r);
// 7. 设置通道 1 延时 10 ns
Step(7, "ts660_set_delay (ch=1, 10 ns)");
r = ts660_set_delay(handle, 1, 10);
if (r == 0) PrintOk("ts660_set_delay"); else PrintFail("ts660_set_delay", r);
// 8. 设置通道 1 脉宽 100 ns
Step(8, "ts660_set_pulse_width (ch=1, 100 ns)");
r = ts660_set_pulse_width(handle, 1, 100);
if (r == 0) PrintOk("ts660_set_pulse_width"); else PrintFail("ts660_set_pulse_width", r);
// 9. 启用全局输出
Step(9, "ts660_set_global_output (enable)");
r = ts660_set_global_output(handle, 1);
if (r == 0) PrintOk("ts660_set_global_output"); else PrintFail("ts660_set_global_output", r);
// 10. 软件触发(先切到软件触发模式)
Step(10, "ts660_set_trigger (Software)");
r = ts660_set_trigger(handle, 2); // Software = 2
if (r == 0) PrintOk("ts660_set_trigger(Software)"); else PrintFail("ts660_set_trigger(Software)", r);
Step(10, "ts660_software_trigger");
r = ts660_software_trigger(handle);
if (r == 0) PrintOk("ts660_software_trigger"); else PrintFail("ts660_software_trigger", r);
// 11. 关闭设备
Step(11, "ts660_close");
ts660_close(handle);
PrintOk("ts660_close");
std::printf("\n=== Test End ===\n");
Pause();
return 0;
}
+150
View File
@@ -0,0 +1,150 @@
<?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>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{7F3B2A11-1C2D-4E5F-9A8B-0123456789AB}</ProjectGuid>
<RootNamespace>TS660_Test</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<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" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(ProjectDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(ProjectDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(ProjectDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(ProjectDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="TS660_Test.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="TS660_DLL.vcxproj">
<Project>{9ad27bf0-ea15-427f-8984-1cb2c92c6215}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+472
View File
@@ -0,0 +1,472 @@
// TS660_UnitTest.cpp: TS660 协议函数单元测试
//
// 测试范围:
// - Checksum: 校验和算法
// - BuildFrame / BuildFrameU32: 帧构建
// - ParseFrame: 帧解析(含负面用例)
// - TS660Frame: ReadU32/ReadU64/ReadFloat 辅助方法
// - TS660Proto: TriggerModeOpt/ChannelOpt/IsWriteSuccess
//
// 所有 golden 数据来自真实协议文档, 不依赖硬件
#include "pch.h"
#include "TS660DDG.h"
#include <cstdio>
#include <vector>
#include <cstring>
#include <cstdint>
// ===== 测试框架(轻量级) =====
static int g_passCount = 0;
static int g_failCount = 0;
#define EXPECT_TRUE(cond, msg) \
do { if ((cond)) { ++g_passCount; } else { ++g_failCount; \
std::printf(" [FAIL] %s (line %d): %s\n", __FILE__, __LINE__, msg); \
} } while(0)
#define EXPECT_FALSE(cond, msg) EXPECT_TRUE(!(cond), msg)
#define EXPECT_EQ(a, b, msg) \
do { if ((a) == (b)) { ++g_passCount; } else { ++g_failCount; \
std::printf(" [FAIL] %s (line %d): %s (got=%lld, want=%lld)\n", \
__FILE__, __LINE__, msg, (long long)(a), (long long)(b)); \
} } while(0)
#define EXPECT_BYTES_EQ(got, want, msg) \
do { bool ok = (got.size() == want.size()); \
if (ok) for (size_t i = 0; i < got.size(); ++i) \
if (got[i] != want[i]) { ok = false; break; } \
if (ok) { ++g_passCount; } else { ++g_failCount; \
std::printf(" [FAIL] %s (line %d): %s\n", __FILE__, __LINE__, msg); \
std::printf(" got: "); for (auto b : got) std::printf("%02X ", b); std::printf("\n"); \
std::printf(" want: "); for (auto b : want) std::printf("%02X ", b); std::printf("\n"); \
} } while(0)
// 从十六进制字符串构造字节向量
static std::vector<uint8_t> Bytes(const char* hex) {
std::vector<uint8_t> v;
for (const char* p = hex; *p; ++p) {
char c = *p;
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') continue;
char hi = c;
char lo = *(++p);
if (lo == 0) break;
auto parse = [](char ch) -> int {
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
return 0;
};
v.push_back(static_cast<uint8_t>((parse(hi) << 4) | parse(lo)));
}
return v;
}
#define TEST(name) static void name()
// ===== 测试用例 =====
// --- Checksum ---
TEST(TestChecksum_ReadTemp) {
// READ_TEMP 发送帧: EB 90 06 00 93 00 00 → 校验和应 = 0x0214
auto data = Bytes("EB 90 06 00 93 00 00");
uint16_t chk = TS660DDG::Checksum(data.data(), static_cast<int>(data.size()));
EXPECT_EQ(chk, 0x0214, "READ_TEMP checksum");
}
TEST(TestChecksum_SoftwareTrig) {
// SOFTWARE_TRIG: EB 90 06 00 14 00 00 → sum = 0x0195
auto data = Bytes("EB 90 06 00 14 00 00");
uint16_t chk = TS660DDG::Checksum(data.data(), static_cast<int>(data.size()));
EXPECT_EQ(chk, 0x0195, "SOFTWARE_TRIG checksum");
}
TEST(TestChecksum_SetTrigFreq) {
// SET_TRIG_FREQ: EB 90 0A 00 05 00 00 90 D0 03 00 → sum = 0x02ED
auto data = Bytes("EB 90 0A 00 05 00 00 90 D0 03 00");
uint16_t chk = TS660DDG::Checksum(data.data(), static_cast<int>(data.size()));
EXPECT_EQ(chk, 0x02ED, "SET_TRIG_FREQ checksum");
}
TEST(TestChecksum_Empty) {
EXPECT_EQ(TS660DDG::Checksum(nullptr, 0), 0, "Empty checksum");
}
TEST(TestChecksum_Overflow) {
// 验证: 多字节求和只取低16位
// 300 * 0xFF = 76500 = 0x12AD4, 低16位 = 0x2AD4
std::vector<uint8_t> data(300, 0xFF);
uint16_t chk = TS660DDG::Checksum(data.data(), 300);
EXPECT_EQ(chk, 0x2AD4, "Overflow checksum low 16 bits");
}
// --- BuildFrame ---
TEST(TestBuildFrame_ReadTemp) {
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_RD | 0x13, 0x0000, nullptr, 0, frame);
auto expected = Bytes("EB 90 06 00 93 00 00 14 02 CC");
EXPECT_BYTES_EQ(frame, expected, "READ_TEMP frame");
}
TEST(TestBuildFrame_ReadTiming) {
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_RD | 0x41, 0x0000, nullptr, 0, frame);
auto expected = Bytes("EB 90 06 00 C1 00 00 42 02 CC");
EXPECT_BYTES_EQ(frame, expected, "READ_TIMING frame");
}
TEST(TestBuildFrame_SetTriggerSoftware) {
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_WR | 0x01, 0x0003, nullptr, 0, frame);
auto expected = Bytes("EB 90 06 00 01 03 00 85 01 CC");
EXPECT_BYTES_EQ(frame, expected, "SET_TRIGGER(Software) frame");
}
TEST(TestBuildFrame_SetChannelOn) {
std::vector<uint8_t> frame;
// OPT = (1 << 8) | 1 = 0x0101
TS660DDG::BuildFrame(TS660_WR | 0x06, 0x0101, nullptr, 0, frame);
auto expected = Bytes("EB 90 06 00 06 01 01 89 01 CC");
EXPECT_BYTES_EQ(frame, expected, "SET_CHANNEL(ch1,on) frame");
}
TEST(TestBuildFrame_SetGlobalOutput) {
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_WR | 0x07, 0x0001, nullptr, 0, frame);
auto expected = Bytes("EB 90 06 00 07 01 00 89 01 CC");
EXPECT_BYTES_EQ(frame, expected, "SET_GLOBAL_OUTPUT(enable) frame");
}
TEST(TestBuildFrame_SoftwareTrig) {
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_WR | 0x14, 0x0000, nullptr, 0, frame);
auto expected = Bytes("EB 90 06 00 14 00 00 95 01 CC");
EXPECT_BYTES_EQ(frame, expected, "SOFTWARE_TRIG frame");
}
// --- BuildFrameU32 ---
TEST(TestBuildFrameU32_SetTrigFreq) {
// 1kHz → 控制字 0x0003D090
std::vector<uint32_t> params = { 0x0003D090 };
std::vector<uint8_t> frame;
TS660DDG::BuildFrameU32(TS660_WR | 0x05, 0x0000, params, frame);
auto expected = Bytes("EB 90 0A 00 05 00 00 90 D0 03 00 ED 02 CC");
EXPECT_BYTES_EQ(frame, expected, "SET_TRIG_FREQ(1kHz) frame");
}
TEST(TestBuildFrameU32_SetDelay) {
// 通道1, 10ns → 控制字 = 10*100 = 1000 = 0x3E8
// OPT=1(通道号), PA0=0x3E8(低32位), PA1=0(高32位)
std::vector<uint32_t> params = { 0x000003E8, 0x00000000 };
std::vector<uint8_t> frame;
TS660DDG::BuildFrameU32(TS660_WR | 0x08, 0x0001, params, frame);
auto expected = Bytes("EB 90 0E 00 08 01 00 E8 03 00 00 00 00 00 00 7D 02 CC");
EXPECT_BYTES_EQ(frame, expected, "SET_DELAY(ch1,10ns) frame");
}
TEST(TestBuildFrameU32_SetPulseWidth) {
// 通道1, 100ns → 控制字 = 100*100 = 10000 = 0x2710
std::vector<uint32_t> params = { 0x00002710, 0x00000000 };
std::vector<uint8_t> frame;
TS660DDG::BuildFrameU32(TS660_WR | 0x09, 0x0001, params, frame);
auto expected = Bytes("EB 90 0E 00 09 01 00 10 27 00 00 00 00 00 00 CA 01 CC");
EXPECT_BYTES_EQ(frame, expected, "SET_PULSE_WIDTH(ch1,100ns) frame");
}
TEST(TestBuildFrameU32_EmptyParams) {
// 空参数 等价于 无PA
std::vector<uint32_t> params;
std::vector<uint8_t> frame;
TS660DDG::BuildFrameU32(TS660_WR | 0x14, 0x0000, params, frame);
auto expected = Bytes("EB 90 06 00 14 00 00 95 01 CC");
EXPECT_BYTES_EQ(frame, expected, "Empty params equivalent to no PA");
}
// --- ParseFrame (正面用例) ---
TEST(TestParseFrame_ReadTempResp) {
// 接收: EB 90 0A 00 93 01 00 00 C0 EC 41 06 04 CC
auto data = Bytes("EB 90 0A 00 93 01 00 00 C0 EC 41 06 04 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_TRUE(ok, "Parse READ_TEMP response");
EXPECT_EQ(f.cmd, 0x93, "cmd");
EXPECT_EQ(f.opt, 0x0001, "opt");
EXPECT_EQ(f.pa.size(), static_cast<size_t>(4), "pa size");
// 温度 = 0x41ECC000 = 29.5°C
float temp = f.ReadFloat(0);
EXPECT_TRUE(temp > 29.0f && temp < 30.0f, "temperature ~29.5C");
}
TEST(TestParseFrame_SetTriggerResp) {
// 接收: EB 90 06 00 01 01 00 83 01 CC
auto data = Bytes("EB 90 06 00 01 01 00 83 01 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_TRUE(ok, "Parse SET_TRIGGER response");
EXPECT_EQ(f.cmd, 0x01, "cmd");
EXPECT_EQ(f.opt, 0x0001, "opt (success)");
EXPECT_EQ(f.pa.size(), static_cast<size_t>(0), "pa size (no PA)");
}
TEST(TestParseFrame_SetTriggerFailResp) {
// OPT=0x0002 表示失败
auto data = Bytes("EB 90 06 00 01 02 00 84 01 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_TRUE(ok, "Parse SET_TRIGGER fail response");
EXPECT_EQ(f.opt, 0x0002, "opt (fail)");
}
TEST(TestParseFrame_SoftwareTrigResp) {
// 接收: EB 90 06 00 14 01 00 96 01 CC
auto data = Bytes("EB 90 06 00 14 01 00 96 01 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_TRUE(ok, "Parse SOFTWARE_TRIG response");
EXPECT_EQ(f.cmd, 0x14, "cmd");
EXPECT_EQ(f.opt, 0x0001, "opt (success)");
}
TEST(TestParseFrame_ReadTimingResp) {
// 简化的 READ_TIMING 响应(只测前几个字段)
// LEN=0x0162=354, DATA=351=CMD(1)+OPT(2)+PA(348=87*4)
// 构造一个最小有效帧: CMD=C1, OPT=0, PA0~PA7 全0, 其余PA也0
std::vector<uint8_t> data;
data.push_back(0xEB); data.push_back(0x90);
int dataLen = 1 + 2 + 87 * 4; // 351
int lenField = dataLen + 3; // 354
data.push_back(static_cast<uint8_t>(lenField & 0xFF)); // 0x62
data.push_back(static_cast<uint8_t>((lenField >> 8) & 0xFF)); // 0x01
data.push_back(0xC1); // CMD
data.push_back(0x00); data.push_back(0x00); // OPT
// 87 个 PA 全 0
for (int i = 0; i < 87 * 4; ++i) data.push_back(0);
// 校验和(占位, 下面计算后替换)
int chkPos = static_cast<int>(data.size());
data.push_back(0); data.push_back(0);
data.push_back(0xCC); // 帧尾
// 计算正确校验和
uint16_t chk = TS660DDG::Checksum(data.data(), chkPos);
data[chkPos] = static_cast<uint8_t>(chk & 0xFF);
data[chkPos + 1] = static_cast<uint8_t>((chk >> 8) & 0xFF);
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_TRUE(ok, "Parse READ_TIMING response");
EXPECT_EQ(f.cmd, 0xC1, "cmd");
EXPECT_EQ(f.opt, 0x0000, "opt");
EXPECT_EQ(f.pa.size(), static_cast<size_t>(348), "pa size = 348 bytes");
}
// --- ParseFrame (负面用例) ---
TEST(TestParseFrame_BadHead) {
auto data = Bytes("AA 90 06 00 01 01 00 83 01 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_FALSE(ok, "Bad head0 rejected");
}
TEST(TestParseFrame_BadTail) {
auto data = Bytes("EB 90 06 00 01 01 00 83 01 DD");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_FALSE(ok, "Bad tail rejected");
}
TEST(TestParseFrame_BadChecksum) {
// 校验和被篡改
auto data = Bytes("EB 90 06 00 01 01 00 FF FF 01 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_FALSE(ok, "Bad checksum rejected");
}
TEST(TestParseFrame_TooShort) {
auto data = Bytes("EB 90 06");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_FALSE(ok, "Too short rejected");
}
TEST(TestParseFrame_NullInput) {
TS660Frame f;
bool ok = TS660DDG::ParseFrame(nullptr, 0, f);
EXPECT_FALSE(ok, "Null input rejected");
}
TEST(TestParseFrame_BadLenField) {
// LEN=0x0001 太小 (< 3)
auto data = Bytes("EB 90 01 00 01 01 00 83 01 CC");
TS660Frame f;
bool ok = TS660DDG::ParseFrame(data.data(), static_cast<int>(data.size()), f);
EXPECT_FALSE(ok, "Bad len field rejected");
}
// --- TS660Frame 辅助方法 ---
TEST(TestFrame_ReadU32) {
TS660Frame f;
f.pa = Bytes("78 56 34 12"); // 小端 = 0x12345678
EXPECT_EQ(f.ReadU32(0), 0x12345678u, "ReadU32 little endian");
}
TEST(TestFrame_ReadU64) {
TS660Frame f;
f.pa = Bytes("00 00 00 00 01 00 00 00"); // 低32=0, 高32=1
EXPECT_EQ(f.ReadU64(0), 0x0000000100000000ULL, "ReadU64");
}
TEST(TestFrame_ReadFloat) {
TS660Frame f;
// 0x41ECC000 = 29.5f
f.pa = Bytes("00 C0 EC 41");
float val = f.ReadFloat(0);
EXPECT_TRUE(val > 29.0f && val < 30.0f, "ReadFloat 29.5");
}
TEST(TestFrame_ReadU32_OutOfBounds) {
TS660Frame f;
f.pa = Bytes("01 02"); // 只有2字节
EXPECT_EQ(f.ReadU32(0), 0u, "ReadU32 out of bounds returns 0");
}
// --- TS660Proto 工具函数 ---
TEST(TestProto_TriggerModeOpt) {
EXPECT_EQ(TS660Proto::TriggerModeOpt(TS660TriggerMode::Internal), 1, "Internal→1");
EXPECT_EQ(TS660Proto::TriggerModeOpt(TS660TriggerMode::External), 2, "External→2");
EXPECT_EQ(TS660Proto::TriggerModeOpt(TS660TriggerMode::Software), 3, "Software→3");
}
TEST(TestProto_ChannelOpt) {
EXPECT_EQ(TS660Proto::ChannelOpt(1, true), 0x0101, "ch1 on → 0x0101");
EXPECT_EQ(TS660Proto::ChannelOpt(1, false), 0x0100, "ch1 off → 0x0100");
EXPECT_EQ(TS660Proto::ChannelOpt(8, true), 0x0801, "ch8 on → 0x0801");
}
TEST(TestProto_IsWriteSuccess) {
TS660Frame ok;
ok.valid = true;
ok.opt = 0x0001;
EXPECT_TRUE(TS660Proto::IsWriteSuccess(ok), "OPT=1 → success");
TS660Frame fail;
fail.valid = true;
fail.opt = 0x0002;
EXPECT_FALSE(TS660Proto::IsWriteSuccess(fail), "OPT=2 → fail");
TS660Frame invalid;
invalid.valid = false;
EXPECT_FALSE(TS660Proto::IsWriteSuccess(invalid), "invalid → fail");
}
// --- BuildFrame + ParseFrame 往返测试 ---
TEST(TestRoundTrip_ReadTemp) {
std::vector<uint8_t> frame;
TS660DDG::BuildFrame(TS660_RD | 0x13, 0x0000, nullptr, 0, frame);
TS660Frame parsed;
bool ok = TS660DDG::ParseFrame(frame.data(), static_cast<int>(frame.size()), parsed);
EXPECT_TRUE(ok, "Round trip READ_TEMP");
EXPECT_EQ(parsed.cmd, 0x93, "round trip cmd");
EXPECT_EQ(parsed.opt, 0x0000, "round trip opt");
}
TEST(TestRoundTrip_SetDelay) {
std::vector<uint32_t> params = { 0x000003E8, 0x00000000 };
std::vector<uint8_t> frame;
TS660DDG::BuildFrameU32(TS660_WR | 0x08, 0x0001, params, frame);
TS660Frame parsed;
bool ok = TS660DDG::ParseFrame(frame.data(), static_cast<int>(frame.size()), parsed);
EXPECT_TRUE(ok, "Round trip SET_DELAY");
EXPECT_EQ(parsed.cmd, 0x08, "round trip cmd");
EXPECT_EQ(parsed.opt, 0x0001, "round trip opt");
EXPECT_EQ(parsed.pa.size(), static_cast<size_t>(8), "round trip pa size");
EXPECT_EQ(parsed.ReadU32(0), 0x000003E8u, "round trip PA0");
EXPECT_EQ(parsed.ReadU32(4), 0x00000000u, "round trip PA1");
}
// ===== 主程序 =====
int main() {
std::printf("=== TS660 Protocol Unit Tests ===\n\n");
auto run = [](const char* name, void(*fn)()) {
std::printf("[TEST] %s\n", name);
fn();
};
// Checksum
run("TestChecksum_ReadTemp", TestChecksum_ReadTemp);
run("TestChecksum_SoftwareTrig", TestChecksum_SoftwareTrig);
run("TestChecksum_SetTrigFreq", TestChecksum_SetTrigFreq);
run("TestChecksum_Empty", TestChecksum_Empty);
run("TestChecksum_Overflow", TestChecksum_Overflow);
std::printf("\n");
// BuildFrame
run("TestBuildFrame_ReadTemp", TestBuildFrame_ReadTemp);
run("TestBuildFrame_ReadTiming", TestBuildFrame_ReadTiming);
run("TestBuildFrame_SetTriggerSoftware", TestBuildFrame_SetTriggerSoftware);
run("TestBuildFrame_SetChannelOn", TestBuildFrame_SetChannelOn);
run("TestBuildFrame_SetGlobalOutput", TestBuildFrame_SetGlobalOutput);
run("TestBuildFrame_SoftwareTrig", TestBuildFrame_SoftwareTrig);
std::printf("\n");
// BuildFrameU32
run("TestBuildFrameU32_SetTrigFreq", TestBuildFrameU32_SetTrigFreq);
run("TestBuildFrameU32_SetDelay", TestBuildFrameU32_SetDelay);
run("TestBuildFrameU32_SetPulseWidth", TestBuildFrameU32_SetPulseWidth);
run("TestBuildFrameU32_EmptyParams", TestBuildFrameU32_EmptyParams);
std::printf("\n");
// ParseFrame (正面)
run("TestParseFrame_ReadTempResp", TestParseFrame_ReadTempResp);
run("TestParseFrame_SetTriggerResp", TestParseFrame_SetTriggerResp);
run("TestParseFrame_SetTriggerFailResp", TestParseFrame_SetTriggerFailResp);
run("TestParseFrame_SoftwareTrigResp", TestParseFrame_SoftwareTrigResp);
run("TestParseFrame_ReadTimingResp", TestParseFrame_ReadTimingResp);
std::printf("\n");
// ParseFrame (负面)
run("TestParseFrame_BadHead", TestParseFrame_BadHead);
run("TestParseFrame_BadTail", TestParseFrame_BadTail);
run("TestParseFrame_BadChecksum", TestParseFrame_BadChecksum);
run("TestParseFrame_TooShort", TestParseFrame_TooShort);
run("TestParseFrame_NullInput", TestParseFrame_NullInput);
run("TestParseFrame_BadLenField", TestParseFrame_BadLenField);
std::printf("\n");
// TS660Frame 辅助方法
run("TestFrame_ReadU32", TestFrame_ReadU32);
run("TestFrame_ReadU64", TestFrame_ReadU64);
run("TestFrame_ReadFloat", TestFrame_ReadFloat);
run("TestFrame_ReadU32_OutOfBounds", TestFrame_ReadU32_OutOfBounds);
std::printf("\n");
// TS660Proto 工具函数
run("TestProto_TriggerModeOpt", TestProto_TriggerModeOpt);
run("TestProto_ChannelOpt", TestProto_ChannelOpt);
run("TestProto_IsWriteSuccess", TestProto_IsWriteSuccess);
std::printf("\n");
// 往返测试
run("TestRoundTrip_ReadTemp", TestRoundTrip_ReadTemp);
run("TestRoundTrip_SetDelay", TestRoundTrip_SetDelay);
std::printf("\n");
std::printf("=== Summary ===\n");
std::printf(" Pass: %d\n", g_passCount);
std::printf(" Fail: %d\n", g_failCount);
std::printf(" Total: %d\n", g_passCount + g_failCount);
std::printf(" Result: %s\n", g_failCount == 0 ? "ALL PASS" : "HAS FAILURES");
return g_failCount == 0 ? 0 : 1;
}
+82
View File
@@ -0,0 +1,82 @@
<?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>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{3A3B3C3D-4E4F-4050-9090-101010101010}</ProjectGuid>
<RootNamespace>TS660_UnitTest</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings" />
<ImportGroup Label="Shared" />
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup>
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalIncludeDirectories>$(SolutionDir)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>TS660_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="TS660_UnitTest.cpp" />
<ClCompile Include="TS660DDG.cpp" />
<ClCompile Include="SerialPort.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="TS660DDG.h" />
<ClInclude Include="SerialPort.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
+12
View File
@@ -0,0 +1,12 @@
@echo off
:: VS 2019 x64 开发者环境
call "D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1
cd /d "g:\project\dllTest\TS660_DLL"
:: 编译调试程序
cl /nologo /EHsc /W3 /std:c++17 /utf-8 ^
/I. ^
TS660_Debug.cpp SerialPort.cpp TS660DDG.cpp ^
/link /OUT:TS660_Debug.exe user32.lib
del /q TS660_Debug.obj SerialPort.obj TS660DDG.obj *.vcxproj.* 2>nul
echo.
echo === Build complete ===
+17
View File
@@ -0,0 +1,17 @@
$env:VCVARS = "D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
# 加载 VS 环境
$vcvarsOutput = & cmd /c "`"$env:VCVARS`" >nul 2>&1 && set" 2>$null
foreach ($line in $vcvarsOutput) {
if ($line -match '^([^=]+)=(.*)$') {
Set-Item -Path "env:$($matches[1])" -Value $matches[2]
}
}
Write-Host "INCLUDE: $($env:INCLUDE.Substring(0, [Math]::Min(80, $env:INCLUDE.Length)))..."
Set-Location "g:\project\dllTest\TS660_DLL"
# 编译
cl /nologo /EHsc /W3 /std:c++17 /utf-8 /DTS660_DLL_EXPORTS /I. TS660_Debug.cpp SerialPort.cpp TS660DDG.cpp /link /OUT:TS660_Debug.exe user32.lib 2>&1 | Select-Object -Last 8
Remove-Item TS660_Debug.obj, SerialPort.obj, TS660DDG.obj -ErrorAction SilentlyContinue
Write-Host "=== Build complete ==="
+109
View File
@@ -0,0 +1,109 @@
# build_debug_x64.ps1
# 一键编译 TS660_DLL 解决方案 (Debug + x64)
#
# 用法:
# 1. 右键此文件 -> "用 PowerShell 运行"
# 2. 或在 PowerShell 中执行: .\build_debug_x64.ps1
# 3. 或在 cmd 中执行: powershell -ExecutionPolicy Bypass -File build_debug_x64.ps1
#
# 如遇执行策略限制, 用以下命令临时绕过(仅当前会话有效):
# Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
param(
[string]$Configuration = "Debug",
[string]$Platform = "x64"
)
$ErrorActionPreference = "Stop"
# 切到脚本所在目录(项目根)
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $scriptRoot
Write-Host "[INFO] Working dir: $scriptRoot" -ForegroundColor Cyan
$solution = Join-Path $scriptRoot "TS660_DLL.sln"
if (-not (Test-Path $solution)) {
Write-Host "[ERROR] Solution file not found: $solution" -ForegroundColor Red
exit 1
}
# === 自动定位 MSBuild ===
$msbuild = $null
# 方式 1: PATH 中已有 msbuild
$found = Get-Command msbuild -ErrorAction SilentlyContinue
if ($found) {
$msbuild = $found.Source
Write-Host "[INFO] Found MSBuild in PATH." -ForegroundColor Gray
}
# 方式 2: 通过 vswhere 自动定位最新 VS 安装
if (-not $msbuild) {
$vswhere = "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vswhere) {
$vsPath = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild -property installationPath 2>$null
if ($vsPath) {
$candidate = Join-Path $vsPath "MSBuild\Current\Bin\MSBuild.exe"
if (Test-Path $candidate) {
$msbuild = $candidate
Write-Host "[INFO] Found MSBuild via vswhere: $msbuild" -ForegroundColor Gray
}
}
}
}
# 方式 3: 常见安装路径硬编码兜底
if (-not $msbuild) {
$candidates = @(
"D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe",
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe",
"D:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe",
"C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe"
)
foreach ($c in $candidates) {
if (Test-Path $c) {
$msbuild = $c
Write-Host "[INFO] Found MSBuild at fallback path: $msbuild" -ForegroundColor Gray
break
}
}
}
if (-not $msbuild) {
Write-Host "[ERROR] MSBuild not found. Please install Visual Studio 2019/2022 with C++ workload." -ForegroundColor Red
Write-Host " Or add MSBuild.exe to PATH manually." -ForegroundColor Yellow
exit 2
}
Write-Host "[INFO] MSBuild: $msbuild" -ForegroundColor Cyan
Write-Host "[INFO] Configuration: $Configuration | Platform: $Platform" -ForegroundColor Cyan
Write-Host ""
# === 执行编译 ===
$startTime = Get-Date
& $msbuild $solution /t:Build /p:Configuration=$Configuration /p:Platform=$Platform /v:minimal /nologo
$exitCode = $LASTEXITCODE
$elapsed = (Get-Date) - $startTime
Write-Host ""
if ($exitCode -eq 0) {
Write-Host "[OK] Build succeeded in $($elapsed.TotalSeconds.ToString('0.00'))s" -ForegroundColor Green
# 显示产物
$outDir = Join-Path $scriptRoot "$Platform\$Configuration"
if (Test-Path $outDir) {
Write-Host ""
Write-Host "[INFO] Outputs in: $outDir" -ForegroundColor Cyan
Get-ChildItem $outDir -File |
Where-Object { $_.Extension -in '.dll', '.lib', '.exe' } |
Sort-Object Name |
ForEach-Object {
$sizeKB = "{0,8:N1} KB" -f ($_.Length / 1KB)
Write-Host (" {0,-20} {1}" -f $_.Name, $sizeKB)
}
}
} else {
Write-Host "[FAIL] Build failed with exit code $exitCode (took $($elapsed.TotalSeconds.ToString('0.00'))s)" -ForegroundColor Red
}
exit $exitCode
+22
View File
@@ -0,0 +1,22 @@
$env:VCVARS = "D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
# 加载 VS 环境
$vcvarsOutput = & cmd /c "`"$env:VCVARS`" >nul 2>&1 && set" 2>$null
foreach ($line in $vcvarsOutput) {
if ($line -match '^([^=]+)=(.*)$') {
Set-Item -Path "env:$($matches[1])" -Value $matches[2]
}
}
Set-Location "g:\project\dllTest\TS660_DLL\TS660_DLL_SDK"
# 编译示例
& cl /nologo /EHsc /W3 /utf-8 /I. example\example.c /link /OUT:example.exe TS660_DLL.lib 2>&1 | Select-Object -Last 3
Remove-Item example.obj -ErrorAction SilentlyContinue
if (Test-Path example.exe) {
Write-Host "示例编译成功"
(Get-Item example.exe) | Select-Object Name, @{N='Size(KB)';E={[math]::Round($_.Length/1KB,1)}}
Remove-Item example.exe -ErrorAction SilentlyContinue
} else {
Write-Host "示例编译失败"
}
+16
View File
@@ -0,0 +1,16 @@
$env:VCPATH = "D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
$vcvarsOutput = & cmd /c "`"$env:VCPATH`" >nul 2>&1 && set" 2>$null
foreach ($line in $vcvarsOutput) {
if ($line -match '^([^=]+)=(.*)$') {
Set-Item -Path "env:$($matches[1])" -Value $matches[2]
}
}
Set-Location "g:\project\dllTest\TS660_DLL"
# 编译单元测试
$clOutput = & cl /nologo /EHsc /W3 /std:c++17 /utf-8 /DTS660_DLL_EXPORTS /I. TS660_UnitTest.cpp TS660DDG.cpp SerialPort.cpp /link /OUT:TS660_UnitTest.exe user32.lib 2>&1
Write-Host $clOutput[-5..-1]
Remove-Item TS660_UnitTest.obj, TS660DDG.obj, SerialPort.obj -ErrorAction SilentlyContinue
Write-Host "=== Build complete ==="
+19
View File
@@ -0,0 +1,19 @@
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
+51
View File
@@ -0,0 +1,51 @@
/* example.c: TS660_DLL 调用示例
*
* 编译: cl /I. example.c /link TS660_DLL.lib /OUT:example.exe
* 运行: example.exe COM10
*/
#include "TS660API.h"
#include <stdio.h>
int main(int argc, char** argv) {
const char* port = (argc >= 2) ? argv[1] : "COM3";
printf("=== TS660 Example ===\nPort: %s\n\n", port);
/* 1. 打开设备 */
void* h = ts660_init(port, 0); /* 0 = 默认波特率 115200 */
if (!h) { printf("[FAIL] 打开失败\n"); return -1; }
printf("[OK] 设备已打开\n");
/* 2. 读取温度 */
float temp = 0;
if (ts660_read_temperature(h, &temp) == 0)
printf("温度: %.2f C\n", temp);
else
printf("[FAIL] 读取温度失败\n");
/* 3. 读取时序配置(通道1) */
long long delay_ns = 0, width_ns = 0;
int trig_mode = 0;
double trig_freq = 0;
if (ts660_read_timing_config(h, 1, &delay_ns, &width_ns, &trig_mode, &trig_freq) == 0) {
printf("通道1: 延时=%lldns, 脉宽=%lldns\n", delay_ns, width_ns);
printf("触发模式=%d, 频率=%.1fHz\n", trig_mode, trig_freq);
}
/* 4. 配置: 内触发 1kHz, 通道1延时10ns/脉宽100ns */
ts660_set_trigger(h, 0); /* 内部触发 */
ts660_set_trigger_freq(h, 1000.0); /* 1kHz */
ts660_set_delay(h, 1, 10); /* 通道1延时10ns */
ts660_set_pulse_width(h, 1, 100); /* 通道1脉宽100ns */
ts660_set_output_channel(h, 1, 1); /* 使能通道1 */
ts660_set_global_output(h, 1); /* 开启全局输出 */
printf("[OK] 配置完成\n");
/* 5. (可选) 软件触发 */
/* ts660_set_trigger(h, 2); */ /* 先切到软件触发模式 */
/* ts660_software_trigger(h); */
/* 6. 关闭 */
ts660_close(h);
printf("[OK] 设备已关闭\n");
return 0;
}
+5
View File
@@ -0,0 +1,5 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>
+5
View File
@@ -0,0 +1,5 @@
// pch.cpp: 与预编译标头对应的源文件
#include "pch.h"
// 当使用预编译的头时,需要使用此源文件,编译才能成功。
+13
View File
@@ -0,0 +1,13 @@
// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H