From 9d1660270272180cd71147d6ddd53d1382643d2e Mon Sep 17 00:00:00 2001
From: wenxiangchao <wenxiangchao@ihengxin.com.cn>
Date: 星期一, 02 十一月 2026 18:00:14 +0800
Subject: [PATCH] merge: 并入远程 Initial commit 作为历史根节点
---
Aging.Infrastructure/Drivers/TcpRawDriverAdapter.cs | 222 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 files changed, 222 insertions(+), 0 deletions(-)
diff --git a/Aging.Infrastructure/Drivers/TcpRawDriverAdapter.cs b/Aging.Infrastructure/Drivers/TcpRawDriverAdapter.cs
new file mode 100644
index 0000000..4599d6d
--- /dev/null
+++ b/Aging.Infrastructure/Drivers/TcpRawDriverAdapter.cs
@@ -0,0 +1,222 @@
+using System;
+using System.Diagnostics;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Aging.Infrastructure.Contracts;
+using ConnectionUtil;
+using log4net;
+
+namespace Aging.Infrastructure.Drivers
+{
+ /// <summary>
+ /// TCP 鍘熷閫氫俊椹卞姩閫傞厤鍣ㄣ��
+ /// 灏佽 ConnectionUtil.TcpClientWrapper锛屽疄鐜扮粺涓�鐨� IDeviceDriver 鎺ュ彛銆�
+ /// </summary>
+ public sealed class TcpRawDriverAdapter : IDeviceDriver
+ {
+ private static readonly ILog Log = LogManager.GetLogger(typeof(TcpRawDriverAdapter));
+
+ private readonly string _ip;
+ private readonly int _port;
+ private TcpClientWrapper? _client;
+ private bool _disposed;
+ private readonly Stopwatch _latencyStopwatch = new Stopwatch();
+ private double _lastLatencyMs;
+ private string _lastError = string.Empty;
+ private DateTime? _lastErrorTime;
+ private int _reconnectCount;
+
+ /// <inheritdoc/>
+ public string DeviceId { get; }
+
+ /// <inheritdoc/>
+ public bool IsConnected => _client?.IsConnected ?? false;
+
+ /// <inheritdoc/>
+ public event EventHandler<DeviceConnectionEventArgs>? ConnectionChanged;
+
+ /// <summary>
+ /// 鍒濆鍖� TCP 鍘熷閫氫俊椹卞姩閫傞厤鍣�
+ /// </summary>
+ /// <param name="deviceId">璁惧鍞竴鏍囪瘑绗�</param>
+ /// <param name="ip">鐩爣 IP 鍦板潃</param>
+ /// <param name="port">鐩爣绔彛鍙�</param>
+ public TcpRawDriverAdapter(string deviceId, string ip, int port)
+ {
+ DeviceId = deviceId ?? throw new ArgumentNullException(nameof(deviceId));
+ _ip = ip ?? throw new ArgumentNullException(nameof(ip));
+ _port = port;
+ }
+
+ /// <inheritdoc/>
+ public async Task ConnectAsync(CancellationToken ct)
+ {
+ ThrowIfDisposed();
+ Log.Info($"[TCP] 璁惧 {DeviceId} 姝e湪杩炴帴 {_ip}:{_port}...");
+
+ try
+ {
+ _client = new TcpClientWrapper(_ip, _port);
+ bool success = await _client.ConnectAsync();
+
+ if (!success)
+ {
+ _lastError = "杩炴帴澶辫触";
+ _lastErrorTime = DateTime.Now;
+ throw new InvalidOperationException($"[TCP] 璁惧 {DeviceId} 杩炴帴 {_ip}:{_port} 澶辫触");
+ }
+
+ _lastError = string.Empty;
+ Log.Info($"[TCP] 璁惧 {DeviceId} 宸叉垚鍔熻繛鎺ュ埌 {_ip}:{_port}");
+ OnConnectionChanged(true, "杩炴帴鎴愬姛");
+ }
+ catch (Exception ex)
+ {
+ _lastError = ex.Message;
+ _lastErrorTime = DateTime.Now;
+ Log.Error($"[TCP] 璁惧 {DeviceId} 杩炴帴寮傚父: {ex.Message}", ex);
+ throw;
+ }
+ }
+
+ /// <inheritdoc/>
+ public Task DisconnectAsync()
+ {
+ ThrowIfDisposed();
+ Log.Info($"[TCP] 璁惧 {DeviceId} 姝e湪鏂紑杩炴帴...");
+
+ try
+ {
+ if (_client != null)
+ {
+ _client?.Close();
+ _client = null;
+ }
+
+ Log.Info($"[TCP] 璁惧 {DeviceId} 宸叉柇寮�杩炴帴");
+ OnConnectionChanged(false, "涓诲姩鏂紑");
+ }
+ catch (Exception ex)
+ {
+ _lastError = ex.Message;
+ _lastErrorTime = DateTime.Now;
+ Log.Error($"[TCP] 璁惧 {DeviceId} 鏂紑杩炴帴寮傚父: {ex.Message}", ex);
+ }
+
+ return Task.CompletedTask;
+ }
+
+ /// <inheritdoc/>
+ public async Task<string> SendCommandAsync(string command, CancellationToken ct)
+ {
+ ThrowIfDisposed();
+ if (!IsConnected) throw new InvalidOperationException("[TCP] 璁惧鏈繛鎺�");
+
+ _latencyStopwatch.Restart();
+ try
+ {
+ Log.Debug($"[TCP] 璁惧 {DeviceId} 鍙戦�佸懡浠�: {command}");
+ string response = await _client.SendMessageAsync(command);
+ _latencyStopwatch.Stop();
+ _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
+ Log.Debug($"[TCP] 璁惧 {DeviceId} 鏀跺埌鍝嶅簲: {response} (寤惰繜 {_lastLatencyMs:F2}ms)");
+ return response;
+ }
+ catch (Exception ex)
+ {
+ _latencyStopwatch.Stop();
+ _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
+ _lastError = ex.Message;
+ _lastErrorTime = DateTime.Now;
+ Log.Error($"[TCP] 璁惧 {DeviceId} 鍙戦�佸懡浠ゅけ璐�: {ex.Message}", ex);
+ throw;
+ }
+ }
+
+ /// <inheritdoc/>
+ public async Task<string> QueryAsync(string query, CancellationToken ct)
+ {
+ ThrowIfDisposed();
+ if (!IsConnected) throw new InvalidOperationException("[TCP] 璁惧鏈繛鎺�");
+
+ _latencyStopwatch.Restart();
+ try
+ {
+ Log.Debug($"[TCP] 璁惧 {DeviceId} 鍙戦�佹煡璇�: {query}");
+ // 浣跨敤杈冪煭瓒呮椂杩涜鏌ヨ鎿嶄綔
+ string response = await _client.SendMessageAsync(query, TimeSpan.FromSeconds(5));
+ _latencyStopwatch.Stop();
+ _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
+ Log.Debug($"[TCP] 璁惧 {DeviceId} 鏌ヨ鍝嶅簲: {response} (寤惰繜 {_lastLatencyMs:F2}ms)");
+ return response;
+ }
+ catch (Exception ex)
+ {
+ _latencyStopwatch.Stop();
+ _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
+ _lastError = ex.Message;
+ _lastErrorTime = DateTime.Now;
+ Log.Error($"[TCP] 璁惧 {DeviceId} 鏌ヨ澶辫触: {ex.Message}", ex);
+ throw;
+ }
+ }
+
+ /// <inheritdoc/>
+ public DeviceDriverStatus GetStatus()
+ {
+ return new DeviceDriverStatus
+ {
+ IsConnected = IsConnected,
+ IsHealthy = IsConnected && string.IsNullOrEmpty(_lastError),
+ LastError = _lastError,
+ LastErrorTime = _lastErrorTime,
+ LatencyMs = _lastLatencyMs,
+ ReconnectCount = _reconnectCount
+ };
+ }
+
+ /// <inheritdoc/>
+ public void Dispose()
+ {
+ if (_disposed) return;
+ _disposed = true;
+
+ try
+ {
+ _client?.Dispose();
+ }
+ catch (Exception ex)
+ {
+ Log.Error($"[TCP] 璁惧 {DeviceId} 閲婃斁璧勬簮寮傚父: {ex.Message}", ex);
+ }
+ }
+
+ /// <summary>
+ /// 瑙﹀彂杩炴帴鐘舵�佸彉鍖栦簨浠�
+ /// </summary>
+ private void OnConnectionChanged(bool isConnected, string reason)
+ {
+ ConnectionChanged?.Invoke(this, new DeviceConnectionEventArgs
+ {
+ DeviceId = DeviceId,
+ IsConnected = isConnected,
+ Reason = reason
+ });
+
+ if (!isConnected)
+ {
+ _reconnectCount++;
+ }
+ }
+
+ /// <summary>
+ /// 妫�鏌ユ槸鍚﹀凡閲婃斁
+ /// </summary>
+ private void ThrowIfDisposed()
+ {
+ if (_disposed) throw new ObjectDisposedException(nameof(TcpRawDriverAdapter));
+ }
+ }
+}
--
Gitblit v1.9.1