чтение из последовательных портов в c # - PullRequest
0 голосов
/ 11 октября 2019

Я изо всех сил пытался сделать это в течение нескольких недель и получить все различные типы результатов от некоторых данных до нуля вообще, за исключением исключений с кодом и ошибками. В настоящее время я пытаюсь написать приложение, которое отправляет команду на последовательный порт, а затем ждет ответа, я могу отправлять команды правильно, но получение возвращаемых данных является проблемой. после того, как команда отправлена, она должна вернуть серию байтов в блоках по 256 и поместить их в массив byte [], пока не будет достигнут установленный объем, например 4096 байтов в кусках по 256 байт. затем передайте массив обратно, чтобы я мог сохранить в файл, я могу открыть создать и сохранить бинарный файл, чтобы не было проблем только с содержимым последовательного порта, я прочитал много-много материала с последовательным портом, и ни один из них не кажется кратким.

Я сделал графический интерфейс, и это код, пока стараюсь не обращать внимания на беспорядок, поскольку я сказал, что борюсь, и код повсюду. Я использую Visual Studio 2019 C #, любая помощь будет принята с благодарностью.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Threading;

namespace SerialApp1
{
    public partial class FormSerial : Form

    {
        int bytread;
        public byte[] spbuf;
        bool DataAvailable;
        int sport_NumberOfBytesRead;

        public FormSerial()
        {
            InitializeComponent();
            GetAvailablePorts();
            byte[] spbuf = new byte[256];

        }

        void GetAvailablePorts()
        {
            String[] ports = SerialPort.GetPortNames();
            cBoxPorts.Items.AddRange(ports);
        }

        //Serial stuff*****************************************************

        void SerialPort1_DataReceived(object Sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort1.BytesToRead != bytread) // Wrong number of bytes
                return;                                 // Does nothing
            spbuf = new Byte[bytread];
            // Try to read the data
            try { sport_NumberOfBytesRead = serialPort1.Read(spbuf, 0, bytread); }
            // If error, return failure
            catch (Exception) { sport_NumberOfBytesRead = -1; }
            DataAvailable = true;                       // Break read loop
        }

         void SerialPort1_ErrorReceived(object Sender, SerialErrorReceivedEventArgs e)
        {
            sport_NumberOfBytesRead = -1;               // Flag error occurred
            DataAvailable = true;             // Break wait loop
        }

        void GetData(byte[] Buffer, int Len)//, int Nbr)
        {
            DataAvailable = false;                    // No data yet
            bytread = Len;                      // Bytes to read
            do
            {                                        // Wait till data is available
                Thread.Sleep(10);
            } while (!DataAvailable);
            Buffer = spbuf;              // Pass the returned data to the caller
            //Nbr = bytread;   // Return the number of bytes read
        }


        //*********************************************************************************



        private void btnOpenP_Click(object sender, EventArgs e)
        {
            try
            {
                if(cBoxPorts.Text==""||cBoxBaud.Text=="")
                {
                    textBReceive.Text="Please select port settings";
                }
                else
                {
                    serialPort1.PortName = cBoxPorts.Text;
                    serialPort1.BaudRate = Convert.ToInt32(cBoxBaud.Text);
                    serialPort1.Open();
                    serialPort1.ReadTimeout = 10;
                    serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
                    serialPort1.ErrorReceived += new SerialErrorReceivedEventHandler(SerialPort1_ErrorReceived);
                    btnSend.Enabled = true;
                    btnReceive.Enabled = true;
                    btnOpenP.Enabled = false;
                    btnCloseP.Enabled = true;
                    textBSend.Enabled = true;
                    cBoxPorts.Enabled = false;
                    cBoxBaud.Enabled = false;
                    progressBar1.Value = 100;
                }                
            }
            catch(UnauthorizedAccessException)
            {
                textBReceive.Text = "Unauthorized Access";
            }
        }

