public partial class MainForm : Form
    {
        System.IO.Ports.SerialPort serialport = new System.IO.Ports.SerialPort();//宣告連接埠
        Boolean light = false, serialportopen = false;
        
        public MainForm()
        {
            InitializeComponent();
            
            foreach(string com in System.IO.Ports.SerialPort.GetPortNames())//取得所有可用的連接埠
            {
                cbPortName.Items.Add(com);
            }
            if (cbPortName.Items.Count > 0)
                cbPortName.SelectedIndex = 0;
            
            cbCmd.Items.Add("0-讀取");
            cbCmd.Items.Add("1-寫入");
            cbCmd.Items.Add("7-強制ON");
            cbCmd.Items.Add("8-強制OFF");
            if(cbCmd.Items.Count>1)
                cbCmd.SelectedIndex=0;
        }
        
        void Button1Click(object sender, EventArgs e)
        {
            if (serialportopen == false && !serialport.IsOpen)
            {
                try
                {
                    //設定連接埠
                    serialport.PortName = cbPortName.Text;//連線埠
                    serialport.BaudRate = 9600;//鮑率
                    serialport.DataBits = 7;//數據位元
                    serialport.Parity = System.IO.Ports.Parity.Even;//偶同位
                    serialport.StopBits = System.IO.Ports.StopBits.One;//停止位元
                    serialport.Encoding = Encoding.Default;//傳輸編碼方式
                    serialport.Open();
                    serialportopen = true;
                    button2.Enabled = true;
                    txtSTX.Enabled = true;
                    if (this.backgroundWorker1.IsBusy != true)
                    {
                        this.backgroundWorker1.WorkerReportsProgress = true;
                        this.backgroundWorker1.RunWorkerAsync();
                    }
                    button1.Text = "中斷";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else if (serialportopen == true && serialport.IsOpen)
            {
                try
                {
                    serialport.Close();
                    if (!serialport.IsOpen)
                    {
                        serialportopen = false;
                        button2.Enabled = false;
                        txtSTX.Enabled = false;
                        this.backgroundWorker1.WorkerReportsProgress = false;
                        this.backgroundWorker1.CancelAsync();
                        this.backgroundWorker1.Dispose();
                        label3.ForeColor = Color.Red;
                        button1.Text = "連線";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        

        private void Button2Click(object sender, EventArgs e)
        {
            try
            {
                string str = "";
                //STX Cmd Addrs Bytes Data ETX SUM
                //str = (Char)2 + "70008" + (Char)3 + "02";//M0
                //str = (Char)2 + "70108" + (Char)3 + "03";//M1
                //str = (Char)2 + "70208" + (Char)3 + "04";//M2
                //str = (Char)2 + "70308" + (Char)3 + "05";//M3
                str = (Char)2 + txtCmd.Text + txtAddrs.Text + txtBytes.Text + txtData.Text + (Char)3 + txtSum.Text;
                serialport.Write(str);
                AddText(MsgType.Error, "傳送:" + str + "\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar==(Char)13)
            {
                Button2Click(sender, e);
            }
        }

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            for (; ; )
            {
                if (backgroundWorker1.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    try
                    {
                        backgroundWorker1.ReportProgress(0);
                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception)
                    {
                        e.Cancel = true;
                        break;
                    }
                }
            }
        }

        private void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                if (serialport.BytesToRead != 0)
                {
                    label2.Text = "緩衝區:" + serialport.BytesToRead.ToString();
                    AddText(MsgType.System, "接收:" + serialport.ReadExisting() + "\r\n");
                    serialport.DiscardInBuffer();
                }
            }
            catch(Exception)
            {}
        }

        private void AddText(MsgType msgtype, string msg)
        {
            richTextBox1.Invoke(new EventHandler(delegate
            {
                richTextBox1.SelectedText = string.Empty;
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
                richTextBox1.SelectionColor = MsgTypeColor[(int)msgtype];
                richTextBox1.AppendText(msg);
                richTextBox1.ScrollToCaret();
            }));
        }
        
        //FX2N CheckSum,取 CMD、ADDR、DATA、ETX 各字元的 ASCII碼 16進位表示法 加總,然後取最後兩個字元。
        private string CheckSum()
        {
            //宣告:int為整數、string為字符串
            int sum = 0;
            string checkstring = "";
            string checksum = "";
        
            //通訊格式中的英文字符必須為大寫(a~f),故先行將text所輸入之傳送數據,經由程序自動轉換為大寫字母,然後加上結束碼etx:chr(3),形成一字符串checkstring
            checkstring = (String)txtCmd.Text + txtAddrs.Text + txtBytes.Text + txtData.Text + (Char)3;
        
            // for屬於重複結構中之計數循環,指令pc在一定的次數內,重複的執行某一敘述區段,亦即取出checkstring字符串中每一個字符,並累加每一個字符的ascii碼,而得出一整數sum。
            for (int i = 0; i < checkstring.Length; i++) {
                sum = sum + Convert.ToInt32(checkstring[i]);
            }
        
            //將10進制整數sum轉換為16進制,並取其右邊二位數,即為所求檢查碼。
            checksum = String.Format("{0:X}", sum);
            checksum.PadLeft(2,'0');
            checksum = checksum.Substring(checksum.Length - 2, 2);
            
            return checksum;
        }
        
        void Button3Click(object sender, EventArgs e)
        {
            string sum = CheckSum();
            txtSum.Text = sum;
        }
        
        void CbCmdSelectedIndexChanged(object sender, EventArgs e)
        {
            string cmd = cbCmd.Text.Split('-')[0];
            txtCmd.Text = cmd;
        }
        
        void SendStr(string str)
        {
            try
            {
                //STX Cmd Addrs Bytes Data ETX SUM
                //str = (Char)2 + "70008" + (Char)3 + "02";//M0
                //str = (Char)2 + "70108" + (Char)3 + "03";//M1
                //str = (Char)2 + "70208" + (Char)3 + "04";//M2
                //str = (Char)2 + "70308" + (Char)3 + "05";//M3
                serialport.Write(str);
                AddText(MsgType.Error, "傳送:" + str + "\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

伊 發表在 痞客邦 PIXNET 留言(0) 人氣()