简体   繁体   English

C#串口通讯问题

[英]C# Serial Port communication issue

I have a problem with a small C# application. 我在使用小型C#应用程序时遇到问题。 The application has to connect through a serial port to a bar code scanner which reads a Data Matrix code. 该应用程序必须通过串行端口连接到条形码扫描仪,该扫描仪读取数据矩阵代码。 The Data Matrix code represents an array of bytes which is a zip archive. 数据矩阵代码表示一个字节数组,它是一个zip存档。 I read a lot about the way SerialPort.DataReceived work but I can't find an elegant solution to my problem. 我读了很多有关SerialPort.DataReceived的工作方式的信息,但是找不到解决问题的优雅方法。 And the application should work with different bar code scanners so i can't make it scanner specific. 而且该应用程序应与其他条形码扫描仪一起使用,因此我无法使其成为特定于扫描仪的。 Here is some of my code: 这是我的一些代码:

    using System;
    using System.IO;
    using System.IO.Ports;
    using System.Windows.Forms;
    using Ionic.Zip;

    namespace SIUI_PE
    {
        public partial class Form1 : Form
        {
            SerialPort _serialPort;

        public Form1()
        {

            InitializeComponent();


        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                _serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.ToString());
                return;
            }
            _serialPort.Handshake = Handshake.None;
            _serialPort.ReadBufferSize = 10000;
            _serialPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
            _serialPort.Open();

        }
        void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           byte[] data = new byte[10000];
           _serialPort.Read(data, 0, 10000);
           File.WriteAllBytes(Directory.GetCurrentDirectory() + "/temp/fis.zip", data);
             try
             {
                 using (ZipFile zip = ZipFile.Read(Directory.GetCurrentDirectory() + "/temp/fis.zip"))
                 {
                     foreach (ZipEntry ZE in zip)
                     {
                         ZE.Extract(Directory.GetCurrentDirectory() + "/temp");
                     }
                 }
                 File.Delete(Directory.GetCurrentDirectory() + "/temp/fis.zip");

             }
             catch (Exception ex1)
             {
                 MessageBox.Show("Corrupt Archive: " + ex1.ToString());

             }
        }

    }
}

So my question is: How can I know that I read all the bytes the scanner sent? 所以我的问题是:我怎么知道我读取了扫描仪发送的所有字节?

The code I've got for reading barcode data, which has been working flawlessly in production for several years looks like this: 我已获得用于读取条形码数据的代码,该代码在生产中已经完美地工作了几年,如下所示:

Note, my app has to read standard UPC barcodes as well as GS1 DataBar, so there's a bit of code you may not need... 请注意,我的应用程序必须读取标准的UPC条形码以及GS1 DataBar,因此您可能不需要一些代码...

The key line in this is: 关键是:

string ScanData = ScannerPort.ReadExisting(); 

which is found in the DoScan section, and simply reads the scan data as a string. 可以在DoScan部分中找到,只需将扫描数据作为字符串读取即可。 It bypasses the need to know how many bytes are sent, and makes the rest of the code easier to deal with. 它绕过了知道发送多少字节的需求,并使其余代码更易于处理。


     // This snippet is in the Form_Load event, and it initializes teh scanner
        InitializeScanner();
        ScannerPort.ReadExisting();
        System.Threading.Thread.Sleep(1000);
     // ens snippet from Form_Load.

        this.ScannerPort.DataReceived += new SerialDataReceivedEventHandler(ScannerPort_DataReceived);


delegate void DoScanCallback();  // used for updating the form UI

void DoScan()
    {
        if (this.txtCouponCount.InvokeRequired)
        {
            DoScanCallback d = new DoScanCallback(DoScan);
            this.Invoke(d);
            return;
        }
        System.Threading.Thread.Sleep(100);
        string ScanData = ScannerPort.ReadExisting();
        if (isInScanMode)
        {
            try
            {
                HandleScanData(ScanData);
            }
            catch (Exception ex)
            {
                     System.Media.SystemSounds.Beep.Play();
                     MessageBox.Show("Invalid Scan");
            }
        }
    }
    void ScannerPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        // this call to sleep allows the scanner to receive the entire scan.
        // without this sleep, we've found that we get only a partial scan.
        try
        {
            DoScan();
        }
        catch (Exception ex)
        {
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show("Unable to handle scan event in ScannerPort_DataReceived." + System.Environment.NewLine + ex.ToString());
        }

    }
    void Port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
    {

          System.Media.SystemSounds.Beep.Play();
          MessageBox.Show(e.EventType.ToString());
    }
    private void HandleScanData(string ScanData)
    {
        //MessageBox.Show(ScanData + System.Environment.NewLine + ScanData.Length.ToString());

        //Determine which type of barcode has been scanned, and handle appropriately.
        if (ScanData.StartsWith("A") && ScanData.Length == 14)
        {
            try
            {
                ProcessUpcCoupon(ScanData);
            }
            catch (Exception ex)
            {
                     System.Media.SystemSounds.Beep.Play();
                     MessageBox.Show("Unable to process UPC coupon data" + System.Environment.NewLine + ex.ToString());

            }
        }
        else if (ScanData.StartsWith("8110"))
        {
            try
            {
                ProcessDataBarCoupon(ScanData);
            }
            catch (Exception ex)
            {
                     System.Media.SystemSounds.Beep.Play();
                     MessageBox.Show("Unable to process DataBar coupon data" + System.Environment.NewLine + ex.ToString());
            }
        }
        else
        {
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show("Invalid Scan" + System.Environment.NewLine + ScanData);
        }


    }


    private void InitializeScanner()
    {
        try
        {
            ScannerPort.PortName = Properties.Settings.Default.ScannerPort;
            ScannerPort.ReadBufferSize = Properties.Settings.Default.ScannerReadBufferSize;
            ScannerPort.Open();
            ScannerPort.BaudRate = Properties.Settings.Default.ScannerBaudRate;
            ScannerPort.DataBits = Properties.Settings.Default.ScannerDataBit;
            ScannerPort.StopBits = Properties.Settings.Default.ScannerStopBit;
            ScannerPort.Parity = Properties.Settings.Default.ScannerParity;
            ScannerPort.ReadTimeout = Properties.Settings.Default.ScannerReadTimeout;
            ScannerPort.DtrEnable = Properties.Settings.Default.ScannerDtrEnable;
            ScannerPort.RtsEnable = Properties.Settings.Default.ScannerRtsEnable;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to initialize scanner.  The error message received will be shown next.  You should close this program and try again.  If the problem persists, please contact support.", "Error initializing scanner");
            MessageBox.Show(ex.Message);
            Application.Exit();
        }


    }

As stated in the doc for SerialPort.DataReceived, "Use the BytesToRead property to determine how much data is left to be read in the buffer." 如SerialPort.DataReceived的文档所述,“使用BytesToRead属性来确定要在缓冲区中读取多少数据。”

here is the doc for SerialPort.BytesToRead 这是SerialPort.BytesToRead的文档

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM