tidstagning/Tidstagning/Relay.cs

96 lines
2.3 KiB
C#
Raw Normal View History

2020-08-06 15:31:10 +00:00
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
2020-04-21 15:47:38 +00:00
namespace Tidstagning
{
class Relay
{
SerialPort com;
Timer cooldownTimer;
Queue<Int32> signals = new Queue<Int32>();
public Relay(string ComPort = null)
2020-04-21 15:47:38 +00:00
{
com = new SerialPort();
com.PortName = ComPort;
com.BaudRate = 9600;
try
{
com.Open();
}
catch
{
}
2020-04-21 15:47:38 +00:00
}
private void On()
{
Debug.WriteLine("Output on");
Set(0x00, 0x01);
}
private void Off()
{
Debug.WriteLine("Output off");
Set(0x00, 0x00);
}
/**
* Sound the horn for a given time
* Uses a thread to postpone the off call.
*/
public void Sound(int time)
{
Debug.WriteLine("Requesting horn for: " + time.ToString() + "ms");
signals.Enqueue(time);
On();
if (signals.Count == 1)
{
cooldownTimer = new System.Threading.Timer(x =>
{
Off();
signals.Dequeue();
}, null, signals.Peek(), Timeout.Infinite);
}
else
{
cooldownTimer.Change(signals.Peek(), Timeout.Infinite);
}
}
private void Set(int output, byte state) {
2020-04-21 15:47:38 +00:00
byte[] command = {0xff, 0x01, state};
if (com.IsOpen)
{
Debug.WriteLine("COM: " + com.PortName + " Write: 0x" + Convert.ToString(command[2], 16));
com.Write(command, 0, 3);
}
2020-04-21 15:47:38 +00:00
}
public void Close() {
if (com.IsOpen)
{
Off(); //Make sure the horn is off before closing the com port...
2020-04-21 15:47:38 +00:00
com.Close();
}
2020-04-21 15:47:38 +00:00
}
public static string[] GetPorts()
{
string[] ports;
if (SerialPort.GetPortNames().Length != 0)
{
ports = SerialPort.GetPortNames();
}
else
{
ports = new string[]{ "N/A" };
}
return ports;
2020-04-21 15:47:38 +00:00
}
}
}