using Microsoft.Win32;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace C_Windows_1
{
    public partial class PortSetting : Form
    {
        public PortSetting()
        {
            InitializeComponent();
        }

        private void PortSetting_Load(object sender, EventArgs e)
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();//获得有效端口号
            PortNum.Items.AddRange(ports);
            CodePort1.Items.AddRange(ports); 
            Baudrate.SelectedIndex = 0;
            Read();
            if (Form1.f1.CH1.IsOpen())
            {
                label6.Text = "已连接";
                label6.ForeColor = Color.Green;
                label5.Text = "已连接";
                label5.ForeColor = Color.Green;
                Form1.f1.label6.Text = "已连接";

                BtnCon1.Enabled = false;
                PortNum.Enabled = false;
                Baudrate.Enabled = false;
            }
            else
            {
                label6.Text = "未连接";
                label6.ForeColor = Color.Red;

                label5.Text = "未连接";
                label5.ForeColor = Color.Red;

               
                Form1.f1.label6.Text = "未连接";

                BtnCon1.Enabled = true;

                PortNum.Enabled = true;
                Baudrate.Enabled = true;
            }



            if (Form1.f1.SerialPort1.IsOpen)
            {
                CodeIsComm1.Text = "已连接";
                CodeIsComm1.ForeColor = Color.Green;
                PortBtnCon1.Enabled = false;
            }
            else
            {
                CodeIsComm1.Text = "未连接";
                CodeIsComm1.ForeColor = Color.Red;
                PortBtnCon1.Enabled = true;
            }

        }

        private void BtnCon1_Click(object sender, EventArgs e)
        {
            try
            {

                if (Form1.f1.CH1.IsOpen())
                {
                    Form1.f1.CH1.Close();
                }
                Form1.f1.ModbusRtuint(Form1.f1.CH1, Convert.ToByte(Form1.f1.Station.Text), PortNum.Text, Convert.ToInt32(Baudrate.Text), 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None);

                if (Form1.f1.CH1.IsOpen())
                {
                    Form1.f1.label6.Text = "已连接";
                    Form1.f1.BtnCon1.Enabled = false;
                    Form1.f1.label6.ForeColor = Color.Green;

                    label6.Text = "已连接";
                    label6.ForeColor = Color.Green;
                    label5.Text = "已连接";
                    label5.ForeColor = Color.Green;
                    BtnCon1.Enabled = false;
                    PortNum.Enabled = false;
                    Baudrate.Enabled = false;
                    SetPort();
                    Form1.f1.PortNum.Text = PortNum.Text;
                    Form1.f1.Baudrate.Text = Baudrate.Text;

                }
                else
                {
                    MessageBox.Show("连接失败,请检查端口占用情况");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            PortNum.Items.Clear();
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            PortNum.Items.AddRange(ports);
        }

        private void BtnBreak_Click(object sender, EventArgs e)
        {
            try
            {
                if (Form1.f1.CH1.IsOpen())
                {
                    Form1.f1.CH1.Close();
                    if (Form1.f1.CH1.IsOpen() is false)
                    {
                        label6.Text = "未连接";
                        label6.ForeColor = Color.Red;
                        label5.Text = "未连接";
                        label5.ForeColor = Color.Red;
                        Form1.f1.label6.Text = "未连接";
                        Form1.f1.label6.ForeColor = Color.Red;
                        BtnCon1.Enabled = true;
                        PortNum.Enabled = true;
                        Baudrate.Enabled = true;
                        Form1.f1.BtnCon1.Enabled = true;
                    }
                }
                //else
                //{
                //    ////读取启动信号需停止
                //    //Form1.f1.Timer1.Stop();
                //    //Form1.f1.Timer1.Dispose();
                //    //if (Form1.f1.Timer1.Enabled is true)
                //    //{
                //    //    Form1.f1.Timer1.Stop();
                //    //}
                //    Form1.f1.SerialPort1.Close();
                //    if (Form1.f1.SerialPort1.IsOpen is false)
                //    {
                //        label6.Text = "未连接";
                //        label6.ForeColor = Color.Red;
                //        BtnCon1.Enabled = true;

                //        label5.Text = "未连接";
                //        label5.ForeColor = Color.Red;

                //        Form1.f1.label6.Text = "未连接";

                //        PortNum.Enabled = true;
                //        Baudrate.Enabled = true;
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //发送过程
        private void Send()
        {
            try
            {
                //将CRC冗余码添加进指令中
                String str = Form1.f1.Station.Text + "0300190001";
                byte[] byt = StrtoHexbyte(str);
                int str2;
                str2 = Crc16_Modbus(byt, byt.Length);

                string str3;

                str3 = Convert.ToString((str2 >> 8) & 0xff, 16);
                string str4;
                str4 = Convert.ToString(str2 & 0xff, 16);

                if (str3.Length == 1)
                {
                    str3 = "0" + str3;
                }
                if (str4.Length == 1)
                {
                    str4 = "0" + str4;
                }
                SendText.Text = str + str4 + str3;
                String str5 = SendText.Text;
                if (str5.Length > 0)
                {
                    byte[] byt2 = StrtoHexbyte(str5);
                    TestPort1.Write(byt2, 0, byt2.Length);//发送数据
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //计算CRC冗余码
        private int Crc16_Modbus(byte[] modbusdata, int length)
        {
            int i, j;
            int crc = 0xffff;//0xffff or 0
            for (i = 0; i < length; i++)
            {
                crc ^= modbusdata[i] & 0xff;
                for (j = 0; j < 8; j++)
                {
                    if ((crc & 0x01) == 1)
                    {
                        crc = (crc >> 1) ^ 0xa001;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }

            return crc;
        }

        //将发送数据转为十六进制数据
        private static byte[] StrtoHexbyte(String hexstring)
        {
            int i;
            hexstring = hexstring.Replace(" ", "");
            byte[] returnBytes = new byte[(hexstring.Length) / 2];
            try
            {
                for (i = 0; i < returnBytes.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(hexstring.Substring(i * 2, 2), 16);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
            return returnBytes;
        }

        //接收数据
        private void TestPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(100);
                int len = TestPort1.BytesToRead;//获取可以读取的字节数
                if (len > 1)
                {
                    byte[] buff = new byte[len];//创建缓存数据数组
                    TestPort1.Read(buff, 0, len);//把数据读取到buff数组
                    //string str = Encoding.Default.GetString(buff);
                    Invoke((new System.Action(() => //串口接收事件会自动创建线程
                    {
                        ReceiveText.Clear();
                        ReceiveText.Text = ByteToHexStr(buff);
                        TestPort1.DiscardInBuffer();
                    }
                   )));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ReceiveText_TextChanged(object sender, EventArgs e)
        {
            //if (ReceiveText.Text.Length > 0)
            //{
            //    timer1.Interval = 200;
            //    timer1.Start();
            //}
        }

        private void Stagenum()
        {
            string testresult = ReceiveText.Text.Replace(" ", "");
            if (testresult.Length > 10 && testresult.Substring(2, 2) == "03")
            {
                //设置端口的参数，包括波特率等
                Form1.f1.SerialPort1.BaudRate = int.Parse(Baudrate.Text);
                Form1.f1.SerialPort1.PortName = PortNum.Text;
                Form1.f1.SerialPort1.DataBits = 8;
                Form1.f1.SerialPort1.StopBits = System.IO.Ports.StopBits.One;
                Form1.f1.SerialPort1.Parity = System.IO.Ports.Parity.None;

                Form1.f1.SerialPort1.Open();
                if (Form1.f1.SerialPort1.IsOpen)
                {
                    label5.Text = "已连接";
                    label5.ForeColor = Color.Green;

                    Form1.f1.label6.Text = "已连接";
                    Form1.f1.label6.ForeColor = Color.Green;

                    Form1.f1.PortNum.Text = Form1.f1.SerialPort1.PortName;

                    Form1.f1.Timer1.Interval = 800;
                    Form1.f1.Timer1.Start();
                    Form1.f1.stage = 1;

                    Form1.f1.BtnCon1.Enabled = false;


                    //stage = 1;
                    SetPort();
                }
            }
        }

        //十六进制接收
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            try
            {
                if (bytes != null)
                {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        returnStr += bytes[i].ToString("X2");//每个字节转换成两位十六进制
                        returnStr += " ";//两个16进制用空格隔开,方便看数据
                    }
                }
                return returnStr;
            }
            catch (Exception)
            {
                return returnStr;
            }
        }

        //端口写入
        private void SetPort()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.SetValue("port", PortNum.Text);
            regName.SetValue("Baudrate", Baudrate.Text);
            regName.Close();
        }


        private void SetcodePort()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.SetValue("codeport", CodePort1.Text);
            regName.SetValue("codeBaudrate", CodeBaud1.Text);
            regName.Close();
        }

        private void Read()
        {
            RegistryKey regName;

            regName = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set", true);

            if (regName is null)
            {
                regName = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\PMD\\1.0\\User-LL18-Set");
            }

            regName.OpenSubKey("User");
            if (regName.GetValue("port") is null)
            {
                PortNum.Text = "";
            }
            else
            {
                PortNum.Text = regName.GetValue("port").ToString();
            }
            if (regName.GetValue("Baudrate") is null)
            {
                Baudrate.Text = "9600";
            }
            else
            {
                Baudrate.Text = regName.GetValue("Baudrate").ToString();
            }
            if (regName.GetValue("codeport") is null)
            {
                CodePort1.Text = "COM8";
            }
            else
            {
                CodePort1.Text = regName.GetValue("codeport").ToString();
            }
            CodeBaud1.Text = "9600";



            regName.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //try
            //{
            //    timer1.Stop();
            //    TestPort1.Close();
            //    Stagenum();
            //}
            //catch (Exception ex)
            //{
            //    timer1.Stop();
            //}
        }

        private void PortBtnCon1_Click(object sender, EventArgs e)
        {
            try
            {
                Form1.f1.CodePort1.Close();
                //设置端口的参数，包括波特率等
                Form1.f1.CodePort1.BaudRate = int.Parse(CodeBaud1.Text);
                Form1.f1.CodePort1.PortName = CodePort1.Text;
                Form1.f1.CodePort1.DataBits = 8;
                Form1.f1.CodePort1.StopBits = System.IO.Ports.StopBits.One;
                Form1.f1.CodePort1.Parity = System.IO.Ports.Parity.None;
                Form1.f1.CodePort1.Open();
                if (Form1.f1.CodePort1.IsOpen)
                {
                    CodeIsComm1.Text = "已连接";
                    CodeIsComm1.ForeColor = Color.Green;
                    CodePort1.Enabled = false;
                    PortBtnCon1.Enabled = false;
                    CodeBaud1.Enabled = false;
                    SetcodePort();
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void PortBtnRefresh_Click(object sender, EventArgs e)
        {
            CodePort1.Items.Clear();
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            CodePort1.Items.AddRange(ports);
        }

        private void PortBtnBreak_Click(object sender, EventArgs e)
        {
            Form1.f1.CodePort1.Close();
            if (!Form1.f1.CodePort1.IsOpen)
            {
                CodeIsComm1.Text = "未连接";
                CodeIsComm1.ForeColor = Color.Red;
                CodePort1.Enabled = true;
                PortBtnCon1.Enabled = true;
                CodeBaud1.Enabled = true;
            }
        }
    }
}