ComHelper

2019-06-03  本文已影响0人  psmyfish
public class COMHelper
    {
        private static readonly SerialPort comPort = new SerialPort();

        private static string portName;

        private static bool isCOMOpen = false;

        public COMHelper()
        {
        }

        public void SendToCOM(int eventTrigger)
        {
            string toSendString = "01 E1 01 00 ";
            toSendString += eventTrigger.ToString("X2");
            byte[] b = HexStringToByteArray(toSendString);
            sendData(b);
        }

        public static void SerialPortInit()
        {
            var ports = SerialPort.GetPortNames();
            if (ports.Length == 0) return;
            else
                portName = ports[0];
            if (isCOMOpen == false)
            {
                try
                {
                    comPort.PortName = portName;
                    comPort.BaudRate = 115200;
                    comPort.Parity = Parity.None;
                    comPort.StopBits = StopBits.One;
                    comPort.DataBits = 8;
                    comPort.Handshake = Handshake.None;
                    comPort.RtsEnable = false;
                    comPort.Open();
                    isCOMOpen = true;
                }
                catch
                {
                    // ignored
                }
            }
            else
            {
                return;
            }
        }

        public static void SerialPortClose()
        {
            isCOMOpen = false;
            comPort.Close();
        }

        private byte[] HexStringToByteArray(string s)
        {//16进制字符串转化为字节数组
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        private bool sendData(byte[] sendBuffer)
        {
            if (isCOMOpen == false)
            {
                return false;
            }
            try
            {
                comPort.Write(sendBuffer, 0, sendBuffer.Length);
                comPort.DiscardOutBuffer();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读