簡體   English   中英

C#串口通訊問題

[英]C# Serial Port communication issue

我在使用小型C#應用程序時遇到問題。 該應用程序必須通過串行端口連接到條形碼掃描儀,該掃描儀讀取數據矩陣代碼。 數據矩陣代碼表示一個字節數組,它是一個zip存檔。 我讀了很多有關SerialPort.DataReceived的工作方式的信息,但是找不到解決問題的優雅方法。 而且該應用程序應與其他條形碼掃描儀一起使用,因此我無法使其成為特定於掃描儀的。 這是我的一些代碼:

    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());

             }
        }

    }
}

所以我的問題是:我怎么知道我讀取了掃描儀發送的所有字節?

我已獲得用於讀取條形碼數據的代碼,該代碼在生產中已經完美地工作了幾年,如下所示:

請注意,我的應用程序必須讀取標准的UPC條形碼以及GS1 DataBar,因此您可能不需要一些代碼...

關鍵是:

string ScanData = ScannerPort.ReadExisting(); 

可以在DoScan部分中找到,只需將掃描數據作為字符串讀取即可。 它繞過了知道發送多少字節的需求,並使其余代碼更易於處理。


     // 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();
        }


    }

如SerialPort.DataReceived的文檔所述,“使用BytesToRead屬性來確定要在緩沖區中讀取多少數據。”

這是SerialPort.BytesToRead的文檔

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