rossmann-engineering / EasyModbusTCP.NET

Modbus TCP, Modbus UDP and Modbus RTU client/server library for .NET implementations
928 stars 402 forks source link

What is the best way to get string from register?? #42

Closed dj910624 closed 4 years ago

dj910624 commented 4 years ago

When I read register from Modbus server, I always convert each register element. Source code is follow:

data = modbusclient.ReadInputRegisters(12800, 123);
returnSize = data[2];
for (int u = 0; u < data.Length; u++)
{
       data[u] = (ushort)IPAddress.NetworkToHostOrder(Convert.ToInt16(data[u]));
}

if (returnSize == 244)
       string read_value = ModbusClient.ConvertRegistersToString(data, 3, returnSize - 4);
else
       string read_value = ModbusClient.ConvertRegistersToString(data, 3, returnSize);

It is really best way to convert register array to string ?? Thanks.

Padanian commented 4 years ago

Sorry, but I don't follow you here. You are reading 123 registers. Why returnsize can be 244?

dj910624 commented 4 years ago

Oh, 244 is the length of packet contents, When I request to 12800 address to server, they always return contents length with contents. For example, If I request 12800 address and 123 quantity, returned packet bytes length is 246 (123 * 2) and real contents length is 244(246 - header: 2 bytes). This number is always included in return_data[2].

Padanian commented 4 years ago

No, the content is 123 Int16. You have to work with Int16, not bytes.

When you need to reconvert the string, then and only then you will get two bytes from each register

rossmann-engineering commented 4 years ago

There are two static Methods for that purpose:

public static string ConvertRegistersToString(int[] registers, int offset, int stringLength) public static int[] ConvertStringToRegisters(string stringToConvert)