Files
HA.NetDeamon/NetDaemonApps/NetDaemonApps/DeviceLib/SocketBase.cs
Stephan Maier b9eb4cf019 Neuerstellung
2023-08-29 11:37:30 +02:00

112 lines
3.8 KiB
C#

using NetDaemon.HassModel.Entities;
using NetDaemonInterface;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace NetDaemonApps.DeviceLib
{
public class SocketBase
{
private Task switchOnSockets;
private CancellationTokenSource cts;
public SocketBase()
{
// worker.DoWork += Worker_DoWork;
cts = new CancellationTokenSource();
}
/// <summary>
///
/// </summary>
/// <param name="entities">Entitäten von HA</param>
/// <param name="dataElement">Daten aus dem CallService Event</param>
/// <returns></returns>
public Task CheckStateAsync(CallServiceDataElement dataElement)
{
return Task.Factory.StartNew(async () =>
{
if (Input != null && Outputs != null) // Aus- bzw Eingänge nicht null
{
if (Outputs.All(x => x.IsOff())) // alle Steckdosen ausgeschalten
{
cts = new CancellationTokenSource();
switchOnSockets = TurnOnSockets(cts.Token);
}
else // min. eine Steckdose eingeschalten
{
if (switchOnSockets != null && !switchOnSockets.IsCompleted && cts != null && !cts.IsCancellationRequested)
cts.Cancel();
if (switchOnSockets != null)
Task.WaitAll(switchOnSockets);
Outputs.ForEach(x => x.TurnOff()); // alle Steckdosen ausschalten
}
}
});
}
private Task TurnOnSockets(CancellationToken token = default(CancellationToken))
{
return Task.Factory.StartNew(() =>
{
// alle Steckdosen verzögert einschalten
foreach (var output in Outputs)
{
// Task abbrechen
if (token.IsCancellationRequested)
{
return;
}
// Steckdose einschalten
output.TurnOn();
if (!output.Equals(Outputs.LastOrDefault()))
Thread.Sleep(SwitchOnDelayTime); // Verzögerung
}
if (SwitchOffTime > 0)
{
//Thread.Sleep(SwitchOffTime);
Task.WaitAll(TurnOffSockets(token));
}
});
}
private Task TurnOffSockets(CancellationToken token = default(CancellationToken))
{
return Task.Factory.StartNew(() =>
{
Task.WaitAny(Task.Delay(SwitchOffTime, token));
Outputs.ForEach(x => x.TurnOff());
});
}
/// <summary>
/// Eingangs Entitäten, wobei Entitäten [0] die Master-Entitäten. Mit der Master-Entitäten werden alle Ausgänge verzögert geschalten.
/// </summary>
public InputButtonEntity Input { get; set; }
/// <summary>
/// Ausgangs Entitäten (die geschalten werden sollen)
/// </summary>
public List<LightEntity> Outputs { get; set; }
/// <summary>
/// Verzögerungszeit in ms zwischen den Out-Entitäten, wenn alle geschalten werden sollen
/// </summary>
public int SwitchOnDelayTime { get; set; } = 500;
/// <summary>
/// Steckdose nach Zeit x ms ausschalten.
/// </summary>
public int SwitchOffTime { get; set; } = 250;
}
}