gcw_MV9p2JJN 585cac5cd0 1
2026-01-25 11:01:34 +08:00

70 lines
2.3 KiB
C#

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RIZO.Service.PLC;
using S7.Net;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RIZO.Service.PLCBackground
{
public class PlcPollingServiceOP72 : BackgroundService
{
private readonly ILogger<PlcPollingServiceOP72> _logger;
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;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("PLC Polling Service started");
// 使用工厂方法创建服务实例
using (_plcService = new PlcService(_ipAddress, _cpuType))
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
// 使用异步读写方法
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}");
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);
}
}
}
_logger.LogInformation("PLC Polling Service stopped");
}
}
}