96 lines
2.3 KiB
C#
96 lines
2.3 KiB
C#
using System.IO.Ports;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using System.Diagnostics;
|
|
namespace Tidstagning
|
|
{
|
|
class Relay
|
|
{
|
|
SerialPort com;
|
|
Timer cooldownTimer;
|
|
Queue<Int32> signals = new Queue<Int32>();
|
|
public Relay(string ComPort = null)
|
|
{
|
|
com = new SerialPort();
|
|
com.PortName = ComPort;
|
|
com.BaudRate = 9600;
|
|
try
|
|
{
|
|
com.Open();
|
|
}
|
|
catch
|
|
{
|
|
|
|
}
|
|
}
|
|
|
|
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) {
|
|
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);
|
|
}
|
|
}
|
|
public void Close() {
|
|
if (com.IsOpen)
|
|
{
|
|
Off(); //Make sure the horn is off before closing the com port...
|
|
com.Close();
|
|
}
|
|
}
|
|
|
|
public static string[] GetPorts()
|
|
{
|
|
string[] ports;
|
|
|
|
if (SerialPort.GetPortNames().Length != 0)
|
|
{
|
|
ports = SerialPort.GetPortNames();
|
|
}
|
|
else
|
|
{
|
|
ports = new string[]{ "N/A" };
|
|
}
|
|
return ports;
|
|
}
|
|
}
|
|
}
|