using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace com_to_com
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            string[] strCom = SerialPort.GetPortNames();
            if (strCom == null)
            {
                MessageBox.Show("本机没有串口！", "Error");
            }
            else
            {
                foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
                {
                    this.comboBox1.Items.Add(portName);

                }
                comboBox1.Text = strCom[0];

            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Thread rf_auto_test = new Thread(form_closed);  //创建线程
            rf_auto_test.Start();
        }


        public void form_closed()
        {
            ledautosta = false;
            System.Threading.Thread.Sleep(500);
            this.Close();
        }


        public const int ZT_SUCCESS = 0;
        public const int SERIAL_PORT = 0;
        public const int BAUDRATE_9600 = 9600;
        public const int FLOW_CONTROL_NONE = 0;
        bool portopenstatus=false;

        private void button8_Click(object sender, EventArgs e)
        {
            
            string result = System.Text.RegularExpressions.Regex.Replace(comboBox1.Text, @"[^0-9]+", "");
            int comnum = int.Parse(result);

            Class1.SetCommSettings(1, comnum, 9600, FLOW_CONTROL_NONE);
            int ret = Class1.OpenPort();
            if (ret != ZT_SUCCESS)
            {
                portopenstatus = false;
                MessageBox.Show("打开端口失败！");
            }
            else
            {
                if (ledautosta == false)
                {
                    ledautosta = true;
                    Thread rxtest = new Thread(rx);  //创建线程
                    rxtest.Start();
                }
                print("port open success");
                portopenstatus = true;
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (portopenstatus)
            {
                Class1.SetLedOn(1);
                Class1.SetLedOn(14);
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            if (portopenstatus)
            {
                Class1.SetLedOff(1);
                Class1.SetLedOff(14);
            }
        }

        bool ledautosta = false;
        private void button12_Click(object sender, EventArgs e)
        {
            if (portopenstatus)
            {
                if (ledautosta == false)
                {
                    ledautosta = true;
                    Thread rxtest = new Thread(rx);  //创建线程
                    rxtest.Start();
                }
            }
        }

        public string ShowTxt(byte[] myBytes, int len)
        {
            string result = "";
            for (int i = 0; i < len; i++)
            {
                string val = Convert.ToString(myBytes[i], 16);
                result += (val.Length == 2 ? val : "0" + val) + " ";
            }
            return result;
        }

        public void rx()
        {
            byte[] buff =new byte[1024];
            int Expectedreceivelength=10;
            uint actualreceivedlength=0;
            while (ledautosta)
            {
                actualreceivedlength = 0;
                Expectedreceivelength = 50;
                Class1.ReceiveDataFromDevice(buff, Expectedreceivelength, ref actualreceivedlength, 500);
                if (actualreceivedlength>0) print("RX: " + ShowTxt(buff, (int)actualreceivedlength));

                if (portopenstatus == false) break;
            }
        }

        public void print(string a)
        {
            textBox1.Text += DateTime.Now.ToLongTimeString().ToString() + ": " + a;
            textBox1.Text += "\r\n";
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.SelectionLength = 0;
            textBox1.ScrollToCaret();
        }

        public static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            Class1.ClosePort();
            print("port close");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] hexdata = new byte[] { };
            int ret;
            uint actualreceivedlength=0;
            if (textBox3.Text == "")
            {
                MessageBox.Show("输出不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (portopenstatus)
            {
                hexdata = strToToHexByte(textBox3.Text);
                ret = Class1.SendDataToDevice(hexdata, (uint)hexdata.Length, ref actualreceivedlength, 500);
                if (ret == 0)
                {
                    print("TX: " + ShowTxt(hexdata, hexdata.Length));
                }
            }

        }
    }
}
