diff --git a/HardwareControl.Core/AxisPlatform/AxisPlatformNative.cs b/HardwareControl.Core/AxisPlatform/AxisPlatformNative.cs
new file mode 100644
index 0000000..44242f7
--- /dev/null
+++ b/HardwareControl.Core/AxisPlatform/AxisPlatformNative.cs
@@ -0,0 +1,116 @@
+using System.Runtime.InteropServices;
+
+namespace HardwareControl.Core.AxisPlatform
+{
+ ///
+ /// AxisPlatform2.dll 的 P/Invoke 声明。
+ /// 所有结构体按 C 端 #pragma pack(1) 布局,字段顺序与 axis_platform2.h 一致。
+ ///
+ 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);
+
+ /// 读取 DLL 内部记录的最后一次错误描述;无错误或句柄为空时返回空串。
+ 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;
+ }
+ }
+
+ /// 限位参数,对应 Axis2Limits(6 × int32)。
+ [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;
+ }
+
+ /// 单轴运动参数,对应 Axis2MoveParams(6 字节)。
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ internal struct Axis2MoveParams
+ {
+ public short Distance;
+ public ushort Speed;
+ public ushort Accel;
+ }
+
+ /// 上传数据,对应 Axis2UploadData(13 字节载荷)。
+ [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;
+ }
+}
diff --git a/HardwareControl.Core/AxisPlatform/AxisStageOptions.cs b/HardwareControl.Core/AxisPlatform/AxisStageOptions.cs
new file mode 100644
index 0000000..0848f4f
--- /dev/null
+++ b/HardwareControl.Core/AxisPlatform/AxisStageOptions.cs
@@ -0,0 +1,70 @@
+namespace HardwareControl.Core.AxisPlatform
+{
+ ///
+ /// 帧头类型,对应 AXIS_HEAD_*。
+ ///
+ public enum AxisPlatformHeadType : byte
+ {
+ /// 台式自聚焦二维平台(0x7A)。
+ Desktop2D = 0x7A,
+
+ /// 传送带三维平台(0x7B)。
+ Conveyor3D = 0x7B,
+ }
+
+ ///
+ /// 位移台配置,对应 appsettings.json 的 "AxisStage" 节。
+ /// 串口优先从系统参数 translation_com 读取,未配置时才使用 。
+ ///
+ public sealed class AxisStageOptions
+ {
+ public const string SectionName = "AxisStage";
+
+ ///
+ /// 回退串口名(例如 "COM5"),仅当系统参数 translation_com 为空时使用。
+ ///
+ public string? ComPort { get; set; }
+
+ /// 帧头类型,默认台式二维平台。
+ public AxisPlatformHeadType FrameHead { get; set; } = AxisPlatformHeadType.Desktop2D;
+
+ /// 未显式传参时使用的默认速度。
+ public ushort DefaultSpeed { get; set; } = 50;
+
+ /// 未显式传参时使用的默认加速度。
+ public ushort DefaultAccel { get; set; } = 10;
+
+ /// 限位参数;为 null 时不限位(向 DLL 传 NULL)。
+ public AxisStageLimits? Limits { get; set; }
+
+ /// 读取上传数据的默认超时,单位毫秒。
+ public int ReadTimeoutMs { get; set; } = 1000;
+
+ /// 读取上传数据失败时的重试间隔,单位毫秒。
+ public int ReadRetryIntervalMs { get; set; } = 50;
+ }
+
+ ///
+ /// 位移台限位参数(单位 mm)。仅在配置了 "Limits" 节时生效,
+ /// 未配置的轴使用足够大的范围,等效于该轴不限位。
+ ///
+ 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,
+ };
+ }
+}
diff --git a/HardwareControl.Core/AxisPlatform/AxisStagePoint.cs b/HardwareControl.Core/AxisPlatform/AxisStagePoint.cs
new file mode 100644
index 0000000..ff50da4
--- /dev/null
+++ b/HardwareControl.Core/AxisPlatform/AxisStagePoint.cs
@@ -0,0 +1,8 @@
+namespace HardwareControl.Core.AxisPlatform
+{
+ /// 三轴坐标/位移,单位 mm。
+ public readonly record struct AxisStagePoint(int X, int Y, int Z)
+ {
+ public static AxisStagePoint Zero => new(0, 0, 0);
+ }
+}
diff --git a/HardwareControl.Core/AxisPlatform/AxisStageStatus.cs b/HardwareControl.Core/AxisPlatform/AxisStageStatus.cs
new file mode 100644
index 0000000..82780d2
--- /dev/null
+++ b/HardwareControl.Core/AxisPlatform/AxisStageStatus.cs
@@ -0,0 +1,33 @@
+namespace HardwareControl.Core.AxisPlatform
+{
+ ///
+ /// 位移台上传帧(0xF5)的解析结果。
+ ///
+ /// X 轴当前位置(mm)。
+ /// Y 轴当前位置(mm)。
+ /// Z 轴当前位置(mm)。
+ /// X 轴是否运动中。
+ /// Y 轴是否运动中。
+ /// Z 轴是否运动中。
+ /// 设备是否处于 Debug 模式(sys_sta 非 0)。
+ /// 设备端错误码。
+ /// 硬件版本号。
+ /// 软件版本号。
+ /// 本机解析到该帧的时间。
+ 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)
+ {
+ /// 是否有任意轴仍在运动。
+ public bool AnyMoving => XMoving || YMoving || ZMoving;
+ }
+}
diff --git a/HardwareControl.Core/AxisPlatform/AxisStageStatusChangedEventArgs.cs b/HardwareControl.Core/AxisPlatform/AxisStageStatusChangedEventArgs.cs
new file mode 100644
index 0000000..1b97f41
--- /dev/null
+++ b/HardwareControl.Core/AxisPlatform/AxisStageStatusChangedEventArgs.cs
@@ -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;
+ }
+ }
+}
diff --git a/HardwareControl.Core/FocusSystem/FocusRealTimeResult.cs b/HardwareControl.Core/FocusSystem/FocusRealTimeResult.cs
new file mode 100644
index 0000000..c3f598f
--- /dev/null
+++ b/HardwareControl.Core/FocusSystem/FocusRealTimeResult.cs
@@ -0,0 +1,30 @@
+namespace HardwareControl.Core.FocusSystem
+{
+ /// 实时应答类型,对应 Focus2RealTimeResp.type。
+ public enum FocusRealTimeResultType
+ {
+ /// 消息应答(0x01),命令执行回执。
+ MessageAck = 0x01,
+
+ /// 运行结果(0x02)。
+ RunningResult = 0x02,
+
+ /// 查询结果(0x03),如同步延时获取。
+ QueryResult = 0x03,
+
+ Unknown = 0xFF,
+ }
+
+ /// 设备缓存的运行结果/查询结果(focus_query_result)。
+ /// 应答类型。
+ /// 执行状态是否为成功(sta=0x01)。
+ /// 设备端错误码。
+ /// 附加数据;仅查询结果(0x03)携带,其余为 null。
+ /// 本机解析到该帧的时间。
+ public sealed record FocusRealTimeResult(
+ FocusRealTimeResultType Type,
+ bool Success,
+ int DeviceError,
+ int? Data,
+ DateTimeOffset ReceivedAt);
+}
diff --git a/HardwareControl.Core/FocusSystem/FocusSyncTime.cs b/HardwareControl.Core/FocusSystem/FocusSyncTime.cs
new file mode 100644
index 0000000..c78905f
--- /dev/null
+++ b/HardwareControl.Core/FocusSystem/FocusSyncTime.cs
@@ -0,0 +1,11 @@
+namespace HardwareControl.Core.FocusSystem
+{
+ ///
+ /// 光谱仪同步延时参数(对应 Focus2SyncTimeParams),单位微秒。
+ ///
+ public sealed record FocusSyncTime(
+ ushort DelayUs,
+ ushort OffsetUs,
+ ushort HoldUs,
+ ushort HoldOffsetUs);
+}
diff --git a/HardwareControl.Core/FocusSystem/FocusSystemNative.cs b/HardwareControl.Core/FocusSystem/FocusSystemNative.cs
new file mode 100644
index 0000000..e8cdf83
--- /dev/null
+++ b/HardwareControl.Core/FocusSystem/FocusSystemNative.cs
@@ -0,0 +1,169 @@
+using System.Runtime.InteropServices;
+
+namespace HardwareControl.Core.FocusSystem
+{
+ ///
+ /// FocusSystem2.dll 的 P/Invoke 声明。
+ /// 所有结构体按 C 端 #pragma pack(1) 布局,字段顺序与 focus_system2.h 一致。
+ /// 除查询类函数外,命令函数内部已完成"组包→发送→收应答"。
+ ///
+ 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);
+
+ /// 读取 DLL 内部记录的最后一次错误描述;无错误或句柄为空时返回空串。
+ 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;
+ }
+ }
+
+ /// 系统信息,对应 Focus2SysInfo(15 字节载荷)。
+ [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;
+ }
+
+ /// 实时应答,对应 Focus2RealTimeResp(3~5 字节载荷)。
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ internal struct Focus2RealTimeResp
+ {
+ public byte Type;
+ public byte Sta;
+ public byte Error;
+ public ushort Data;
+ }
+
+ /// 光谱仪同步参数,对应 Focus2SyncTimeParams(8 字节)。
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ internal struct Focus2SyncTimeParams
+ {
+ public ushort DelayUs;
+ public ushort OffsetUs;
+ public ushort HoldUs;
+ public ushort HoldOffsetUs;
+ }
+}
diff --git a/HardwareControl.Core/FocusSystem/FocusSystemOptions.cs b/HardwareControl.Core/FocusSystem/FocusSystemOptions.cs
new file mode 100644
index 0000000..a449922
--- /dev/null
+++ b/HardwareControl.Core/FocusSystem/FocusSystemOptions.cs
@@ -0,0 +1,25 @@
+namespace HardwareControl.Core.FocusSystem
+{
+ ///
+ /// 定焦系统配置,对应 appsettings.json 的 "FocusSystem" 节。
+ /// 串口优先从系统参数 focus_com 读取,未配置时才使用 。
+ ///
+ public sealed class FocusSystemOptions
+ {
+ public const string SectionName = "FocusSystem";
+
+ ///
+ /// 回退串口名(例如 "COM6"),仅当系统参数 focus_com 为空时使用。
+ ///
+ public string? ComPort { get; set; }
+
+ /// 校准位移未显式传速度时使用的默认速度。
+ public ushort DefaultCalibrationSpeed { get; set; } = 50;
+
+ /// 读取系统信息/运行结果的默认超时,单位毫秒。
+ public int ReadTimeoutMs { get; set; } = 1000;
+
+ /// 读取失败时的重试间隔,单位毫秒。
+ public int ReadRetryIntervalMs { get; set; } = 100;
+ }
+}
diff --git a/HardwareControl.Core/FocusSystem/FocusSystemStatus.cs b/HardwareControl.Core/FocusSystem/FocusSystemStatus.cs
new file mode 100644
index 0000000..f3293f2
--- /dev/null
+++ b/HardwareControl.Core/FocusSystem/FocusSystemStatus.cs
@@ -0,0 +1,43 @@
+namespace HardwareControl.Core.FocusSystem
+{
+ ///
+ /// 定焦系统上传的系统信息(0xF5)解析结果。
+ ///
+ /// 对焦校准位置。
+ /// 设备端错误码:0=无错误,11=测距超时,12=超负极限,13=超正极限。
+ /// 错误码的中文描述。
+ /// 滑台位置。
+ /// 激光器是否在线。
+ /// 电源电压(V)。
+ /// 扩展板电压(V)。
+ /// 硬件版本号。
+ /// 软件版本号。
+ /// 开机时间(分钟)。
+ /// 同步延时。
+ /// 是否处于 Debug 模式(sys_sta 非 0)。
+ /// 本机解析到该帧的时间。
+ 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})",
+ };
+ }
+}
diff --git a/HardwareControl.Core/FocusSystem/FocusSystemStatusChangedEventArgs.cs b/HardwareControl.Core/FocusSystem/FocusSystemStatusChangedEventArgs.cs
new file mode 100644
index 0000000..aa56cbd
--- /dev/null
+++ b/HardwareControl.Core/FocusSystem/FocusSystemStatusChangedEventArgs.cs
@@ -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;
+ }
+ }
+}
diff --git a/HardwareControl.Core/HardwareControl.Core.csproj b/HardwareControl.Core/HardwareControl.Core.csproj
index 6b2d374..e3edb1b 100644
--- a/HardwareControl.Core/HardwareControl.Core.csproj
+++ b/HardwareControl.Core/HardwareControl.Core.csproj
@@ -37,6 +37,18 @@
PreserveNewest
PreserveNewest
+
+
+ AxisPlatform2.dll
+ PreserveNewest
+ PreserveNewest
+
+
+
+ FocusSystem2.dll
+ PreserveNewest
+ PreserveNewest
+
diff --git a/HardwareControl.Core/HardwareService/IAxisStageService.cs b/HardwareControl.Core/HardwareService/IAxisStageService.cs
new file mode 100644
index 0000000..120bc3f
--- /dev/null
+++ b/HardwareControl.Core/HardwareService/IAxisStageService.cs
@@ -0,0 +1,69 @@
+using HardwareControl.Core.AxisPlatform;
+
+namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
+{
+ ///
+ /// 位移台(三轴运动平台)服务,封装 AxisPlatform2.dll。
+ ///
+ /// 串口在连接时从系统参数 translation_com 读取,读取不到时回退到
+ /// appsettings.json 的 "AxisStage:ComPort"。所有原生调用串行执行,
+ /// 运动接口只负责下发命令,到位与否需通过 轮询。
+ ///
+ public interface IAxisStageService : IAsyncDisposable
+ {
+ /// 串口是否已打开。
+ bool IsConnected { get; }
+
+ /// 当前使用的串口名(已规范化为 "\\.\COMx");未连接时为 null。
+ string? PortName { get; }
+
+ Task ConnectAsync(CancellationToken ct = default);
+
+ Task DisconnectAsync(CancellationToken ct = default);
+
+ /// X 轴相对运动,正值为正向。
+ Task MoveXAsync(
+ int distanceMm,
+ int? speed = null,
+ int? accel = null,
+ CancellationToken ct = default);
+
+ /// Y 轴相对运动,正值为正向。
+ Task MoveYAsync(
+ int distanceMm,
+ int? speed = null,
+ int? accel = null,
+ CancellationToken ct = default);
+
+ /// Z 轴相对运动,正值为正向。
+ Task MoveZAsync(
+ int distanceMm,
+ int? speed = null,
+ int? accel = null,
+ CancellationToken ct = default);
+
+ /// 三轴相对运动,三轴共用同一速度与加速度。
+ Task MoveRelativeAsync(
+ AxisStagePoint delta,
+ int? speed = null,
+ int? accel = null,
+ CancellationToken ct = default);
+
+ /// 三轴绝对运动, 为目标位置坐标。
+ Task MoveAbsoluteAsync(
+ AxisStagePoint target,
+ int? speed = null,
+ int? accel = null,
+ CancellationToken ct = default);
+
+ ///
+ /// 读取设备最新上传帧(当前位置、运动状态、版本等)。
+ /// 内部会先清空串口缓冲,在 内重试直到收到有效帧。
+ ///
+ Task ReadStatusAsync(
+ int? timeoutMs = null,
+ CancellationToken ct = default);
+
+ event EventHandler? StatusChanged;
+ }
+}
diff --git a/HardwareControl.Core/HardwareService/IFocusSystemService.cs b/HardwareControl.Core/HardwareService/IFocusSystemService.cs
new file mode 100644
index 0000000..17ca9a0
--- /dev/null
+++ b/HardwareControl.Core/HardwareService/IFocusSystemService.cs
@@ -0,0 +1,126 @@
+using HardwareControl.Core.FocusSystem;
+
+namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
+{
+ ///
+ /// 定焦系统服务,封装 FocusSystem2.dll。
+ ///
+ /// 串口在连接时从系统参数 focus_com 读取,读取不到时回退到
+ /// appsettings.json 的 "FocusSystem:ComPort"。命令函数内部已完成
+ /// "组包→发送→收应答",返回即表示设备已回执;运行结果与系统信息
+ /// 需通过 / 查询。
+ /// 所有原生调用串行执行。
+ ///
+ public interface IFocusSystemService : IAsyncDisposable
+ {
+ /// 串口是否已打开。
+ bool IsConnected { get; }
+
+ /// 当前使用的串口名(已规范化为 "\\.\COMx");未连接时为 null。
+ string? PortName { get; }
+
+ Task ConnectAsync(CancellationToken ct = default);
+
+ Task DisconnectAsync(CancellationToken ct = default);
+
+ // ---------- 对焦 ----------
+
+ /// 单次对焦。
+ Task StartSingleFocusAsync(CancellationToken ct = default);
+
+ /// 连续对焦。
+ Task StartContinuousFocusAsync(CancellationToken ct = default);
+
+ // ---------- 校准 ----------
+
+ /// 进入校准模式。
+ Task EnterCalibrationModeAsync(CancellationToken ct = default);
+
+ /// 校准滑台移动指定距离,正值为正向;速度为空时使用配置默认值。
+ Task MoveCalibrationAsync(
+ int distanceMm,
+ int? speed = null,
+ CancellationToken ct = default);
+
+ /// 保存当前校准参数到设备存储器。
+ Task SaveCalibrationAsync(CancellationToken ct = default);
+
+ // ---------- 激光器 ----------
+
+ /// 激光器按指定频率出光。
+ Task TurnLaserOnAsync(byte frequency, CancellationToken ct = default);
+
+ /// 立即关闭激光器。
+ Task TurnLaserOffAsync(CancellationToken ct = default);
+
+ /// 设置激光能量值(0~255)。
+ Task SetLaserPowerAsync(byte power, CancellationToken ct = default);
+
+ // ---------- 测距 ----------
+
+ /// 触发激光传感器执行一次测距。
+ Task StartSingleRangeAsync(CancellationToken ct = default);
+
+ /// 激光传感器进入连续测距模式。
+ Task StartContinuousRangeAsync(CancellationToken ct = default);
+
+ // ---------- 升降机构 ----------
+
+ /// 升降机构到达指定位置,正值为上升。
+ Task ControlLiftAsync(int position, CancellationToken ct = default);
+
+ // ---------- 外部触发 ----------
+
+ /// 配置外部触发参数。
+ Task SetExternalTriggerAsync(CancellationToken ct = default);
+
+ /// 响应外部触发信号控制激光器出光。
+ Task FireExternalTriggerAsync(CancellationToken ct = default);
+
+ // ---------- 自动检测 ----------
+
+ /// 启动自动下降检测流程。
+ Task StartAutoDescendAsync(CancellationToken ct = default);
+
+ /// 按指定周期和次数循环出光。
+ Task StartFixedCycleAsync(
+ ushort intervalMs,
+ ushort count,
+ CancellationToken ct = default);
+
+ // ---------- 光谱仪同步 ----------
+
+ /// 设置光谱仪同步延时参数。
+ Task SetSyncTimeAsync(
+ FocusSyncTime parameters,
+ CancellationToken ct = default);
+
+ /// 请求设备返回当前同步延时,结果通过 读取。
+ Task RequestSyncTimeAsync(CancellationToken ct = default);
+
+ // ---------- 电源 ----------
+
+ /// 控制设备总电源关机。
+ Task PowerOffAsync(CancellationToken ct = default);
+
+ // ---------- 查询 ----------
+
+ ///
+ /// 读取系统信息(对焦位置、错误码、电压、版本等)。
+ /// 在 内重试直到收到有效帧。
+ ///
+ Task ReadSystemInfoAsync(
+ int? timeoutMs = null,
+ CancellationToken ct = default);
+
+ ///
+ /// 读取设备缓存的运行结果/查询结果(type=0x02/0x03)。
+ /// 在 内轮询直到收到结果帧。
+ ///
+ Task ReadResultAsync(
+ int? timeoutMs = null,
+ CancellationToken ct = default);
+
+ event EventHandler? StatusChanged;
+ }
+}
diff --git a/HardwareControl.Core/HardwareServiceImpl/AxisStageService.cs b/HardwareControl.Core/HardwareServiceImpl/AxisStageService.cs
new file mode 100644
index 0000000..4453949
--- /dev/null
+++ b/HardwareControl.Core/HardwareServiceImpl/AxisStageService.cs
@@ -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
+{
+ ///
+ /// 位移台服务实现:AxisPlatform2.dll 负责串口与协议,
+ /// 本类负责串口参数解析、调用串行化、错误映射与日志。
+ ///
+ public sealed class AxisStageService : IAxisStageService
+ {
+ // 系统参数中保存位移台串口的配置名称
+ private const string ComPortConfigName = "translation_com";
+
+ private readonly AxisStageOptions _options;
+ private readonly ILogger _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 options,
+ ILogger logger,
+ ISystemConfigService? systemConfig = null)
+ {
+ _options = options.Value;
+ _logger = logger;
+ _systemConfig = systemConfig;
+ }
+
+ public bool IsConnected => _connected;
+
+ public string? PortName => _portName;
+
+ public event EventHandler? 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());
+ 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);
+ }
+ }
+ }
+
+ ///
+ /// 串口优先取系统参数 translation_com;为空时回退到 appsettings 的 AxisStage:ComPort。
+ ///
+ 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 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,
+ };
+
+ /// 文档中运动函数的返回值可能为发送字节数,非负均视为成功。
+ 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);
+ }
+ }
+}
diff --git a/HardwareControl.Core/HardwareServiceImpl/FocusSystemService.cs b/HardwareControl.Core/HardwareServiceImpl/FocusSystemService.cs
new file mode 100644
index 0000000..50cd986
--- /dev/null
+++ b/HardwareControl.Core/HardwareServiceImpl/FocusSystemService.cs
@@ -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
+{
+ ///
+ /// 定焦系统服务实现:FocusSystem2.dll 负责串口与协议,
+ /// 本类负责串口参数解析、调用串行化、错误映射与日志。
+ ///
+ public sealed class FocusSystemService : IFocusSystemService
+ {
+ // 系统参数中保存对焦硬件串口的配置名称
+ private const string ComPortConfigName = "focus_com";
+
+ private readonly FocusSystemOptions _options;
+ private readonly ILogger _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 options,
+ ILogger logger,
+ ISystemConfigService? systemConfig = null)
+ {
+ _options = options.Value;
+ _logger = logger;
+ _systemConfig = systemConfig;
+ }
+
+ public bool IsConnected => _connected;
+
+ public string? PortName => _portName;
+
+ public event EventHandler? 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);
+ }
+ }
+
+ ///
+ /// 串口优先取系统参数 focus_com;为空时回退到 appsettings 的 FocusSystem:ComPort。
+ ///
+ 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 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 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 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;
+ }
+
+ /// 命令返回 FOCUS2_OK(0) 表示成功,非 0 时按错误映射。
+ 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);
+ }
+ }
+}
diff --git a/HardwareControl.Core/SerialPortNames.cs b/HardwareControl.Core/SerialPortNames.cs
new file mode 100644
index 0000000..33aa8e2
--- /dev/null
+++ b/HardwareControl.Core/SerialPortNames.cs
@@ -0,0 +1,27 @@
+namespace HardwareControl.Core
+{
+ ///
+ /// 串口名规范化。原生库要求 Windows 设备路径 "\\.\COMx",
+ /// 同时兼容用户在系统参数里只填写 "COM5" 的情况。
+ ///
+ 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;
+ }
+ }
+}
diff --git a/HardwareControl.Core/dll/AxisPlatform2.dll b/HardwareControl.Core/dll/AxisPlatform2.dll
new file mode 100644
index 0000000..8c58200
Binary files /dev/null and b/HardwareControl.Core/dll/AxisPlatform2.dll differ
diff --git a/HardwareControl.Core/dll/FocusSystem2.dll b/HardwareControl.Core/dll/FocusSystem2.dll
new file mode 100644
index 0000000..b518525
Binary files /dev/null and b/HardwareControl.Core/dll/FocusSystem2.dll differ
diff --git a/HardwareWeb/Program.cs b/HardwareWeb/Program.cs
index 7c7888f..c180808 100644
--- a/HardwareWeb/Program.cs
+++ b/HardwareWeb/Program.cs
@@ -1,3 +1,5 @@
+using HardwareControl.Core.AxisPlatform;
+using HardwareControl.Core.FocusSystem;
using HardwareControl.Core.HardwareServiceImpl;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.SampleAnalysis;
@@ -56,6 +58,15 @@ builder.Services.AddSingleton();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
+// 9. 位移台:串口优先取系统参数 translation_com,未配置时回退到 appsettings 的 AxisStage:ComPort
+builder.Services.Configure(
+ builder.Configuration.GetSection(AxisStageOptions.SectionName));
+builder.Services.AddSingleton();
+
+// 10. 对焦系统:串口优先取系统参数 focus_com,未配置时回退到 appsettings 的 FocusSystem:ComPort
+builder.Services.Configure(
+ builder.Configuration.GetSection(FocusSystemOptions.SectionName));
+builder.Services.AddSingleton();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
diff --git a/HardwareWeb/appsettings.json b/HardwareWeb/appsettings.json
index b729cfe..2585ba6 100644
--- a/HardwareWeb/appsettings.json
+++ b/HardwareWeb/appsettings.json
@@ -26,6 +26,20 @@
"Gain": null,
"SdkLogEnabled": false
},
+ "AxisStage": {
+ "ComPort": null,
+ "FrameHead": "Desktop2D",
+ "DefaultSpeed": 50,
+ "DefaultAccel": 10,
+ "ReadTimeoutMs": 1000,
+ "ReadRetryIntervalMs": 50
+ },
+ "FocusSystem": {
+ "ComPort": null,
+ "DefaultCalibrationSpeed": 50,
+ "ReadTimeoutMs": 1000,
+ "ReadRetryIntervalMs": 100
+ },
"CameraStream": {
"Enabled": true,
"FramesPerSecond": 15,