using System; using System.IO.Ports; using System.Text; namespace Team.Communicate { public class LightHelper { private SerialPort _serialPort; public string PortName { get; private set; } public void Init(string name) { _serialPort = new SerialPort { BaudRate = 9600, PortName = name }; _serialPort.DataReceived += _serialPort_DataReceived; } private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { } public void OpenPort() { if (_serialPort.IsOpen) { return; } _serialPort.Open(); } //public bool GetLightStatus(int port) //{ //} public void SetLightValue(int port,int value) { var valueContent = value.ToString("X"); if (valueContent.Length == 2) { valueContent = "0" + valueContent; } var sendValue = $"$3{port}{valueContent}"; var bytes = Encoding.ASCII.GetBytes(sendValue); byte ret = 0; for (int i = 0; i < bytes.Length; i++) { if (i == 0) { ret = bytes[0]; continue; } ret ^= bytes[i]; } var end = ret.ToString("X"); sendValue += end; _serialPort.Write(sendValue); } public void OpenLight(int port) { var s = $"$1{port}064"; var bytes = Encoding.ASCII.GetBytes(s); byte ret = 0; for (int i = 0; i < bytes.Length; i++) { if (i == 0) { ret = bytes[0]; continue; } ret ^= bytes[i]; } var end = ret.ToString("X"); _serialPort.Write(s + end); } public void CloseLight(int port) { var s = $"$2{port}029"; var bytes = Encoding.ASCII.GetBytes(s); byte ret = 0; for (int i = 0; i < bytes.Length; i++) { if (i == 0) { ret = bytes[0]; continue; } ret ^= bytes[i]; } var end = ret.ToString("X"); _serialPort.Write(s + end); } } }