Tagessicherung

This commit is contained in:
Maier Stephan SI
2024-07-22 09:01:44 +03:00
parent 7fb7fce332
commit fb47ce09ab
12 changed files with 516 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
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));
return;
}
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);
}
}