Разбор входного сигнала датчика в Windows Forms Application - PullRequest
0 голосов
/ 01 февраля 2020

Я пытаюсь проанализировать входные данные из LiDaR OSI LaserScan AutoSense 615 либо в консольном приложении, либо в приложении Windows Forms с использованием C#.

По данным производителя, вывод LiDaR является байтовым 11111110, за которым следуют тридцать байтов данных интенсивности (со значениями между 00000000 и 11111111 включительно) и тридцать байтов данных диапазона (со значениями между 00000000 и 11111101 включительно), затем байт 11111111, за которым следуют тридцать байтов данных интенсивности и тридцать байтов данных диапазона.

Выходной сигнал LiDaR передается через собственный десятиконтактный порт на девятиконтактный порт RS-422 с внутренней резьбой, затем через девятиконтактный порт RS-422 с наружной резьбой, адаптер RS-422 на USB производства SeaLevel и порт USB 2.0. Я установил драйвер «SeaCOM для Windows v3.7.4». В диспетчере устройств Windows я установил скорость передачи 14400. Скорость передачи 9600 генерирует аналогичные результаты. Я также попробовал Prolifi c USB-порт последовательного порта, который преобразует RS-232 в USB, и сгенерировал аналогичные результаты.

Я создал следующее приложение Windows Form, которое, учитывая приведенный ниже код, отображающий положение байта заголовка ведущего луча (11111110) в массиве байтов, длина которого равна длине двух информационных пакетов или 2 * 61 байта. Эта позиция в большинстве случаев состоит из одной цифры. Это правильный стартовый байт? Я понял, что когда я конвертирую массив байтов в BitArray, биты байта читаются справа налево. Все еще хорошо читать байты, начиная с позиции с меньшим индексом и переходя к большему индексу?

Если я нашел позицию 11111110, я оцениваю, находится ли байт 11111111 в этой позиции плюс 61. Иногда байт 11111111 найдено, в большинстве случаев это не так. Существуют ли стоп-биты, связанные с протоколом RS-422, которые мне не хватает? Мой кабель не может собрать все биты? Должен ли я просто начать с 11111110, собрать еще шестьдесят байтов, а затем начать искать 11111111?

enter image description here

namespace Serial_Communication
{
    public partial class formSerialCommunication : System.Windows.Forms.Form
    {

        // Constructor formSerialCommunication initializes form components.
        public formSerialCommunication()
        {
            InitializeComponent();
        }


        // On loading formSerialCommunication, add available port names
        // to comboBoxAvailablePorts.
        void formSerialCommunication_Load(object sender, System.EventArgs e)
        {
            comboBoxAvailablePorts.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
        }


        // Define a buttonOpenPort.Click event handler.
        private void buttonOpenPort_Click(object sender, System.EventArgs e)
        {

            try
            {
                // If buttonOpenPort has been clicked, but either a COM port is not selected
                // or the user has not entered a baud rate, add a message to textBoxReceivedData.
                if (comboBoxAvailablePorts.Text == "" || textBoxBaudRate.Text == "")
                {
                    textBoxReceivedData.Text = "Please select port and enter baud rate.";
                }

                else
                {
                    // Transfer the name of the selected COM port
                    // to serialPortAssociatedWithFormSerialCommunication.
                    serialPortAssociatedWithFormSerialCommunication.PortName =
                        comboBoxAvailablePorts.Text;

                    // Transfer the user's baud rate
                    // to serialPortAssociatedWithFormSerialCommunication.
                    serialPortAssociatedWithFormSerialCommunication.BaudRate =
                        System.Convert.ToInt32(textBoxBaudRate.Text);

                    // Try to open the serial port.
                    serialPortAssociatedWithFormSerialCommunication.Open();

                    // Cause a transition of progressBarConnectionStatus
                    // from gray / empty to green / full.
                    progressBarConnectionStatus.Value = 100;

                    // Disable buttonOpenPort.
                    buttonOpenPort.Enabled = false;

                    // Enable buttonClosePort.
                    buttonClosePort.Enabled = true;

                    // Enable buttonReceiveData.
                    buttonReceiveData.Enabled = true;

                }

            }

            catch(System.UnauthorizedAccessException)
            {
                textBoxReceivedData.Text =
                    "An UnauthorizedAccessException has been caught." +
                    "The exception is thrown when the operating system denies access" +
                    "because of an input / output error or a specific type of security error.";
            }

        } // buttonOpenPort_Click


        // Define a buttonClosePort.Click event handler.
        private void buttonClosePort_Click(object sender, System.EventArgs e)
        {
            // Close serial port.
            serialPortAssociatedWithFormSerialCommunication.Close();

            // Set progress bar at gray / empty.
            progressBarConnectionStatus.Value = 0;

            // Enable buttonOpenPort.
            buttonOpenPort.Enabled = true;

            // Disable buttonClosePort.
            buttonClosePort.Enabled = false;

            // Disable buttonReceiveData.
            buttonReceiveData.Enabled = false;

            // Clear text from textBoxPositionOfLeadingBeamHeaderByteInTwoBurstInput.
            textBoxPositionOfLeadingBeamHeaderByteInTwoBurstInput.Text = "";

            // Clear text from textBoxReceivedData.
            textBoxReceivedData.Text = "";

        }


        // Create a buttonReceiveData.Click event handler.
        private void buttonReceiveData_Click(object sender, System.EventArgs e)
        {
            // Refresh textBoxPositionOfLeadingBeamHeaderByteInTwoBurstInput.
            textBoxPositionOfLeadingBeamHeaderByteInTwoBurstInput.Text = "";

            // Refresh textBoxReceivedData.
            textBoxReceivedData.Text = "";

            try
            {
                // Define the number of bytes transmitted in one information burst
                // from an OSI LaserScan AutoSense 615 LiDaR.
                int bytesInInformationBurst = 61;

                // Define the number of bits transmitted in one information burst
                // from an OSI LaserScan AutoSense 615 LiDaR.
                int bitsInInformationBurst = 8 * bytesInInformationBurst;

                // Declare a buffer for bytes from the serial port.
                byte[] bufferAsByteArray = new byte[2 * bytesInInformationBurst];

                // Define an offset at which to write bytes in bufferAsByteArray.
                int offset = 0;

                // Read into bufferAsByteArray starting at position offset
                // bytesTransmittedInASecond bytes.
                serialPortAssociatedWithFormSerialCommunication.Read(
                    bufferAsByteArray,
                    offset,
                    2 * bytesInInformationBurst);

                // Considering each byte in bufferAsByteArray...
                for (int i = 0; i < bytesInInformationBurst; ++i)
                {
                    // If the present byte is 1111110...
                    if (bufferAsByteArray[i] == 0xFE)
                    {
                        // Display the position of the present byte in bufferAsByteArray.
                        textBoxPositionOfLeadingBeamHeaderByteInTwoBurstInput.Text =
                            System.Convert.ToString(i);

                        if (bufferAsByteArray[i + 61] == 0xFF)
                        {
                            textBoxPositionOfLeadingBeamHeaderByteInTwoBurstInput.Text +=
                                ";" + System.Convert.ToString(i + 61);
                        }

                        break;
                    }

                }

            } // try

            catch(System.TimeoutException)
            {
                textBoxReceivedData.Text =
                    "A TimeoutException has been caught." +
                    "The exception is thrown when the time allotted for a process or operation" +
                    "has expired.";
            } // catch(TimeoutException)

        }


    }

}
...