예제 #1
0
        private void btnSetting_Click(object sender, RoutedEventArgs e)
        {
            _serialPort = new GodSerialPort(txtCOM.Text, Convert.ToInt32(txtRate.Text), Parity.None, 8, StopBits.One)
            {
                DataFormat = SerialPortDataFormat.Hex,
                RtsEnable  = true,
                DtrEnable  = true
            };

            _serialPort.Open();

            if (!_serialPort.IsOpen)
            {
                Console.WriteLine("串口打开失败");
            }
            else
            {
                int interval = Convert.ToInt32(txtReceiveInterval.Text);

                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        var data = _serialPort?.ReadString();

                        this.Dispatcher.Invoke(() =>
                        {
                            if (!string.IsNullOrEmpty(data))
                            {
                                if (data.StartsWith("00 C7") || data.StartsWith("00 C8"))
                                {
                                    Console.WriteLine("收到注册包或心跳包" + data);
                                }
                                else
                                {
                                    content.Text = data + "\r\n";
                                }
                            }
                        });


                        Thread.Sleep(5000);
                    }
                });
            }
        }
예제 #2
0
        private void receiveWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _serialPort =
                    new GodSerialPort("COM8", 9600, Parity.None, 8, StopBits.One)
                {
                    DataFormat = SerialPortDataFormat.Hex,
                    RtsEnable  = true,
                    DtrEnable  = true
                };

                Open();

                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        var data = _serialPort.ReadString();

                        this.Dispatcher.Invoke(() =>
                        {
                            if (!string.IsNullOrEmpty(data))
                            {
                                this.rtxReceiveData.AppendText(data + "\n");
                            }
                        });

                        Thread.Sleep(3000);
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("串口数据接收错误:" + ex.ToString());
            }
        }