        private void btnCloseP_Click(object sender, EventArgs e)
        {
            serialPort1.Close();            
            btnSend.Enabled = false;
            btnReceive.Enabled = false;
            btnOpenP.Enabled = true;
            btnCloseP.Enabled = false;
            textBSend.Enabled = false;
            cBoxPorts.Enabled = true;
            cBoxBaud.Enabled = true;
            progressBar1.Value = 0;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            //serialPort1.WriteLine(textBSend.Text);
            string nl = Environment.NewLine;
            string sts;
            sts = ("R," + textBSAd.Text + "," + textBLng.Text + "," + textBLWdt.Text + nl);
            serialPort1.WriteLine(sts);
            textBSend.Text = "";
            //GetData(spbuf, Convert.ToInt32(textBLng.Text), sport_NumberOfBytesRead);
            //GetData(spbuf, 256);
            try
            {

            }
            catch (TimeoutException)
            {
                textBReceive.Text = (textBReceive.Text + nl + "Timeout Exception");
                //textBReceive.Text = "Timeout Exception";            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().ToString()); //will print System.NullReferenceException for example
            }

            //for (int i = 0; i <= sport_NumberOfBytesRead; i++)//spbuf.Length - 1
            //    {
             //       if (i % 8 == 0) { textBReceive.Text = textBReceive.Text + nl + i.ToString("X3") + ": "; }
              //      textBReceive.Text = (textBReceive.Text += spbuf[i].ToString("X2"));
              //      textBReceive.Text = (textBReceive.Text += " ");
               // }
        }

        private void btnReceive_Click(object sender, EventArgs e)
        {
            string nl = Environment.NewLine;
            int nbrtr = 256;
            try
            {

                //ReadSerialdata(nbrtr);
                textBReceive.Text = textBReceive.Text + serialPort1.ReadLine();
            }
            catch (TimeoutException)
            {
                textBReceive.Text = (textBReceive.Text + nl + "Timeout Exception");
                //textBReceive.Text = "Timeout Exception";            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().ToString()); //will print System.NullReferenceException for example
            }
        }

        OpenFileDialog ofd = new OpenFileDialog();

        private void btnOBF_Click(object sender, EventArgs e)
        {
            ofd.ShowDialog();
            //BinaryReader br = new BinaryReader(File.OpenRead(ofd.FileName));
            byte[] afbytes = File.ReadAllBytes(ofd.FileName);
            string nl = Environment.NewLine;
            for (int i = 0; i <= afbytes.Length-1; i++)
            {
                if (i % 8 == 0) { textBReceive.Text = textBReceive.Text + nl + i.ToString("X3") + ": "; }
                textBReceive.Text = (textBReceive.Text += afbytes[i].ToString("X2"));
                textBReceive.Text = (textBReceive.Text += " ");
            }
        }

        private void btnSend2_Click(object sender, EventArgs e)
        {
            string nl = Environment.NewLine;
            string sts;
            sts = ("R," + textBSAd.Text + "," + textBLng.Text + "," + textBLWdt.Text + nl);
            serialPort1.WriteLine(sts);
            //serialPort1.Write(nl);
            //MessageBox.Show(sts);
            try
            {
                ReadSerialdata(256);
                //Fill_Txt_Rec();
            }
            catch (TimeoutException)
            {
                textBReceive.Text = (textBReceive.Text + nl + "Timeout Exception");
                //textBReceive.Text = "Timeout Exception";            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().ToString()); //will print System.NullReferenceException for example
            }

        }

        public byte[] ReadSerialdata(int numBytes)
        {
            //byte[] spbuf = new byte[numBytes];
            for(int i = 0; i <= numBytes-1; i++)
            {
                spbuf[i] = (byte)serialPort1.ReadByte();
            }
            //serialPort1.ReadByte();
            foreach(byte bytVal in spbuf)
            {
                textBReceive.Text = (textBReceive.Text += (spbuf[bytVal].ToString("X2") + " "));
            }
            return spbuf;
        }

        private void Fill_Txt_Rec()
        {
            string nl = Environment.NewLine;

            for (int i=0; i >= spbuf.Length; i++)
            {
                if (i % 8 == 0) { textBReceive.Text = textBReceive.Text + nl + i.ToString("X3") + ": "; }
                textBReceive.Text = (textBReceive.Text += spbuf[i].ToString("X2"));
                textBReceive.Text = (textBReceive.Text += " ");
            }
        }
    }
}

спасибо,

извините за не ясность

бит у меня проблемы ссчитывает байты последовательно в байтовый массив из последовательного порта, а не передает этот байтовый массив обратно в вызывающую функцию. Мне нужно, чтобы приложение отправило команду на последовательный порт, а затем дождалось возвращения возвращаемых данных, которые являются необработанными байтами, у устройства нет проблем с получением команд и отправкой обратно данных, просто сторона c # считывает информацию обратно.

...