61 lines
2.1 KiB
C#
61 lines
2.1 KiB
C#
using System;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using FootwearTest.Models;
|
|
|
|
namespace FootwearTest.Services;
|
|
|
|
public sealed class ModbusTcpDeviceClient : IDeviceClient
|
|
{
|
|
private readonly DeviceSettings _settings;
|
|
private TcpClient? _tcpClient;
|
|
|
|
public ModbusTcpDeviceClient(DeviceSettings settings)
|
|
{
|
|
_settings = settings;
|
|
LastSnapshot = DeviceSnapshot.Initial with { AlarmText = "Modbus 点表未配置,当前仅验证连接" };
|
|
}
|
|
|
|
public bool IsConnected => _tcpClient?.Connected == true;
|
|
public string ConnectionText => IsConnected ? $"Modbus TCP {_settings.Host}:{_settings.Port} 已连接" : "Modbus TCP 未连接";
|
|
public DeviceSnapshot LastSnapshot { get; private set; }
|
|
public event EventHandler<DeviceSnapshot>? SnapshotUpdated;
|
|
|
|
public async Task ConnectAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
_tcpClient?.Dispose();
|
|
_tcpClient = new TcpClient();
|
|
await _tcpClient.ConnectAsync(_settings.Host, _settings.Port, cancellationToken);
|
|
LastSnapshot = LastSnapshot with { Timestamp = DateTime.Now, AlarmText = "等待配置真实 Modbus 寄存器点表" };
|
|
SnapshotUpdated?.Invoke(this, LastSnapshot);
|
|
}
|
|
|
|
public Task DisconnectAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
_tcpClient?.Dispose();
|
|
_tcpClient = null;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task<DeviceSnapshot> ReadSnapshotAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
LastSnapshot = LastSnapshot with { Timestamp = DateTime.Now };
|
|
SnapshotUpdated?.Invoke(this, LastSnapshot);
|
|
return Task.FromResult(LastSnapshot);
|
|
}
|
|
|
|
public Task SetOutputsAsync(bool pumpRunning, bool fanRunning, bool heaterRunning, CancellationToken cancellationToken = default)
|
|
{
|
|
LastSnapshot = LastSnapshot with
|
|
{
|
|
Timestamp = DateTime.Now,
|
|
PumpRunning = pumpRunning,
|
|
FanRunning = fanRunning,
|
|
HeaterRunning = heaterRunning
|
|
};
|
|
SnapshotUpdated?.Invoke(this, LastSnapshot);
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|