Exemple #1
0
        private void btnOpenCom_Click(object sender, EventArgs e)
        {
            if (btnOpenCom.Text == "打开连接")
            {
                if (modbus.Open(cmbPort.Text, int.Parse(cmbBaudRate.Text), int.Parse(cmbDataBits.Text),
                                (Parity)cmbParity.SelectedIndex, (StopBits)int.Parse(cmbStopBit.Text), -1, -1))
                {
                    lblState.Text        = modbus.PortName + "端口已经打开";
                    gBoxCOM.Enabled      = false;
                    btnOpenCom.Text      = "断开连接";
                    btnOpenCom.BackColor = Color.Plum;

                    timer1.Start();
                    btnOffTimer.Text = "停止刷新";
                }
            }
            else
            {
                timer1.Stop();
                btnOffTimer.Text = "自动刷新";
                CommonTools.Delay(1000);
                if (modbus.Close())
                {
                    lblState.Text        = "连接未打开";
                    gBoxCOM.Enabled      = true;
                    btnOpenCom.Text      = "打开连接";
                    btnOpenCom.BackColor = Color.Lime;
                }
            }
        }
        void SPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            CommonTools.Delay(500);
            if (!IsOpen)
            {
                return;
            }
            if (SPort.BytesToRead > 0)
            {
                byte[] dataBytes = new byte[SPort.BytesToRead];
                SPort.Read(dataBytes, 0, SPort.BytesToRead);

                //SPort.DiscardInBuffer();
                //SPort.DiscardOutBuffer();

                //               string strDebug = CommonTools.ToHexString(dataBytes); //调试用
                if (CheckResponse(dataBytes, dataBytes.Length))
                {
                    ReceivedData(CommonTools.ToHexString(dataBytes));
                }
                else
                {
                    ReceivedData("CRC_Error");
                }
            }
        }