How to pars the text and extract some parts and assigning them to variables in visual studio .Net without interfering with the received data from serial port?

Goharshenasanesfahani, Sahar 0 Reputation points
2024-05-28T15:45:37.88+00:00

I have a received data from com port in this format:

************************* General Device Configuration *************************

Flash address...............0x40100180

Memory allocated............256

Size on disk................188

Parameters:

Config version ID:          0

DeviceID:

                            11006

Serial Number:

                            11006

App Version:                3.3.4

Fota Version:               1.2.0

Bootloader Version:         1.0.0

****************************** Cell Configuration ******************************

Flash address...............0x40100280

Memory allocated............2048

Size on disk................1024

Parameters:

Access point:

                            0

Context ID:                 1

PDP Type:                   IP

AT connection command:

AT command:                 at+cereg?

Response string:            +CEREG: 0,1

Response Wait Time:         2000

Retry Count:                10

Retry Delay:                5000

AT power-down command:

AT command:                 at+qpowd=0

Response string:            OK

Response Wait Time:         500

Retry Count:                1

Retry Delay:                500

AT power-up command:

<sequence terminator>

****************************** FOTA Configuration ******************************

Flash address...............0x40100A80

Memory allocated............512

Size on disk................120

Parameters:

FTP server IP address:      44.197.124.42

FTP user name:

FTP password:               4

Desired App Version:

OTA Requested:              false

Manual Mode:                disabled

I am trying to extract some values, but I want it to separate them based on the sections header. The code that I am using right now is interfering and messing up with the received data which I can see in a text box on my main form.

This is my code snippet:

private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

{

try

{

    // Set a timeout value for reading from the serial port

    //SerPort.ReadTimeout = 10000; // Timeout in milliseconds (adjust as needed)

    string receivedData = SerPort.ReadLine(); // Read a line from the serial port

    UpdateReceivedData(receivedData);

    // If the received data contains "General Device Configuration", start parsing

    if (receivedData.Contains("General Device Configuration"))

    {

        // Keep reading lines until the end of the section

        StringBuilder sectionData = new StringBuilder();

        while (true)

        {

            string line = SerPort.ReadLine();

            sectionData.AppendLine(line);

            if (line.Contains("****"))

            {

                break;

            }

        }

        string generalDeviceConfigSection = sectionData.ToString();

        // Extract key-value pairs from the section

        ExtractKeyValuePairs(generalDeviceConfigSection);

    }

    

}

catch (TimeoutException tEx)

{

    // Handle timeout exception if necessary

    MessageBox.Show("Timeout occurred while reading from the serial port.");

}

catch (Exception ex)

{

    // Handle other exceptions

    MessageBox.Show($"Error occurred while reading from the serial port: {ex.Message}");

}

}

private void ExtractKeyValuePairs(string sectionData)

{

string[] lines = sectionData.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

foreach (string line in lines)

{

    string[] parts = line.Split(':');

    if (parts.Length == 2)

    {

        string key = parts[0].Trim();

        string value = parts[1].Trim();

        if (key == "DeviceID")

        {

            deviceId = value;

        }

        else if (key == "Serial Number")

        {

            serialNo = value;

        }

    }

}

}

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,887 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 43,046 Reputation points Microsoft Vendor
    2024-05-29T03:14:57.0033333+00:00

    Hi @Goharshenasanesfahani, Sahar , Welcome to Microsoft Q&A,

    You can use a dictionary to store the contents of each section, which can avoid data clutter and present the information of each section more clearly.

    1. When receiving data, separate it by section header:
    • Use a dictionary to store the data of each section.
    • When receiving a new data row, check whether it is a section header, and if so, start a new section record.
    1. Extract key-value pairs and store in a dictionary:
    • Extract and store the key-value pairs of each section separately by section header
    private Dictionary<string, StringBuilder> sectionsData = new Dictionary<string, StringBuilder>();
    private StringBuilder currentSectionData = null;
    private string currentSectionTitle = string.Empty;
    
    private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            string receivedData = SerPort.ReadLine();
            UpdateReceivedData(receivedData);
    
            // Check if the received line is a section title
            if (receivedData.StartsWith("General Device Configuration"))
            {
                currentSectionTitle = "General Device Configuration";
                currentSectionData = new StringBuilder();
                sectionsData[currentSectionTitle] = currentSectionData;
            }
    
            // If currently in a section, append the line to the section data
            if (currentSectionData != null)
            {
                currentSectionData.AppendLine(receivedData);
    
                // Check for end of section marker
                if (receivedData.Contains("****"))
                {
                    currentSectionData = null;
                }
            }
        }
        catch (TimeoutException)
        {
            MessageBox.Show("Timeout occurred while reading from the serial port.");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error occurred while reading from the serial port: {ex.Message}");
        }
    }
    
    private void ExtractKeyValuePairs(string sectionTitle, string sectionData)
    {
        string[] lines = sectionData.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string line in lines)
        {
            string[] parts = line.Split(':');
            if (parts.Length == 2)
            {
                string key = parts[0].Trim();
                string value = parts[1].Trim();
                
                // Process the key-value pair as needed, here is an example:
                if (sectionTitle == "General Device Configuration")
                {
                    if (key == "DeviceID")
                    {
                        deviceId = value;
                    }
                    else if (key == "Serial Number")
                    {
                        serialNo = value;
                    }
                }
            }
        }
    }
    
    private void UpdateReceivedData(string receivedData)
    {
        // Assuming this method updates the main form's text box with the received data
        // For example:
        textBoxReceivedData.AppendText(receivedData + Environment.NewLine);
    
        // After updating, check if there are any completed sections to process
        foreach (var section in sectionsData)
        {
            if (section.Value.ToString().Contains("****"))
            {
                ExtractKeyValuePairs(section.Key, section.Value.ToString());
            }
        }
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.