Files
WorkIndicator/Delcom/StoplightIndicator.cs
T
ckaczor 8c63b93d09
Deploy to Gitea Releases / deploy-to-gitea-releases (push) Successful in 33s
Tweak logging and change settings string
2026-08-18 14:43:22 -04:00

139 lines
3.6 KiB
C#

using System;
using System.Diagnostics;
using Serilog;
namespace WorkIndicator.Delcom
{
public class StoplightIndicator : IDisposable
{
private readonly ILogger _logger;
public enum Light
{
Green,
Yellow,
Red
}
public enum LightState
{
Off,
On,
Blink
}
private LightState _green = LightState.Off;
private LightState _yellow = LightState.Off;
private LightState _red = LightState.Off;
public StoplightIndicator()
{
_logger = Log.ForContext<StoplightIndicator>();
Device = new Delcom();
Device.Open();
SetLights(_red, _yellow, _green);
}
public void Dispose()
{
Device.Close();
}
public Delcom Device { get; }
public void GetLights(out LightState red, out LightState yellow, out LightState green)
{
red = _red;
yellow = _yellow;
green = _green;
}
public LightState GetLight(Light light)
{
switch (light)
{
case Light.Red:
return _red;
case Light.Yellow:
return _yellow;
case Light.Green:
return _green;
default:
throw new ArgumentOutOfRangeException(nameof(light));
}
}
public void SetLights(LightState red, LightState yellow, LightState green)
{
if (_red == red && _yellow == yellow && _green == green)
return;
var port1 = 0;
_red = red;
_yellow = yellow;
_green = green;
_logger.Information("Red: {red}, Yellow: {yellow}, Green: {green}", _red, _yellow, _green);
port1 = port1.SetBitValue((int) Light.Green, green == LightState.Off);
port1 = port1.SetBitValue((int) Light.Yellow, yellow == LightState.Off);
port1 = port1.SetBitValue((int) Light.Red, red == LightState.Off);
Device.WritePorts(0, port1);
var blinkEnable = 0;
var blinkDisable = 0;
if (red == LightState.Blink)
blinkEnable = blinkEnable.SetBitValue((int) Light.Red, true);
else
blinkDisable = blinkDisable.SetBitValue((int) Light.Red, true);
if (yellow == LightState.Blink)
blinkEnable = blinkEnable.SetBitValue((int) Light.Yellow, true);
else
blinkDisable = blinkDisable.SetBitValue((int) Light.Yellow, true);
if (green == LightState.Blink)
blinkEnable = blinkEnable.SetBitValue((int) Light.Green, true);
else
blinkDisable = blinkDisable.SetBitValue((int) Light.Green, true);
Device.WriteBlink(blinkDisable, blinkEnable);
}
public void SetLight(Light light, LightState state)
{
var red = _red;
var yellow = _yellow;
var green = _green;
switch (light)
{
case Light.Red:
red = state;
break;
case Light.Yellow:
yellow = state;
break;
case Light.Green:
green = state;
break;
default:
throw new ArgumentOutOfRangeException(nameof(light));
}
SetLights(red, yellow, green);
}
}
}