using System.IO.Ports; using System; using System.Collections.Generic; using System.Threading; using System.Diagnostics; namespace Tidstagning { class Relay { SerialPort com; Timer cooldownTimer; public Relay(string ComPort = null) { com = new SerialPort(); com.PortName = ComPort; com.BaudRate = 9600; try { com.Open(); } catch { } } private void On() { Set(0x00, 0x01); } private void Off() { Set(0x00, 0x00); } public void Sound(int time) { Debug.WriteLine("Requesting horn for: " + time.ToString() + "ms"); On(); cooldownTimer = new System.Threading.Timer(x => { Off(); }, null, new TimeSpan(0, 0, time / 1000), new System.TimeSpan(0)); } 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; } } }