2026-01-25 09:45:38 +08:00

64 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 readonly PlcService _plcService;
private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(5);
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数据
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");
}
}
}