From 585cac5cd0d4eea2c6259e3edcbbe10caf993ca1 Mon Sep 17 00:00:00 2001 From: gcw_MV9p2JJN Date: Sun, 25 Jan 2026 11:01:34 +0800 Subject: [PATCH] 1 --- .../PLCBackground/PlcPollingServiceOP72.cs | 56 ++++++++++--------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/RIZO.Service/PLCBackground/PlcPollingServiceOP72.cs b/RIZO.Service/PLCBackground/PlcPollingServiceOP72.cs index 66dfbf9..c6a03f2 100644 --- a/RIZO.Service/PLCBackground/PlcPollingServiceOP72.cs +++ b/RIZO.Service/PLCBackground/PlcPollingServiceOP72.cs @@ -13,51 +13,57 @@ namespace RIZO.Service.PLCBackground public class PlcPollingServiceOP72 : BackgroundService { private readonly ILogger _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 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) + // 使用工厂方法创建服务实例 + using (_plcService = new PlcService(_ipAddress, _cpuType)) { - try + while (!stoppingToken.IsCancellationRequested) { - // 示例:读取DB块数据 - var data1 = _plcService.Read("DB1.DBW0"); // 读取字 - var data2 = _plcService.Read("DB1.DBD4"); // 读取双字 - var flag = _plcService.Read("M10.0"); // 读取标志位 + 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}"); + _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) - { - break; - } - catch (Exception ex) - { - _logger.LogError(ex, "PLC polling error"); - await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); // 错误后延迟重试 + 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); + } } } - _plcService.Dispose(); _logger.LogInformation("PLC Polling Service stopped"); } + + } }