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 _logger; private readonly PlcService _plcService; private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(5); public PlcPollingServiceOP72(ILogger 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数据 while (!stoppingToken.IsCancellationRequested) { try { // 示例:读取DB块数据 var data1 = _plcService.Read("DB1.DBW0"); // 读取字 var data2 = _plcService.Read("DB1.DBD4"); // 读取双字 var flag = _plcService.Read("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 Task.Delay(_pollingInterval, stoppingToken); } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "PLC polling error"); await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); // 错误后延迟重试 } } _plcService.Dispose(); _logger.LogInformation("PLC Polling Service stopped"); } } }