Files
FSI.BT.IR.Plc.TimeSync/scr/FSI.BT.IR.Plc.TimeSync/SyncPlcTime.cs
Maier Stephan SI bc23a8514f Tagessicherung
2024-07-22 17:01:21 +03:00

108 lines
3.7 KiB
C#

using NLog;
using Sharp7;
using GuerrillaNtp;
using static FSI.BT.IR.Plc.TimeSync.Settings.Context;
namespace FSI.BT.IR.Plc.TimeSync
{
internal class SyncPlcTime : IPlc
{
private Logger _log = LogManager.GetCurrentClassLogger();
private const string DATE_TIME_FORMAT = "dd.MM.yyyy HH:mm:ss.fff";
public SyncPlcTime(IPlc plc)
{
Name = plc.Name;
Description = plc.Description;
Adress = plc.Adress;
Rack = plc.Rack;
Slot = plc.Slot;
UpdateIntervall = plc.UpdateIntervall;
TimeDifference = plc.TimeDifference;
LocalTime = plc.LocalTime;
Enable = plc.Enable;
}
public string Name { get; set; }
public string Description { get; set; }
public string Adress { get; set; }
public int Rack { get; set; }
public int Slot { get; set; }
public int UpdateIntervall { get; set; }
public int TimeDifference { get; set; }
public bool LocalTime { get; set; }
public bool Enable { get; set; }
public string NtpServer { get; set; }
public async Task Snyc(CancellationToken cancellationToken) =>
await Task.Run(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
var plc = new S7Client();
var connectionRslt = plc.ConnectTo(Adress, Rack, Slot);
if (connectionRslt == 0)
{
_log.Debug(Name + " Verbindung hergestellt.");
}
else
{
_log.Error(Name + " Verbindung nicht hergestellt.");
_log.Error(Name + " Fehler: " + plc.ErrorText(connectionRslt));
await Task.Delay(UpdateIntervall, cancellationToken);
continue;
}
var plcDateTime = new DateTime();
plc.GetPlcDateTime(ref plcDateTime);
_log.Debug(Name + " SPS Zeit (aktuell): " + plcDateTime.ToString(DATE_TIME_FORMAT));
var client = new NtpClient(NtpServer);
NtpClock clock = client.Query();
DateTime ntpDateTime;
if (LocalTime)
{
_log.Debug(Name + " UTC Zeit: " + clock.Now.ToString(DATE_TIME_FORMAT));
ntpDateTime = clock.Now.DateTime;
}
else
{
_log.Debug(Name + " Ortszeit: " + clock.UtcNow.ToString(DATE_TIME_FORMAT));
ntpDateTime = clock.UtcNow.DateTime;
}
var timeSpan = Math.Abs((plcDateTime - ntpDateTime).TotalMilliseconds);
if (TimeDifference > 0 && timeSpan >= TimeDifference)
{
_log.Debug(Name + " Zeitdifferenz " + timeSpan + " ms überschritten");
_log.Info(Name + " neue Zeit: " + ntpDateTime.ToString(DATE_TIME_FORMAT));
var temp = plc.SetPlcDateTime(ntpDateTime);
}
else if (TimeDifference == 0)
{
_log.Info(Name + " neue Zeit: " + ntpDateTime.ToString(DATE_TIME_FORMAT));
var temp = plc.SetPlcDateTime(ntpDateTime);
}
plc.Disconnect();
_log.Debug(Name + " Verbindung getrennt.");
await Task.Delay(UpdateIntervall, cancellationToken);
}
}, cancellationToken);
}
}