提交位移台和对焦系统代码

This commit is contained in:
ldh
2026-11-18 08:55:40 +08:00
parent 29e90bbc7b
commit dd6edce089
21 changed files with 2083 additions and 0 deletions
@@ -0,0 +1,116 @@
using System.Runtime.InteropServices;
namespace HardwareControl.Core.AxisPlatform
{
/// <summary>
/// AxisPlatform2.dll 的 P/Invoke 声明。
/// 所有结构体按 C 端 #pragma pack(1) 布局,字段顺序与 axis_platform2.h 一致。
/// </summary>
internal static class AxisPlatformNative
{
private const string DllName = "AxisPlatform2.dll";
// 错误码,对应 AXIS2_ERR_*
internal const int Ok = 0;
internal const int ErrNullPtr = -1;
internal const int ErrBufTooSmall = -2;
internal const int ErrFrameTooShort = -3;
internal const int ErrComOpenFailed = -4;
internal const int ErrComNotOpen = -5;
internal const int ErrComSendFailed = -6;
internal const int ErrParseFailed = -7;
internal const int ErrTimeout = -8;
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern IntPtr axis_init(
[MarshalAs(UnmanagedType.LPStr)] string comPort,
byte headType,
IntPtr limits);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void axis_close(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int axis_x_move(IntPtr handle, short distance, ushort speed, ushort accel);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int axis_y_move(IntPtr handle, short distance, ushort speed, ushort accel);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int axis_z_move(IntPtr handle, short distance, ushort speed, ushort accel);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int axis_xyz_rel_move(
IntPtr handle,
ref Axis2MoveParams x,
ref Axis2MoveParams y,
ref Axis2MoveParams z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int axis_xyz_abs_move(
IntPtr handle,
ref Axis2MoveParams x,
ref Axis2MoveParams y,
ref Axis2MoveParams z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void axis_flush(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int axis_read_upload(IntPtr handle, out Axis2UploadData data);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr axis_get_error(IntPtr handle);
/// <summary>读取 DLL 内部记录的最后一次错误描述;无错误或句柄为空时返回空串。</summary>
internal static string GetError(IntPtr handle)
{
if (handle == IntPtr.Zero)
{
return string.Empty;
}
var pointer = axis_get_error(handle);
return pointer == IntPtr.Zero
? string.Empty
: Marshal.PtrToStringAnsi(pointer) ?? string.Empty;
}
}
/// <summary>限位参数,对应 Axis2Limits(6 × int32)。</summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Axis2Limits
{
public int XPosLimit;
public int XNegLimit;
public int YPosLimit;
public int YNegLimit;
public int ZPosLimit;
public int ZNegLimit;
}
/// <summary>单轴运动参数,对应 Axis2MoveParams(6 字节)。</summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Axis2MoveParams
{
public short Distance;
public ushort Speed;
public ushort Accel;
}
/// <summary>上传数据,对应 Axis2UploadData(13 字节载荷)。</summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Axis2UploadData
{
public byte SysSta;
public short XPos;
public short YPos;
public short ZPos;
public byte XSta;
public byte YSta;
public byte ZSta;
public byte Error;
public byte HwVersion;
public byte SwVersion;
}
}
@@ -0,0 +1,70 @@
namespace HardwareControl.Core.AxisPlatform
{
/// <summary>
/// 帧头类型,对应 AXIS_HEAD_*。
/// </summary>
public enum AxisPlatformHeadType : byte
{
/// <summary>台式自聚焦二维平台(0x7A)。</summary>
Desktop2D = 0x7A,
/// <summary>传送带三维平台(0x7B)。</summary>
Conveyor3D = 0x7B,
}
/// <summary>
/// 位移台配置,对应 appsettings.json 的 "AxisStage" 节。
/// 串口优先从系统参数 translation_com 读取,未配置时才使用 <see cref="ComPort"/>。
/// </summary>
public sealed class AxisStageOptions
{
public const string SectionName = "AxisStage";
/// <summary>
/// 回退串口名(例如 "COM5"),仅当系统参数 translation_com 为空时使用。
/// </summary>
public string? ComPort { get; set; }
/// <summary>帧头类型,默认台式二维平台。</summary>
public AxisPlatformHeadType FrameHead { get; set; } = AxisPlatformHeadType.Desktop2D;
/// <summary>未显式传参时使用的默认速度。</summary>
public ushort DefaultSpeed { get; set; } = 50;
/// <summary>未显式传参时使用的默认加速度。</summary>
public ushort DefaultAccel { get; set; } = 10;
/// <summary>限位参数;为 null 时不限位(向 DLL 传 NULL)。</summary>
public AxisStageLimits? Limits { get; set; }
/// <summary>读取上传数据的默认超时,单位毫秒。</summary>
public int ReadTimeoutMs { get; set; } = 1000;
/// <summary>读取上传数据失败时的重试间隔,单位毫秒。</summary>
public int ReadRetryIntervalMs { get; set; } = 50;
}
/// <summary>
/// 位移台限位参数(单位 mm)。仅在配置了 "Limits" 节时生效,
/// 未配置的轴使用足够大的范围,等效于该轴不限位。
/// </summary>
public sealed class AxisStageLimits
{
public int XPositive { get; set; } = 1_000_000;
public int XNegative { get; set; } = -1_000_000;
public int YPositive { get; set; } = 1_000_000;
public int YNegative { get; set; } = -1_000_000;
public int ZPositive { get; set; } = 1_000_000;
public int ZNegative { get; set; } = -1_000_000;
internal Axis2Limits ToNative() => new()
{
XPosLimit = XPositive,
XNegLimit = XNegative,
YPosLimit = YPositive,
YNegLimit = YNegative,
ZPosLimit = ZPositive,
ZNegLimit = ZNegative,
};
}
}
@@ -0,0 +1,8 @@
namespace HardwareControl.Core.AxisPlatform
{
/// <summary>三轴坐标/位移,单位 mm。</summary>
public readonly record struct AxisStagePoint(int X, int Y, int Z)
{
public static AxisStagePoint Zero => new(0, 0, 0);
}
}
@@ -0,0 +1,33 @@
namespace HardwareControl.Core.AxisPlatform
{
/// <summary>
/// 位移台上传帧(0xF5)的解析结果。
/// </summary>
/// <param name="XPosition">X 轴当前位置(mm)。</param>
/// <param name="YPosition">Y 轴当前位置(mm)。</param>
/// <param name="ZPosition">Z 轴当前位置(mm)。</param>
/// <param name="XMoving">X 轴是否运动中。</param>
/// <param name="YMoving">Y 轴是否运动中。</param>
/// <param name="ZMoving">Z 轴是否运动中。</param>
/// <param name="IsDebugMode">设备是否处于 Debug 模式(sys_sta 非 0)。</param>
/// <param name="DeviceError">设备端错误码。</param>
/// <param name="HardwareVersion">硬件版本号。</param>
/// <param name="SoftwareVersion">软件版本号。</param>
/// <param name="ReceivedAt">本机解析到该帧的时间。</param>
public sealed record AxisStageStatus(
int XPosition,
int YPosition,
int ZPosition,
bool XMoving,
bool YMoving,
bool ZMoving,
bool IsDebugMode,
int DeviceError,
int HardwareVersion,
int SoftwareVersion,
DateTimeOffset ReceivedAt)
{
/// <summary>是否有任意轴仍在运动。</summary>
public bool AnyMoving => XMoving || YMoving || ZMoving;
}
}
@@ -0,0 +1,14 @@
namespace HardwareControl.Core.AxisPlatform
{
public class AxisStageStatusChangedEventArgs : EventArgs
{
public bool IsConnected { get; }
public string Message { get; }
public AxisStageStatusChangedEventArgs(bool isConnected, string message)
{
IsConnected = isConnected;
Message = message;
}
}
}
@@ -0,0 +1,30 @@
namespace HardwareControl.Core.FocusSystem
{
/// <summary>实时应答类型,对应 Focus2RealTimeResp.type。</summary>
public enum FocusRealTimeResultType
{
/// <summary>消息应答(0x01),命令执行回执。</summary>
MessageAck = 0x01,
/// <summary>运行结果(0x02)。</summary>
RunningResult = 0x02,
/// <summary>查询结果(0x03),如同步延时获取。</summary>
QueryResult = 0x03,
Unknown = 0xFF,
}
/// <summary>设备缓存的运行结果/查询结果(focus_query_result)。</summary>
/// <param name="Type">应答类型。</param>
/// <param name="Success">执行状态是否为成功(sta=0x01)。</param>
/// <param name="DeviceError">设备端错误码。</param>
/// <param name="Data">附加数据;仅查询结果(0x03)携带,其余为 null。</param>
/// <param name="ReceivedAt">本机解析到该帧的时间。</param>
public sealed record FocusRealTimeResult(
FocusRealTimeResultType Type,
bool Success,
int DeviceError,
int? Data,
DateTimeOffset ReceivedAt);
}
@@ -0,0 +1,11 @@
namespace HardwareControl.Core.FocusSystem
{
/// <summary>
/// 光谱仪同步延时参数(对应 Focus2SyncTimeParams),单位微秒。
/// </summary>
public sealed record FocusSyncTime(
ushort DelayUs,
ushort OffsetUs,
ushort HoldUs,
ushort HoldOffsetUs);
}
@@ -0,0 +1,169 @@
using System.Runtime.InteropServices;
namespace HardwareControl.Core.FocusSystem
{
/// <summary>
/// FocusSystem2.dll 的 P/Invoke 声明。
/// 所有结构体按 C 端 #pragma pack(1) 布局,字段顺序与 focus_system2.h 一致。
/// 除查询类函数外,命令函数内部已完成"组包→发送→收应答"。
/// </summary>
internal static class FocusSystemNative
{
private const string DllName = "FocusSystem2.dll";
// 错误码,对应 FOCUS2_ERR_*
internal const int Ok = 0;
internal const int ErrNullPtr = -1;
internal const int ErrBufTooSmall = -2;
internal const int ErrFrameTooShort = -3;
internal const int ErrComOpenFailed = -4;
internal const int ErrComNotOpen = -5;
internal const int ErrComSendFailed = -6;
internal const int ErrParseFailed = -7;
internal const int ErrTimeout = -8;
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern IntPtr focus_init([MarshalAs(UnmanagedType.LPStr)] string comPort);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void focus_close(IntPtr handle);
// ---------- 对焦 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_single_focus(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_continuous_focus(IntPtr handle);
// ---------- 校准 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_calib_mode(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_calib_move(IntPtr handle, sbyte distance, ushort speed);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_calib_save(IntPtr handle);
// ---------- 激光器 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_laser_on(IntPtr handle, byte freq);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_laser_off(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_laser_power(IntPtr handle, byte power);
// ---------- 测距 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_single_range(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_continuous_range(IntPtr handle);
// ---------- 升降机构 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_lift_control(IntPtr handle, sbyte position);
// ---------- 外部触发 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_ext_trigger_set(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_ext_trigger_fire(IntPtr handle);
// ---------- 自动检测 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_auto_descend(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_fixed_cycle(IntPtr handle, ushort timeMs, ushort count);
// ---------- 光谱仪同步 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_sync_time_set(
IntPtr handle,
ref Focus2SyncTimeParams parameters);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_sync_time_get(IntPtr handle);
// ---------- 电源 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_power_off(IntPtr handle);
// ---------- 查询 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_read_sys_info(IntPtr handle, out Focus2SysInfo info);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int focus_query_result(IntPtr handle, out Focus2RealTimeResp result);
// ---------- 错误 ----------
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr focus_get_error(IntPtr handle);
/// <summary>读取 DLL 内部记录的最后一次错误描述;无错误或句柄为空时返回空串。</summary>
internal static string GetError(IntPtr handle)
{
if (handle == IntPtr.Zero)
{
return string.Empty;
}
var pointer = focus_get_error(handle);
return pointer == IntPtr.Zero
? string.Empty
: Marshal.PtrToStringAnsi(pointer) ?? string.Empty;
}
}
/// <summary>系统信息,对应 Focus2SysInfo(15 字节载荷)。</summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Focus2SysInfo
{
public byte SysSta;
public ushort FocusPos;
public byte Error;
public sbyte Location;
public byte LaserSta;
public byte Voltage;
public ushort ExtVoltage;
public byte HwVersion;
public byte SwVersion;
public ushort StartTime;
public ushort SyncTime;
}
/// <summary>实时应答,对应 Focus2RealTimeResp(3~5 字节载荷)。</summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Focus2RealTimeResp
{
public byte Type;
public byte Sta;
public byte Error;
public ushort Data;
}
/// <summary>光谱仪同步参数,对应 Focus2SyncTimeParams(8 字节)。</summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Focus2SyncTimeParams
{
public ushort DelayUs;
public ushort OffsetUs;
public ushort HoldUs;
public ushort HoldOffsetUs;
}
}
@@ -0,0 +1,25 @@
namespace HardwareControl.Core.FocusSystem
{
/// <summary>
/// 定焦系统配置,对应 appsettings.json 的 "FocusSystem" 节。
/// 串口优先从系统参数 focus_com 读取,未配置时才使用 <see cref="ComPort"/>。
/// </summary>
public sealed class FocusSystemOptions
{
public const string SectionName = "FocusSystem";
/// <summary>
/// 回退串口名(例如 "COM6"),仅当系统参数 focus_com 为空时使用。
/// </summary>
public string? ComPort { get; set; }
/// <summary>校准位移未显式传速度时使用的默认速度。</summary>
public ushort DefaultCalibrationSpeed { get; set; } = 50;
/// <summary>读取系统信息/运行结果的默认超时,单位毫秒。</summary>
public int ReadTimeoutMs { get; set; } = 1000;
/// <summary>读取失败时的重试间隔,单位毫秒。</summary>
public int ReadRetryIntervalMs { get; set; } = 100;
}
}
@@ -0,0 +1,43 @@
namespace HardwareControl.Core.FocusSystem
{
/// <summary>
/// 定焦系统上传的系统信息(0xF5)解析结果。
/// </summary>
/// <param name="FocusPosition">对焦校准位置。</param>
/// <param name="Error">设备端错误码:0=无错误,11=测距超时,12=超负极限,13=超正极限。</param>
/// <param name="ErrorDescription">错误码的中文描述。</param>
/// <param name="Location">滑台位置。</param>
/// <param name="LaserOnline">激光器是否在线。</param>
/// <param name="VoltageVolts">电源电压(V)。</param>
/// <param name="ExtendedVoltageVolts">扩展板电压(V)。</param>
/// <param name="HardwareVersion">硬件版本号。</param>
/// <param name="SoftwareVersion">软件版本号。</param>
/// <param name="StartTimeMinutes">开机时间(分钟)。</param>
/// <param name="SyncTime">同步延时。</param>
/// <param name="IsDebugMode">是否处于 Debug 模式(sys_sta 非 0)。</param>
/// <param name="ReceivedAt">本机解析到该帧的时间。</param>
public sealed record FocusSystemStatus(
int FocusPosition,
int Error,
string ErrorDescription,
int Location,
bool LaserOnline,
double VoltageVolts,
double ExtendedVoltageVolts,
int HardwareVersion,
int SoftwareVersion,
int StartTimeMinutes,
int SyncTime,
bool IsDebugMode,
DateTimeOffset ReceivedAt)
{
public static string DescribeError(int error) => error switch
{
0 => "无错误",
11 => "测距超时",
12 => "超负极限",
13 => "超正极限",
_ => $"未知错误({error})",
};
}
}
@@ -0,0 +1,14 @@
namespace HardwareControl.Core.FocusSystem
{
public class FocusSystemStatusChangedEventArgs : EventArgs
{
public bool IsConnected { get; }
public string Message { get; }
public FocusSystemStatusChangedEventArgs(bool isConnected, string message)
{
IsConnected = isConnected;
Message = message;
}
}
}
@@ -37,6 +37,18 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
<!-- 位移台原生库,P/Invoke 按文件名加载,必须位于可执行文件同目录 -->
<None Update="dll\AxisPlatform2.dll">
<Link>AxisPlatform2.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
<!-- 对焦系统原生库,P/Invoke 按文件名加载,必须位于可执行文件同目录 -->
<None Update="dll\FocusSystem2.dll">
<Link>FocusSystem2.dll</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
@@ -0,0 +1,69 @@
using HardwareControl.Core.AxisPlatform;
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
{
/// <summary>
/// 位移台(三轴运动平台)服务,封装 AxisPlatform2.dll。
///
/// 串口在连接时从系统参数 translation_com 读取,读取不到时回退到
/// appsettings.json 的 "AxisStage:ComPort"。所有原生调用串行执行,
/// 运动接口只负责下发命令,到位与否需通过 <see cref="ReadStatusAsync"/> 轮询。
/// </summary>
public interface IAxisStageService : IAsyncDisposable
{
/// <summary>串口是否已打开。</summary>
bool IsConnected { get; }
/// <summary>当前使用的串口名(已规范化为 "\\.\COMx");未连接时为 null。</summary>
string? PortName { get; }
Task ConnectAsync(CancellationToken ct = default);
Task DisconnectAsync(CancellationToken ct = default);
/// <summary>X 轴相对运动,正值为正向。</summary>
Task MoveXAsync(
int distanceMm,
int? speed = null,
int? accel = null,
CancellationToken ct = default);
/// <summary>Y 轴相对运动,正值为正向。</summary>
Task MoveYAsync(
int distanceMm,
int? speed = null,
int? accel = null,
CancellationToken ct = default);
/// <summary>Z 轴相对运动,正值为正向。</summary>
Task MoveZAsync(
int distanceMm,
int? speed = null,
int? accel = null,
CancellationToken ct = default);
/// <summary>三轴相对运动,三轴共用同一速度与加速度。</summary>
Task MoveRelativeAsync(
AxisStagePoint delta,
int? speed = null,
int? accel = null,
CancellationToken ct = default);
/// <summary>三轴绝对运动,<paramref name="target"/> 为目标位置坐标。</summary>
Task MoveAbsoluteAsync(
AxisStagePoint target,
int? speed = null,
int? accel = null,
CancellationToken ct = default);
/// <summary>
/// 读取设备最新上传帧(当前位置、运动状态、版本等)。
/// 内部会先清空串口缓冲,在 <paramref name="timeoutMs"/> 内重试直到收到有效帧。
/// </summary>
Task<AxisStageStatus> ReadStatusAsync(
int? timeoutMs = null,
CancellationToken ct = default);
event EventHandler<AxisStageStatusChangedEventArgs>? StatusChanged;
}
}
@@ -0,0 +1,126 @@
using HardwareControl.Core.FocusSystem;
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
{
/// <summary>
/// 定焦系统服务,封装 FocusSystem2.dll。
///
/// 串口在连接时从系统参数 focus_com 读取,读取不到时回退到
/// appsettings.json 的 "FocusSystem:ComPort"。命令函数内部已完成
/// "组包→发送→收应答",返回即表示设备已回执;运行结果与系统信息
/// 需通过 <see cref="ReadSystemInfoAsync"/> / <see cref="ReadResultAsync"/> 查询。
/// 所有原生调用串行执行。
/// </summary>
public interface IFocusSystemService : IAsyncDisposable
{
/// <summary>串口是否已打开。</summary>
bool IsConnected { get; }
/// <summary>当前使用的串口名(已规范化为 "\\.\COMx");未连接时为 null。</summary>
string? PortName { get; }
Task ConnectAsync(CancellationToken ct = default);
Task DisconnectAsync(CancellationToken ct = default);
// ---------- 对焦 ----------
/// <summary>单次对焦。</summary>
Task StartSingleFocusAsync(CancellationToken ct = default);
/// <summary>连续对焦。</summary>
Task StartContinuousFocusAsync(CancellationToken ct = default);
// ---------- 校准 ----------
/// <summary>进入校准模式。</summary>
Task EnterCalibrationModeAsync(CancellationToken ct = default);
/// <summary>校准滑台移动指定距离,正值为正向;速度为空时使用配置默认值。</summary>
Task MoveCalibrationAsync(
int distanceMm,
int? speed = null,
CancellationToken ct = default);
/// <summary>保存当前校准参数到设备存储器。</summary>
Task SaveCalibrationAsync(CancellationToken ct = default);
// ---------- 激光器 ----------
/// <summary>激光器按指定频率出光。</summary>
Task TurnLaserOnAsync(byte frequency, CancellationToken ct = default);
/// <summary>立即关闭激光器。</summary>
Task TurnLaserOffAsync(CancellationToken ct = default);
/// <summary>设置激光能量值(0~255)。</summary>
Task SetLaserPowerAsync(byte power, CancellationToken ct = default);
// ---------- 测距 ----------
/// <summary>触发激光传感器执行一次测距。</summary>
Task StartSingleRangeAsync(CancellationToken ct = default);
/// <summary>激光传感器进入连续测距模式。</summary>
Task StartContinuousRangeAsync(CancellationToken ct = default);
// ---------- 升降机构 ----------
/// <summary>升降机构到达指定位置,正值为上升。</summary>
Task ControlLiftAsync(int position, CancellationToken ct = default);
// ---------- 外部触发 ----------
/// <summary>配置外部触发参数。</summary>
Task SetExternalTriggerAsync(CancellationToken ct = default);
/// <summary>响应外部触发信号控制激光器出光。</summary>
Task FireExternalTriggerAsync(CancellationToken ct = default);
// ---------- 自动检测 ----------
/// <summary>启动自动下降检测流程。</summary>
Task StartAutoDescendAsync(CancellationToken ct = default);
/// <summary>按指定周期和次数循环出光。</summary>
Task StartFixedCycleAsync(
ushort intervalMs,
ushort count,
CancellationToken ct = default);
// ---------- 光谱仪同步 ----------
/// <summary>设置光谱仪同步延时参数。</summary>
Task SetSyncTimeAsync(
FocusSyncTime parameters,
CancellationToken ct = default);
/// <summary>请求设备返回当前同步延时,结果通过 <see cref="ReadResultAsync"/> 读取。</summary>
Task RequestSyncTimeAsync(CancellationToken ct = default);
// ---------- 电源 ----------
/// <summary>控制设备总电源关机。</summary>
Task PowerOffAsync(CancellationToken ct = default);
// ---------- 查询 ----------
/// <summary>
/// 读取系统信息(对焦位置、错误码、电压、版本等)。
/// 在 <paramref name="timeoutMs"/> 内重试直到收到有效帧。
/// </summary>
Task<FocusSystemStatus> ReadSystemInfoAsync(
int? timeoutMs = null,
CancellationToken ct = default);
/// <summary>
/// 读取设备缓存的运行结果/查询结果(type=0x02/0x03)。
/// 在 <paramref name="timeoutMs"/> 内轮询直到收到结果帧。
/// </summary>
Task<FocusRealTimeResult> ReadResultAsync(
int? timeoutMs = null,
CancellationToken ct = default);
event EventHandler<FocusSystemStatusChangedEventArgs>? StatusChanged;
}
}
@@ -0,0 +1,654 @@
using System.Runtime.InteropServices;
using HardwareControl.Core.AxisPlatform;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HardwareControl.Core.HardwareServiceImpl
{
/// <summary>
/// 位移台服务实现:AxisPlatform2.dll 负责串口与协议,
/// 本类负责串口参数解析、调用串行化、错误映射与日志。
/// </summary>
public sealed class AxisStageService : IAxisStageService
{
// 系统参数中保存位移台串口的配置名称
private const string ComPortConfigName = "translation_com";
private readonly AxisStageOptions _options;
private readonly ILogger<AxisStageService> _logger;
private readonly ISystemConfigService? _systemConfig;
// 串行化所有原生调用,DLL 句柄不支持并发访问
private readonly SemaphoreSlim _gate = new(1, 1);
private IntPtr _handle = IntPtr.Zero;
private volatile bool _connected;
private volatile string? _portName;
private bool _disposed;
public AxisStageService(
IOptions<AxisStageOptions> options,
ILogger<AxisStageService> logger,
ISystemConfigService? systemConfig = null)
{
_options = options.Value;
_logger = logger;
_systemConfig = systemConfig;
}
public bool IsConnected => _connected;
public string? PortName => _portName;
public event EventHandler<AxisStageStatusChangedEventArgs>? StatusChanged;
// ---------- 连接 ----------
public async Task ConnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
if (_connected)
{
return;
}
await Task.Run(ConnectCore, CancellationToken.None).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private void ConnectCore()
{
var port = ResolvePort();
var limitsPointer = IntPtr.Zero;
try
{
if (_options.Limits is { } limits)
{
var native = limits.ToNative();
limitsPointer = Marshal.AllocHGlobal(Marshal.SizeOf<Axis2Limits>());
Marshal.StructureToPtr(native, limitsPointer, false);
}
_logger.LogInformation(
"正在打开位移台串口 {Port}(帧头 {FrameHead})",
port,
_options.FrameHead);
var handle = AxisPlatformNative.axis_init(
port,
(byte)_options.FrameHead,
limitsPointer);
if (handle == IntPtr.Zero)
{
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
$"打开位移台串口 {port} 失败:串口不存在或被占用");
}
_handle = handle;
_connected = true;
_portName = port;
_logger.LogInformation("位移台串口已打开:{Port}", port);
StatusChanged?.Invoke(
this,
new AxisStageStatusChangedEventArgs(true, $"位移台已连接:{port}"));
}
catch (HardwareException)
{
ResetConnectionState();
throw;
}
catch (Exception ex) when (ex is DllNotFoundException
or BadImageFormatException
or EntryPointNotFoundException)
{
ResetConnectionState();
_logger.LogError(ex, "加载 AxisPlatform2.dll 失败");
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
BuildNativeLoadFailureMessage(ex),
ex);
}
catch (Exception ex)
{
ResetConnectionState();
_logger.LogError(ex, "打开位移台串口时发生未预期异常");
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
"连接位移台失败",
ex);
}
finally
{
if (limitsPointer != IntPtr.Zero)
{
Marshal.FreeHGlobal(limitsPointer);
}
}
}
/// <summary>
/// 串口优先取系统参数 translation_com;为空时回退到 appsettings 的 AxisStage:ComPort。
/// </summary>
private string ResolvePort()
{
string? configured = null;
try
{
configured = _systemConfig?
.GetAll()
.FirstOrDefault(config => string.Equals(
config.ConfigName,
ComPortConfigName,
StringComparison.OrdinalIgnoreCase))?
.ConfigValue?
.Trim();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", ComPortConfigName);
}
var port = !string.IsNullOrWhiteSpace(configured)
? configured
: _options.ComPort?.Trim();
if (string.IsNullOrWhiteSpace(port))
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"未配置位移台串口:请先在系统参数中添加 {ComPortConfigName}(例如 COM5)");
}
return SerialPortNames.Normalize(port);
}
// ---------- 断开 ----------
public async Task DisconnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_disposed)
{
return;
}
var wasConnected = _connected;
CloseHandle();
if (wasConnected)
{
_logger.LogInformation("位移台串口已关闭");
StatusChanged?.Invoke(
this,
new AxisStageStatusChangedEventArgs(false, "位移台已断开"));
}
}
finally
{
_gate.Release();
}
}
private void CloseHandle()
{
var handle = _handle;
ResetConnectionState();
if (handle == IntPtr.Zero)
{
return;
}
try
{
AxisPlatformNative.axis_close(handle);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "关闭位移台串口时发生异常");
}
}
private void ResetConnectionState()
{
_handle = IntPtr.Zero;
_connected = false;
_portName = null;
}
// ---------- 运动 ----------
public async Task MoveXAsync(
int distanceMm,
int? speed = null,
int? accel = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var distance = ToDistance(distanceMm, "X");
var (speedValue, accelValue) = ResolveMotion(speed, accel);
ct.ThrowIfCancellationRequested();
var result = AxisPlatformNative.axis_x_move(
handle, distance, speedValue, accelValue);
EnsureSuccess(handle, result, $"X 轴移动 {distance}mm");
_logger.LogInformation(
"位移台 X 轴移动:{Distance}mm,速度 {Speed},加速度 {Accel}",
distance,
speedValue,
accelValue);
}
finally
{
_gate.Release();
}
}
public async Task MoveYAsync(
int distanceMm,
int? speed = null,
int? accel = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var distance = ToDistance(distanceMm, "Y");
var (speedValue, accelValue) = ResolveMotion(speed, accel);
ct.ThrowIfCancellationRequested();
var result = AxisPlatformNative.axis_y_move(
handle, distance, speedValue, accelValue);
EnsureSuccess(handle, result, $"Y 轴移动 {distance}mm");
_logger.LogInformation(
"位移台 Y 轴移动:{Distance}mm,速度 {Speed},加速度 {Accel}",
distance,
speedValue,
accelValue);
}
finally
{
_gate.Release();
}
}
public async Task MoveZAsync(
int distanceMm,
int? speed = null,
int? accel = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var distance = ToDistance(distanceMm, "Z");
var (speedValue, accelValue) = ResolveMotion(speed, accel);
ct.ThrowIfCancellationRequested();
var result = AxisPlatformNative.axis_z_move(
handle, distance, speedValue, accelValue);
EnsureSuccess(handle, result, $"Z 轴移动 {distance}mm");
_logger.LogInformation(
"位移台 Z 轴移动:{Distance}mm,速度 {Speed},加速度 {Accel}",
distance,
speedValue,
accelValue);
}
finally
{
_gate.Release();
}
}
public async Task MoveRelativeAsync(
AxisStagePoint delta,
int? speed = null,
int? accel = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var (speedValue, accelValue) = ResolveMotion(speed, accel);
var x = ToParams(delta.X, speedValue, accelValue, "X");
var y = ToParams(delta.Y, speedValue, accelValue, "Y");
var z = ToParams(delta.Z, speedValue, accelValue, "Z");
ct.ThrowIfCancellationRequested();
var result = AxisPlatformNative.axis_xyz_rel_move(
handle, ref x, ref y, ref z);
EnsureSuccess(
handle,
result,
$"三轴相对运动(X={delta.X},Y={delta.Y},Z={delta.Z})");
_logger.LogInformation(
"位移台三轴相对运动:X={X},Y={Y},Z={Z},速度 {Speed},加速度 {Accel}",
delta.X,
delta.Y,
delta.Z,
speedValue,
accelValue);
}
finally
{
_gate.Release();
}
}
public async Task MoveAbsoluteAsync(
AxisStagePoint target,
int? speed = null,
int? accel = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var (speedValue, accelValue) = ResolveMotion(speed, accel);
var x = ToParams(target.X, speedValue, accelValue, "X");
var y = ToParams(target.Y, speedValue, accelValue, "Y");
var z = ToParams(target.Z, speedValue, accelValue, "Z");
ct.ThrowIfCancellationRequested();
var result = AxisPlatformNative.axis_xyz_abs_move(
handle, ref x, ref y, ref z);
EnsureSuccess(
handle,
result,
$"三轴绝对运动(X={target.X},Y={target.Y},Z={target.Z})");
_logger.LogInformation(
"位移台三轴绝对运动:X={X},Y={Y},Z={Z},速度 {Speed},加速度 {Accel}",
target.X,
target.Y,
target.Z,
speedValue,
accelValue);
}
finally
{
_gate.Release();
}
}
// ---------- 状态 ----------
public async Task<AxisStageStatus> ReadStatusAsync(
int? timeoutMs = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var timeout = timeoutMs ?? _options.ReadTimeoutMs;
if (timeout <= 0)
{
timeout = 1000;
}
return await Task.Run(
() => ReadStatusCore(handle, timeout, ct),
CancellationToken.None)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private AxisStageStatus ReadStatusCore(
IntPtr handle,
int timeoutMs,
CancellationToken ct)
{
// 丢弃旧缓存,确保读到的是设备新上传的帧
AxisPlatformNative.axis_flush(handle);
var deadline = Environment.TickCount64 + timeoutMs;
var retryInterval = Math.Clamp(_options.ReadRetryIntervalMs, 10, 1000);
while (true)
{
ct.ThrowIfCancellationRequested();
var result = AxisPlatformNative.axis_read_upload(handle, out var data);
if (result == AxisPlatformNative.Ok)
{
var status = MapStatus(data);
_logger.LogDebug(
"位移台状态:X={X},Y={Y},Z={Z},运动中={Moving},设备错误={Error}",
status.XPosition,
status.YPosition,
status.ZPosition,
status.AnyMoving,
status.DeviceError);
return status;
}
// 未收到数据/未找到上传帧时在超时时间内重试,其余错误立即抛出
if (result is not (AxisPlatformNative.ErrTimeout
or AxisPlatformNative.ErrParseFailed))
{
throw MapNativeError(handle, result, "读取位移台状态");
}
if (Environment.TickCount64 >= deadline)
{
var detail = result == AxisPlatformNative.ErrTimeout
? "未收到任何数据"
: "未找到有效的上传帧";
throw new HardwareException(
HardwareErrorKind.Timeout,
$"读取位移台状态超时({timeoutMs}ms):{detail}");
}
Thread.Sleep(retryInterval);
}
}
private static AxisStageStatus MapStatus(Axis2UploadData data) =>
new(
data.XPos,
data.YPos,
data.ZPos,
data.XSta != 0,
data.YSta != 0,
data.ZSta != 0,
data.SysSta != 0,
data.Error,
data.HwVersion,
data.SwVersion,
DateTimeOffset.Now);
// ---------- 参数校验与错误映射 ----------
private (ushort Speed, ushort Accel) ResolveMotion(int? speed, int? accel)
{
var speedValue = speed ?? _options.DefaultSpeed;
var accelValue = accel ?? _options.DefaultAccel;
if (speedValue is <= 0 or > ushort.MaxValue)
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"运行速度 {speedValue} 超出范围(1~{ushort.MaxValue})");
}
if (accelValue is <= 0 or > ushort.MaxValue)
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"加速度 {accelValue} 超出范围(1~{ushort.MaxValue})");
}
return ((ushort)speedValue, (ushort)accelValue);
}
private static short ToDistance(int value, string axis)
{
if (value is < short.MinValue or > short.MaxValue)
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"{axis} 轴位移 {value}mm 超出范围({short.MinValue}~{short.MaxValue})");
}
return (short)value;
}
private static Axis2MoveParams ToParams(
int value,
ushort speed,
ushort accel,
string axis) => new()
{
Distance = ToDistance(value, axis),
Speed = speed,
Accel = accel,
};
/// <summary>文档中运动函数的返回值可能为发送字节数,非负均视为成功。</summary>
private static void EnsureSuccess(IntPtr handle, int result, string operation)
{
if (result >= 0)
{
return;
}
throw MapNativeError(handle, result, operation);
}
private static HardwareException MapNativeError(
IntPtr handle,
int code,
string operation)
{
var kind = code switch
{
AxisPlatformNative.ErrNullPtr => HardwareErrorKind.InvalidArgument,
AxisPlatformNative.ErrBufTooSmall => HardwareErrorKind.InvalidArgument,
AxisPlatformNative.ErrFrameTooShort => HardwareErrorKind.CommunicationFailed,
AxisPlatformNative.ErrComOpenFailed => HardwareErrorKind.ConnectFailed,
AxisPlatformNative.ErrComNotOpen => HardwareErrorKind.NotConnected,
AxisPlatformNative.ErrComSendFailed => HardwareErrorKind.CommunicationFailed,
AxisPlatformNative.ErrParseFailed => HardwareErrorKind.CommunicationFailed,
AxisPlatformNative.ErrTimeout => HardwareErrorKind.Timeout,
_ => HardwareErrorKind.Unknown,
};
var hint = code switch
{
AxisPlatformNative.ErrComOpenFailed => "(串口不存在或被占用)",
AxisPlatformNative.ErrComNotOpen => "(串口尚未打开)",
AxisPlatformNative.ErrComSendFailed => "(可能是超出限位或串口发送失败)",
AxisPlatformNative.ErrParseFailed => "(CRC 校验失败或帧格式错误)",
AxisPlatformNative.ErrTimeout => "(未在指定时间内收到数据)",
_ => string.Empty,
};
var detail = AxisPlatformNative.GetError(handle);
var message = string.IsNullOrWhiteSpace(detail)
? $"{operation}失败{hint}(错误码 {code})"
: $"{operation}失败{hint}(错误码 {code}):{detail}";
return new HardwareException(kind, message);
}
private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch
{
DllNotFoundException =>
"加载 AxisPlatform2.dll 失败:请确认该 DLL 已复制到程序输出目录"
+ $"(当前目录:{AppContext.BaseDirectory})",
BadImageFormatException =>
"加载 AxisPlatform2.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行",
EntryPointNotFoundException =>
"加载 AxisPlatform2.dll 失败:DLL 版本与接口声明不匹配",
_ => "加载 AxisPlatform2.dll 失败",
};
// ---------- 释放 ----------
private IntPtr RequireHandle()
{
var handle = _handle;
if (!_connected || handle == IntPtr.Zero)
{
throw new HardwareException(
HardwareErrorKind.NotConnected,
"位移台尚未连接,请先调用连接接口");
}
return handle;
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
public async ValueTask DisposeAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed)
{
return;
}
_disposed = true;
CloseHandle();
}
finally
{
_gate.Release();
_gate.Dispose();
}
GC.SuppressFinalize(this);
}
}
}
@@ -0,0 +1,637 @@
using HardwareControl.Core.FocusSystem;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace HardwareControl.Core.HardwareServiceImpl
{
/// <summary>
/// 定焦系统服务实现:FocusSystem2.dll 负责串口与协议,
/// 本类负责串口参数解析、调用串行化、错误映射与日志。
/// </summary>
public sealed class FocusSystemService : IFocusSystemService
{
// 系统参数中保存对焦硬件串口的配置名称
private const string ComPortConfigName = "focus_com";
private readonly FocusSystemOptions _options;
private readonly ILogger<FocusSystemService> _logger;
private readonly ISystemConfigService? _systemConfig;
// 串行化所有原生调用,DLL 句柄不支持并发访问
private readonly SemaphoreSlim _gate = new(1, 1);
private IntPtr _handle = IntPtr.Zero;
private volatile bool _connected;
private volatile string? _portName;
private bool _disposed;
public FocusSystemService(
IOptions<FocusSystemOptions> options,
ILogger<FocusSystemService> logger,
ISystemConfigService? systemConfig = null)
{
_options = options.Value;
_logger = logger;
_systemConfig = systemConfig;
}
public bool IsConnected => _connected;
public string? PortName => _portName;
public event EventHandler<FocusSystemStatusChangedEventArgs>? StatusChanged;
// ---------- 连接 ----------
public async Task ConnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
if (_connected)
{
return;
}
await Task.Run(ConnectCore, CancellationToken.None).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private void ConnectCore()
{
var port = ResolvePort();
try
{
_logger.LogInformation("正在打开对焦系统串口 {Port}", port);
var handle = FocusSystemNative.focus_init(port);
if (handle == IntPtr.Zero)
{
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
$"打开对焦系统串口 {port} 失败:串口不存在或被占用");
}
_handle = handle;
_connected = true;
_portName = port;
_logger.LogInformation("对焦系统串口已打开:{Port}", port);
StatusChanged?.Invoke(
this,
new FocusSystemStatusChangedEventArgs(true, $"对焦系统已连接:{port}"));
}
catch (HardwareException)
{
ResetConnectionState();
throw;
}
catch (Exception ex) when (ex is DllNotFoundException
or BadImageFormatException
or EntryPointNotFoundException)
{
ResetConnectionState();
_logger.LogError(ex, "加载 FocusSystem2.dll 失败");
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
BuildNativeLoadFailureMessage(ex),
ex);
}
catch (Exception ex)
{
ResetConnectionState();
_logger.LogError(ex, "打开对焦系统串口时发生未预期异常");
throw new HardwareException(
HardwareErrorKind.ConnectFailed,
"连接对焦系统失败",
ex);
}
}
/// <summary>
/// 串口优先取系统参数 focus_com;为空时回退到 appsettings 的 FocusSystem:ComPort。
/// </summary>
private string ResolvePort()
{
string? configured = null;
try
{
configured = _systemConfig?
.GetAll()
.FirstOrDefault(config => string.Equals(
config.ConfigName,
ComPortConfigName,
StringComparison.OrdinalIgnoreCase))?
.ConfigValue?
.Trim();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "读取系统参数 {ConfigName} 失败", ComPortConfigName);
}
var port = !string.IsNullOrWhiteSpace(configured)
? configured
: _options.ComPort?.Trim();
if (string.IsNullOrWhiteSpace(port))
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"未配置对焦系统串口:请先在系统参数中添加 {ComPortConfigName}(例如 COM6)");
}
return SerialPortNames.Normalize(port);
}
// ---------- 断开 ----------
public async Task DisconnectAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_disposed)
{
return;
}
var wasConnected = _connected;
CloseHandle();
if (wasConnected)
{
_logger.LogInformation("对焦系统串口已关闭");
StatusChanged?.Invoke(
this,
new FocusSystemStatusChangedEventArgs(false, "对焦系统已断开"));
}
}
finally
{
_gate.Release();
}
}
private void CloseHandle()
{
var handle = _handle;
ResetConnectionState();
if (handle == IntPtr.Zero)
{
return;
}
try
{
FocusSystemNative.focus_close(handle);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "关闭对焦系统串口时发生异常");
}
}
private void ResetConnectionState()
{
_handle = IntPtr.Zero;
_connected = false;
_portName = null;
}
// ---------- 命令 ----------
public Task StartSingleFocusAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_single_focus, "单次对焦", ct);
public Task StartContinuousFocusAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_continuous_focus, "连续对焦", ct);
public Task EnterCalibrationModeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_calib_mode, "进入校准模式", ct);
public Task MoveCalibrationAsync(
int distanceMm,
int? speed = null,
CancellationToken ct = default)
{
var distance = ToInt8(distanceMm, "校准位移");
var speedValue = speed ?? _options.DefaultCalibrationSpeed;
if (speedValue is <= 0 or > ushort.MaxValue)
{
return Task.FromException(new HardwareException(
HardwareErrorKind.InvalidArgument,
$"校准速度 {speedValue} 超出范围(1~{ushort.MaxValue})"));
}
return ExecuteAsync(
handle => FocusSystemNative.focus_calib_move(
handle,
distance,
(ushort)speedValue),
$"校准位移 {distance}mm",
ct);
}
public Task SaveCalibrationAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_calib_save, "保存校准参数", ct);
public Task TurnLaserOnAsync(byte frequency, CancellationToken ct = default) =>
ExecuteAsync(
handle => FocusSystemNative.focus_laser_on(handle, frequency),
$"激光器出光(频率 {frequency}Hz)",
ct);
public Task TurnLaserOffAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_laser_off, "激光器关光", ct);
public Task SetLaserPowerAsync(byte power, CancellationToken ct = default) =>
ExecuteAsync(
handle => FocusSystemNative.focus_laser_power(handle, power),
$"设置激光能量 {power}",
ct);
public Task StartSingleRangeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_single_range, "单次测距", ct);
public Task StartContinuousRangeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_continuous_range, "连续测距", ct);
public Task ControlLiftAsync(int position, CancellationToken ct = default)
{
var target = ToInt8(position, "升降位置");
return ExecuteAsync(
handle => FocusSystemNative.focus_lift_control(handle, target),
$"升降机构移动到 {target}",
ct);
}
public Task SetExternalTriggerAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_ext_trigger_set, "外部触发设置", ct);
public Task FireExternalTriggerAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_ext_trigger_fire, "外部触发出光", ct);
public Task StartAutoDescendAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_auto_descend, "自动下降检测", ct);
public Task StartFixedCycleAsync(
ushort intervalMs,
ushort count,
CancellationToken ct = default) =>
ExecuteAsync(
handle => FocusSystemNative.focus_fixed_cycle(handle, intervalMs, count),
$"固定周期出光(周期 {intervalMs}ms,{count} 次)",
ct);
public Task SetSyncTimeAsync(
FocusSyncTime parameters,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(parameters);
var native = new Focus2SyncTimeParams
{
DelayUs = parameters.DelayUs,
OffsetUs = parameters.OffsetUs,
HoldUs = parameters.HoldUs,
HoldOffsetUs = parameters.HoldOffsetUs,
};
return ExecuteAsync(
handle => FocusSystemNative.focus_sync_time_set(handle, ref native),
"设置光谱仪同步延时",
ct);
}
public Task RequestSyncTimeAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_sync_time_get, "获取光谱仪同步延时", ct);
public Task PowerOffAsync(CancellationToken ct = default) =>
ExecuteAsync(FocusSystemNative.focus_power_off, "总电源关机", ct);
private async Task ExecuteAsync(
Func<IntPtr, int> command,
string operation,
CancellationToken ct)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
ct.ThrowIfCancellationRequested();
// 命令内部会等待设备应答,放到线程池避免占用请求线程
var result = await Task.Run(
() => command(handle),
CancellationToken.None)
.ConfigureAwait(false);
EnsureSuccess(handle, result, operation);
_logger.LogInformation("对焦系统:{Operation}完成", operation);
}
finally
{
_gate.Release();
}
}
// ---------- 查询 ----------
public async Task<FocusSystemStatus> ReadSystemInfoAsync(
int? timeoutMs = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var timeout = NormalizeTimeout(timeoutMs);
return await Task.Run(
() => ReadSystemInfoCore(handle, timeout, ct),
CancellationToken.None)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private FocusSystemStatus ReadSystemInfoCore(
IntPtr handle,
int timeoutMs,
CancellationToken ct)
{
var deadline = Environment.TickCount64 + timeoutMs;
var retryInterval = ResolveRetryInterval();
while (true)
{
ct.ThrowIfCancellationRequested();
var result = FocusSystemNative.focus_read_sys_info(handle, out var info);
if (result == FocusSystemNative.Ok)
{
var status = MapStatus(info);
_logger.LogDebug(
"对焦系统信息:位置={Position},错误={Error},激光在线={LaserOnline},电压={Voltage:F1}V",
status.FocusPosition,
status.Error,
status.LaserOnline,
status.VoltageVolts);
return status;
}
// 未收到应答/解析失败时在超时时间内重试,其余错误立即抛出
if (result is not (FocusSystemNative.ErrTimeout
or FocusSystemNative.ErrParseFailed))
{
throw MapNativeError(handle, result, "读取对焦系统信息");
}
if (Environment.TickCount64 >= deadline)
{
var detail = result == FocusSystemNative.ErrTimeout
? "未收到应答"
: "CRC 校验失败或载荷不足";
throw new HardwareException(
HardwareErrorKind.Timeout,
$"读取对焦系统信息超时({timeoutMs}ms):{detail}");
}
Thread.Sleep(retryInterval);
}
}
public async Task<FocusRealTimeResult> ReadResultAsync(
int? timeoutMs = null,
CancellationToken ct = default)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
ThrowIfDisposed();
var handle = RequireHandle();
var timeout = NormalizeTimeout(timeoutMs);
return await Task.Run(
() => ReadResultCore(handle, timeout, ct),
CancellationToken.None)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
private FocusRealTimeResult ReadResultCore(
IntPtr handle,
int timeoutMs,
CancellationToken ct)
{
var deadline = Environment.TickCount64 + timeoutMs;
var retryInterval = ResolveRetryInterval();
while (true)
{
ct.ThrowIfCancellationRequested();
var result = FocusSystemNative.focus_query_result(handle, out var response);
if (result == FocusSystemNative.Ok)
{
return MapResult(response);
}
// 非阻塞查询,未找到结果帧时继续轮询
if (result != FocusSystemNative.ErrTimeout)
{
throw MapNativeError(handle, result, "查询对焦系统结果");
}
if (Environment.TickCount64 >= deadline)
{
throw new HardwareException(
HardwareErrorKind.Timeout,
$"查询对焦系统结果超时({timeoutMs}ms):未找到结果帧");
}
Thread.Sleep(retryInterval);
}
}
private static FocusSystemStatus MapStatus(Focus2SysInfo info) =>
new(
info.FocusPos,
info.Error,
FocusSystemStatus.DescribeError(info.Error),
info.Location,
info.LaserSta != 0,
info.Voltage / 10.0,
info.ExtVoltage / 10.0,
info.HwVersion,
info.SwVersion,
info.StartTime,
info.SyncTime,
info.SysSta != 0,
DateTimeOffset.Now);
private static FocusRealTimeResult MapResult(Focus2RealTimeResp response)
{
var type = response.Type switch
{
0x01 => FocusRealTimeResultType.MessageAck,
0x02 => FocusRealTimeResultType.RunningResult,
0x03 => FocusRealTimeResultType.QueryResult,
_ => FocusRealTimeResultType.Unknown,
};
return new FocusRealTimeResult(
type,
response.Sta == 0x01,
response.Error,
type == FocusRealTimeResultType.QueryResult ? response.Data : null,
DateTimeOffset.Now);
}
// ---------- 参数校验与错误映射 ----------
private int NormalizeTimeout(int? timeoutMs)
{
var timeout = timeoutMs ?? _options.ReadTimeoutMs;
return timeout > 0 ? timeout : 1000;
}
private int ResolveRetryInterval() =>
Math.Clamp(_options.ReadRetryIntervalMs, 10, 1000);
private static sbyte ToInt8(int value, string name)
{
if (value is < sbyte.MinValue or > sbyte.MaxValue)
{
throw new HardwareException(
HardwareErrorKind.InvalidArgument,
$"{name} {value} 超出范围({sbyte.MinValue}~{sbyte.MaxValue})");
}
return (sbyte)value;
}
/// <summary>命令返回 FOCUS2_OK(0) 表示成功,非 0 时按错误映射。</summary>
private static void EnsureSuccess(IntPtr handle, int result, string operation)
{
if (result >= 0)
{
return;
}
throw MapNativeError(handle, result, operation);
}
private static HardwareException MapNativeError(
IntPtr handle,
int code,
string operation)
{
var kind = code switch
{
FocusSystemNative.ErrNullPtr => HardwareErrorKind.InvalidArgument,
FocusSystemNative.ErrBufTooSmall => HardwareErrorKind.InvalidArgument,
FocusSystemNative.ErrFrameTooShort => HardwareErrorKind.CommunicationFailed,
FocusSystemNative.ErrComOpenFailed => HardwareErrorKind.ConnectFailed,
FocusSystemNative.ErrComNotOpen => HardwareErrorKind.NotConnected,
FocusSystemNative.ErrComSendFailed => HardwareErrorKind.CommunicationFailed,
FocusSystemNative.ErrParseFailed => HardwareErrorKind.CommunicationFailed,
FocusSystemNative.ErrTimeout => HardwareErrorKind.Timeout,
_ => HardwareErrorKind.Unknown,
};
var hint = code switch
{
FocusSystemNative.ErrComOpenFailed => "(串口不存在或被占用)",
FocusSystemNative.ErrComNotOpen => "(串口尚未打开)",
FocusSystemNative.ErrComSendFailed => "(设备返回失败应答或串口发送失败)",
FocusSystemNative.ErrParseFailed => "(CRC 校验失败或载荷不足)",
FocusSystemNative.ErrTimeout => "(未收到应答)",
_ => string.Empty,
};
var detail = FocusSystemNative.GetError(handle);
var message = string.IsNullOrWhiteSpace(detail)
? $"{operation}失败{hint}(错误码 {code})"
: $"{operation}失败{hint}(错误码 {code}):{detail}";
return new HardwareException(kind, message);
}
private static string BuildNativeLoadFailureMessage(Exception ex) => ex switch
{
DllNotFoundException =>
"加载 FocusSystem2.dll 失败:请确认该 DLL 已复制到程序输出目录"
+ $"(当前目录:{AppContext.BaseDirectory})",
BadImageFormatException =>
"加载 FocusSystem2.dll 失败:DLL 位数与进程不匹配,请使用 x64 进程运行",
EntryPointNotFoundException =>
"加载 FocusSystem2.dll 失败:DLL 版本与接口声明不匹配",
_ => "加载 FocusSystem2.dll 失败",
};
// ---------- 释放 ----------
private IntPtr RequireHandle()
{
var handle = _handle;
if (!_connected || handle == IntPtr.Zero)
{
throw new HardwareException(
HardwareErrorKind.NotConnected,
"对焦系统尚未连接,请先调用连接接口");
}
return handle;
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
public async ValueTask DisposeAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed)
{
return;
}
_disposed = true;
CloseHandle();
}
finally
{
_gate.Release();
_gate.Dispose();
}
GC.SuppressFinalize(this);
}
}
}
+27
View File
@@ -0,0 +1,27 @@
namespace HardwareControl.Core
{
/// <summary>
/// 串口名规范化。原生库要求 Windows 设备路径 "\\.\COMx",
/// 同时兼容用户在系统参数里只填写 "COM5" 的情况。
/// </summary>
internal static class SerialPortNames
{
internal static string Normalize(string port)
{
var value = port.Trim();
if (value.StartsWith(@"\\.\", StringComparison.Ordinal))
{
return value;
}
if (value.StartsWith("COM", StringComparison.OrdinalIgnoreCase) &&
int.TryParse(value.AsSpan(3), out _))
{
return @"\\.\" + value.ToUpperInvariant();
}
return value;
}
}
}
Binary file not shown.
Binary file not shown.