using System; using System.Collections.Generic; using System.IO.Ports; using System.Text; namespace SerialRelayLib { public enum RelayCommand { Open = 1, Close = 2, Toggle = 3, Momentary = 4 } public class SerialRelay { private System.IO.Ports.SerialPort port = new SerialPort(); private string _lastError = string.Empty; private byte[] _sums = new byte[] {0xAB,0xAD,0xAE,0xAF,0xB0,0xAE,0xAF,0xB0,0xB1,0xAF,0xB0,0xB1,0xB2,0xB0,0xB1,0xB2,0xB3}; byte[] b = new byte[8]; public static String[] GetPorts() { return SerialPort.GetPortNames(); } public string LastError { get { return _lastError; } } public SerialRelay() { b[0] = 0x55; b[1] = 0x56; b[2] = 0x00; b[3] = 0x00; b[4] = 0x00; } public bool Open(string portName) { _lastError = string.Empty; if (port.IsOpen) port.Close(); port.PortName = portName; try { port.Open(); return true; } catch(Exception ex) { _lastError = ex.Message; } return false; } public void SendCommand(RelayCommand command,int channel) { if (!port.IsOpen) return; if (channel < 1 || channel > 4) return; b[5] = Convert.ToByte(channel); b[6] = Convert.ToByte(command); b[7] = 0xAB; b[7] += b[5]; b[7] += b[6]; port.Write(b, 0, 8); } } }