Modbus is a protocol that is used on top of TCP sockets or in the RTU version on top of working with a Serial port, or 485 interface, as far as I have seen.
For the protocol, there are open specifications on the official website, where Modbus is dealt with in detail by components, though in English. Modbus is needed, as a rule, to read registers from devices, or write data to them, even 1 bit each, and a number of additional properties. It can provide interaction between the program and the device in order to read the data measured by the device (battery charge, voltmeter reading, temperature) and adjust the device.
Briefly show what modbus rtu is:
')
unsigned char* response; response = new unsigned char[8]; ReadFile(hSer, (char*)response, 8, &size, 0);
So you can read the modbus rtu requests coming to the server. The structure is 8 bytes. FF is byte.
A message may come in the form: 02 03 A0 28 00 04 93 2A
Decrypt the message. 02 is the number of the device being accessed. 03 is the function number, i.e. 3 - read the registers, and sometimes it can also be written down, registers, 1-bit coils, etc.
A0 28 if transferred to the decimal system will be 41000 - the register number, 00 04 - then 4 more registers must be counted from 41000. The last 2 numbers are 2 bytes of the CRC16 code.
Once such a message has arrived, respectively, it is also necessary to fill in the array on the sending side, and forward either via tcp sockets, or through the com port, or in another way.
The answer is also filled in, but there will already be a message of the form: 02 03 08 00 01 00 02 00 03 00 04 95 8 i.e. device code, function code, number of bytes transferred, 1234 data (these are like register values). 2 bytes CRC code.
The CRC code is calculated from the message not including 2 bytes of the CRC code. This is for function 3. In the code:
unsigned char* request request = new unsigned char[reqsize];
Fill in the data and calculate the CRC:
crc.i = CRC16((unsigned char *)request, reqsize-2); request[reqsize-2] = crc.ch[1]; request[reqsize-1] = crc.ch[0];
And send via Serial port:
BOOL iRet = WriteFile(hSer, (char*)request, reqsize, &dwBytesWritten, NULL );
Thus, they sent and responded to function 3 (reading several registers) using the Modbus protocol.
Thanks for attention! Read the specifications on the official protocol site.