0

I am working on modbus protocol in C#. I am able to send a single request and get a response from it. I am using a DataReceivedHandler to read from incoming port

 public ModBusEngine()
    {
        //serial port settings and opening it
        port.ReadTimeout = 500;

        port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        port.Open();

        
       
    }

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {


        //port.ReadTimeout = 200;
        

        // send request and waiting for response
        // the request needs: slaveId, dataAddress, registerCount 
        Thread.Sleep(200);
        Console.WriteLine("Bytes recieved are " + port.BytesToRead);
        try
        {
            receivedBytes = port.BaseStream.Read(buffer, 0, (int)buffer.Length);
            var receiveData = BitConverter.ToString(buffer, 0, receivedBytes);
            var finalData = receiveData.Replace("-", "");

            new Thread(() =>
            {
                SaveData(finalData);
            }).Start();
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
       
    }

I am writing to a port in another method

 private void ModbusMethod(Iterations iterations)
    {
        Console.WriteLine("Starting Modbuss Scheduling data...");
        try
        {
            var items = new byte[]{ Convert.ToByte(iterations.hex), 0x03, 0x00, 0x00, 0x00, 0x03 };
            //iterations.hex is device id
            var crc = BitConverter.GetBytes(ModRTU_CRC(items, items.Length)); //ComputeChecksum(items);

            var dataItems = items.Concat(crc).ToArray();

            port.BaseStream.Write(dataItems, 0, dataItems.Length);

            
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }                      

    }

I am successfully able to send are receive a response.

What I want to do now?

There are multiple registers from which I can get data from the device. These addresses are not completely in sequential order. For example, see below pictures

enter image description here enter image description here

As shown in the above images addresses from 0000 to 0006 are in a sequence then the register is skipped 3 times and the next address is 0009 after that it's again sequential till the address 003A. Then again registers are skipped and start from 0100 to 012E in sequence.

I only want to read certain registers i.e. from 0000 to 0002 than from 000E to 003A and finally from 0100 to 012E. One way is to send the frame one by one and then do the needful with the data. But I want to send them in a single request.

I want to do the following.

  1. Combining the request and send it in one frame

    var req1 = new byte[]{ Convert.ToByte(iterations.hex), 0x03, 0x00, 0x00, 0x00, 0x03 };// msn and meter id var req2 = new byte[]{ Convert.ToByte(iterations.hex), 0x03, 0x00, 0x0E, 0x00, 0x46 }; // energy values var req3 = new byte[]{ Convert.ToByte(iterations.hex), 0x03, 0x01, 0x00, 0x00, 0x48 };// energy values other

var items = req1.concat(req2).concat(req3);

I am not sure that this approach will work or not. I don't know how to do it but I don't want to send the frame one by one as the handler is continuously reading the port.

  1. Collect all the requests data and then save the data.

Any help would be highly appreciated.

8
  • I don't quite get your idea. Modbus has only one function code to read holding registers, which is function code 0x03. It supports contiguous read. The only two choices are : 1. read a bulk data from 0x0000~0x012E , or read different areas multiple times. I will write an answer for suggestion.
    – Louis Go
    Jul 7, 2020 at 11:59
  • @LouisGo The main issue is that all the registers are not in the sequence. For now I have managed to get data till 01 03 00 00 00 61 which includes meter msn to L3 reactive energy half value if I send the frame 01 03 00 00 00 62 the meter stops responding
    – Moeez
    Jul 9, 2020 at 9:26
  • @LouisGo I am just 9 values away of getting all the required data. But I am stuck
    – Moeez
    Jul 9, 2020 at 9:26
  • Just get a larger range of data and get only what you want. It reduce much overhead of communication. Like what I wrote in the answer.
    – Louis Go
    Jul 9, 2020 at 12:28
  • @LouisGo I am getting the larger range of data and within that range, I am unable to get my required values?
    – Moeez
    Jul 9, 2020 at 16:40

1 Answer 1

0

Assumption

Detail use case isn't provided, so I'll assume this use case needs to continuously sending read requests and process responses.


How to send request? ----- Not much choice, either read at once or split them into small areas. It depends on your [baudrate](https://en.wikipedia.org/wiki/Baud) and required probe interval.

Assume a bulk read from 0x000~0x003A + 0x0100~0x012E is T and read from 0x0000~0x012E is 3T. You may calculate communication time here.

  1. If required interval is much greater than 3T, then read from 0x0000~0x012E seems okay for this case.
  2. If required interval is near 1~3T, then either increasing baudrate or using multiple bulk read are okay.

My suggestion is to read two area 0x000~0x003A + 0x0100~0x012E as a general case, since at least reduce read time by T.


How to design ---- My suggestion is keep repeating send and collect it. It's old school but easy to understand for future maintainer.

Following are pseudo code for a state machine while abstracting send and receive.

enum EReadState{
    First,
    Second,
    Third
}
EReadState state = EReadState.First; // I use enum if you have more than two areas need to be read
ManualResetEvent mre = new ManualResetEvent();
void StartPolling()
{
    while(true){
        
        switch( state ){
            case First:
                SendFirstPartRequest();
                break;
            case Second:
                SendSecondPartRequest();
                break;
            case Third:
                SendThirdPartRequest();
                break;
        }
        mre.WaitOne() /  wait for one data received
        // Don't forget implement your break condition
    }
}

void Receive()
{
    var data = ... // get data
    state = setNextState( data ); // If first part is received, set state to second.
    mre.Set(); // Go to next send
}
2
  • mre.WaitOne() after that which break condition is occurred ?
    – Moeez
    Jul 10, 2020 at 4:37
  • Receive() would call mre.Set() to let it send next message.
    – Louis Go
    Jul 10, 2020 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.