This commit is contained in:
gcw_MV9p2JJN 2026-01-25 11:01:34 +08:00
parent ff1dd97316
commit 585cac5cd0

View File

@ -13,51 +13,57 @@ namespace RIZO.Service.PLCBackground
public class PlcPollingServiceOP72 : BackgroundService
{
private readonly ILogger<PlcPollingServiceOP72> _logger;
private readonly PlcService _plcService;
private PlcService _plcService;
private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(5);
private readonly string _ipAddress = "192.168.0.1";
private readonly CpuType _cpuType = CpuType.S71500;
public PlcPollingServiceOP72(ILogger<PlcPollingServiceOP72> logger)
{
_logger = logger;
// 配置PLC连接参数根据实际设备修改
_plcService = new PlcService("192.168.0.1", CpuType.S71500);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("PLC Polling Service started");
// 不断轮询PLC数据
// 使用工厂方法创建服务实例
using (_plcService = new PlcService(_ipAddress, _cpuType))
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
// 示例读取DB块数据
var data1 = _plcService.Read("DB1.DBW0"); // 读取字
var data2 = _plcService.Read("DB1.DBD4"); // 读取双字
var flag = _plcService.Read("M10.0"); // 读取标志位
// 使用异步读写方法
var data1 = await _plcService.ReadAsync("DB1.DBW0");
var data2 = await _plcService.ReadAsync("DB1.DBD4");
var flag = await _plcService.ReadAsync("M10.0");
_logger.LogInformation($"DB1.DBW0: {data1}, DB1.DBD4: {data2}, M10.0: {flag}");
// 示例写入数据到PLC
_plcService.Write("DB1.DBW10", (short)123); // 写入字
_plcService.Write("DB1.DBD20", 45.67d); // 写入浮点数
await _plcService.WriteAsync("DB1.DBW10", (short)123);
await _plcService.WriteAsync("DB1.DBD20", 45.67d);
await Task.Delay(_pollingInterval, stoppingToken);
}
catch (OperationCanceledException)
{
_logger.LogInformation("PLC Polling Service is stopping");
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "PLC polling error");
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); // 错误后延迟重试
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
}
_plcService.Dispose();
_logger.LogInformation("PLC Polling Service stopped");
}
}
}