| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410 |
- using System;
- using System.IO.Ports;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace APS7100TestTool.Services
- {
- /// <summary>
- /// 连接类型枚举
- /// </summary>
- public enum ConnectionType
- {
- None, // 未连接
- SerialPort, // 串口
- Ethernet // 网口
- }
- /// <summary>
- /// SCPI 设备通讯类,支持串口和网口连接
- /// </summary>
- public class ScpiDevice : IDisposable
- {
- private SerialPort? _serialPort;
- private TcpClient? _tcpClient;
- private NetworkStream? _networkStream;
- private ConnectionType _connectionType;
- private readonly object _lockObj = new object();
- private volatile bool _isDisposed = false;
- private volatile bool _isDisconnecting = false;
- public bool IsConnected
- {
- get
- {
- // 不使用锁,避免阻塞 UI 线程(这些属性读取是线程安全的)
- if (_isDisposed || _isDisconnecting) return false;
- return _connectionType switch
- {
- ConnectionType.SerialPort => _serialPort?.IsOpen ?? false,
- ConnectionType.Ethernet => _tcpClient?.Connected ?? false,
- _ => false
- };
- }
- }
- public ConnectionType CurrentConnectionType => _connectionType;
- /// <summary>
- /// 通过串口连接设备
- /// </summary>
- public bool ConnectSerial(string portName, int baudRate = 9600, int dataBits = 8,
- Parity parity = Parity.None, StopBits stopBits = StopBits.One)
- {
- try
- {
- lock (_lockObj)
- {
- Disconnect();
- _serialPort = new SerialPort
- {
- PortName = portName,
- BaudRate = baudRate,
- DataBits = dataBits,
- Parity = parity,
- StopBits = stopBits,
- Encoding = Encoding.ASCII,
- ReadTimeout = 1000, // 减少超时以更快检测断连
- WriteTimeout = 1000,
- NewLine = "\n"
- };
- _serialPort.Open();
- Thread.Sleep(100); // 等待端口稳定
-
- // 清空缓冲区
- _serialPort.DiscardInBuffer();
- _serialPort.DiscardOutBuffer();
- _connectionType = ConnectionType.SerialPort;
- return true;
- }
- }
- catch (Exception ex)
- {
- throw new Exception($"串口连接失败: {ex.Message}", ex);
- }
- }
- /// <summary>
- /// 连接超时时间(毫秒)
- /// </summary>
- public int ConnectionTimeout { get; set; } = 5000;
- /// <summary>
- /// 通过网口连接设备
- /// </summary>
- public bool ConnectEthernet(string ipAddress, int port = 2268)
- {
- TcpClient? tempClient = null;
-
- try
- {
- lock (_lockObj)
- {
- // 先彻底断开并释放旧连接
- ForceDisconnect();
- // 等待端口完全释放
- Thread.Sleep(100);
- tempClient = new TcpClient();
-
- // 设置 LingerState 以立即释放端口
- tempClient.LingerState = new System.Net.Sockets.LingerOption(true, 0);
- tempClient.NoDelay = true;
-
- // 使用带超时的连接
- var connectTask = tempClient.ConnectAsync(ipAddress, port);
- if (!connectTask.Wait(ConnectionTimeout))
- {
- // 超时 - 强制关闭
- try { tempClient.Close(); } catch { }
- try { tempClient.Dispose(); } catch { }
- tempClient = null;
- throw new TimeoutException($"连接超时({ConnectionTimeout/1000}秒),请检查设备IP地址和端口是否正确");
- }
-
- // 检查连接是否真的成功
- if (!tempClient.Connected)
- {
- try { tempClient.Close(); } catch { }
- try { tempClient.Dispose(); } catch { }
- tempClient = null;
- throw new Exception("连接失败,设备未响应");
- }
-
- _tcpClient = tempClient;
- tempClient = null; // 转移所有权,防止 finally 中释放
-
- _networkStream = _tcpClient.GetStream();
- _networkStream.ReadTimeout = 1000;
- _networkStream.WriteTimeout = 1000;
- Thread.Sleep(100); // 等待连接稳定
- _connectionType = ConnectionType.Ethernet;
- return true;
- }
- }
- catch (TimeoutException)
- {
- throw;
- }
- catch (AggregateException ae)
- {
- var innerEx = ae.InnerException ?? ae;
- throw new Exception($"网口连接失败: {innerEx.Message}", innerEx);
- }
- catch (Exception ex)
- {
- throw new Exception($"网口连接失败: {ex.Message}", ex);
- }
- finally
- {
- // 确保临时客户端被释放(如果没有成功转移所有权)
- if (tempClient != null)
- {
- try { tempClient.Close(); } catch { }
- try { tempClient.Dispose(); } catch { }
- }
- }
- }
-
- /// <summary>
- /// 强制断开连接并释放所有资源
- /// </summary>
- private void ForceDisconnect()
- {
- _isDisconnecting = true;
-
- try
- {
- // 关闭网络流
- if (_networkStream != null)
- {
- try { _networkStream.Close(); } catch { }
- try { _networkStream.Dispose(); } catch { }
- _networkStream = null;
- }
-
- // 强制关闭 TCP 连接
- if (_tcpClient != null)
- {
- try
- {
- // 设置 LingerState 为立即关闭
- _tcpClient.LingerState = new System.Net.Sockets.LingerOption(true, 0);
- }
- catch { }
-
- try { _tcpClient.Close(); } catch { }
- try { _tcpClient.Dispose(); } catch { }
- _tcpClient = null;
- }
-
- // 关闭串口
- if (_serialPort != null)
- {
- try
- {
- if (_serialPort.IsOpen)
- {
- _serialPort.DiscardInBuffer();
- _serialPort.DiscardOutBuffer();
- _serialPort.Close();
- }
- }
- catch { }
-
- try { _serialPort.Dispose(); } catch { }
- _serialPort = null;
- }
-
- _connectionType = ConnectionType.None;
- }
- finally
- {
- _isDisconnecting = false;
- }
- }
- /// <summary>
- /// 连接设备(兼容旧方法)
- /// </summary>
- [Obsolete("请使用 ConnectSerial 或 ConnectEthernet")]
- public bool Connect(string portName, int baudRate = 9600, int dataBits = 8,
- Parity parity = Parity.None, StopBits stopBits = StopBits.One)
- {
- return ConnectSerial(portName, baudRate, dataBits, parity, stopBits);
- }
- /// <summary>
- /// 断开连接
- /// </summary>
- public void Disconnect()
- {
- lock (_lockObj)
- {
- ForceDisconnect();
- }
- }
- /// <summary>
- /// 启用命令调试日志
- /// </summary>
- public static bool EnableCommandLog { get; set; } = false;
-
- /// <summary>
- /// 命令日志事件
- /// </summary>
- public static event Action<string>? OnCommandLog;
- /// <summary>
- /// 发送 SCPI 命令(无返回)
- /// </summary>
- public void SendCommand(string command)
- {
- lock (_lockObj)
- {
- CheckConnectionState();
- try
- {
- if (EnableCommandLog)
- {
- OnCommandLog?.Invoke($"[SCPI TX] {command}");
- }
-
- if (_connectionType == ConnectionType.SerialPort)
- {
- if (_serialPort == null || !_serialPort.IsOpen)
- throw new InvalidOperationException("串口未打开");
- _serialPort.WriteLine(command);
- }
- else // Ethernet
- {
- if (_networkStream == null || !_networkStream.CanWrite)
- throw new InvalidOperationException("网络流不可写");
- byte[] data = Encoding.ASCII.GetBytes(command + "\n");
- _networkStream.Write(data, 0, data.Length);
- }
-
- Thread.Sleep(20); // 给设备处理时间(减少延迟)
- }
- catch (ObjectDisposedException)
- {
- throw new InvalidOperationException("设备连接已关闭");
- }
- catch (System.IO.IOException ex)
- {
- throw new InvalidOperationException($"通信错误: {ex.Message}", ex);
- }
- }
- }
- /// <summary>
- /// 发送 SCPI 查询命令并获取返回值
- /// </summary>
- public string Query(string command)
- {
- lock (_lockObj)
- {
- CheckConnectionState();
- string response;
- try
- {
- if (EnableCommandLog)
- {
- OnCommandLog?.Invoke($"[SCPI TX] {command}");
- }
-
- if (_connectionType == ConnectionType.SerialPort)
- {
- if (_serialPort == null || !_serialPort.IsOpen)
- throw new InvalidOperationException("串口未打开");
-
- // 串口方式
- _serialPort.DiscardInBuffer();
- _serialPort.WriteLine(command);
- Thread.Sleep(30); // 减少延迟以提高响应速度
- response = _serialPort.ReadLine().Trim();
- }
- else // Ethernet
- {
- if (_networkStream == null || !_networkStream.CanWrite)
- throw new InvalidOperationException("网络流不可用");
-
- // 网口方式
- byte[] sendData = Encoding.ASCII.GetBytes(command + "\n");
- _networkStream.Write(sendData, 0, sendData.Length);
-
- Thread.Sleep(30); // 减少延迟以提高响应速度
-
- byte[] buffer = new byte[4096];
- int bytesRead = _networkStream.Read(buffer, 0, buffer.Length);
- response = Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();
- }
- }
- catch (ObjectDisposedException)
- {
- throw new InvalidOperationException("设备连接已关闭");
- }
- catch (System.IO.IOException ex)
- {
- throw new InvalidOperationException($"通信错误: {ex.Message}", ex);
- }
- catch (TimeoutException ex)
- {
- throw new InvalidOperationException($"通信超时: {ex.Message}", ex);
- }
- return response;
- }
- }
-
- /// <summary>
- /// 检查连接状态(必须在锁内调用)
- /// </summary>
- private void CheckConnectionState()
- {
- if (_isDisposed)
- throw new ObjectDisposedException(nameof(ScpiDevice));
- if (_isDisconnecting)
- throw new InvalidOperationException("设备正在断开连接");
-
- bool connected = _connectionType switch
- {
- ConnectionType.SerialPort => _serialPort?.IsOpen ?? false,
- ConnectionType.Ethernet => _tcpClient?.Connected ?? false,
- _ => false
- };
-
- if (!connected)
- throw new InvalidOperationException("设备未连接");
- }
- /// <summary>
- /// 获取可用的串口列表
- /// </summary>
- public static string[] GetAvailablePorts()
- {
- return SerialPort.GetPortNames();
- }
- public void Dispose()
- {
- if (!_isDisposed)
- {
- Disconnect();
- _serialPort?.Dispose();
- _isDisposed = true;
- }
- }
- }
- }
|