DCON

<< Click to Display Table of Contents >>

Navigation:  Multi-Protocol MasterOPC Server > Lua 5.1 Reference Manual > Examples and Other Useful Things > Examples of Calculations of Checksums >

DCON

The function server.SendAndReciveDataByMask supports calculation of DCON checksum. To provide this, you should set the parameter of checksum calculation to 1. However, it is required the full correspondence to a frame of the DCON format in this mode (the last frame symbol is CR, carriage return). There are devices that use a protocol, which is similar to DCON but use the different last symbol - for example, two symbols, CR LF. In this case, the standard algorithm of calculation cannot be used, and you need to write calculation yourself.

The checksum of DCON is a 2-byte number, and the algorithm of its calculation is very simple: it is a sum of all bytes modulo 256. Below is a request example:

$012

Convert symbols to bytes (http://www.asciitable.com) and summarize; the checksum is 0xB7

0x24h + 0x30h + 0x31 + 0x32 = 0xB7

Example of DCON checksum calculation function:

function DCONcrc(str)

   crc=0;

   for i=1,string.len(str),1 do    

       local byte=string.byte(str,i);--get the byte required

       crc=math.fmod((crc+byte),256); --divide modulo 256

   end;

   return string.format("%02X",crc); --convert to a string and return the sum calculated

end;

Example of the use

val="!01070600";

CRC=DCONcrc(val);

--CRC = AF

In order to integrate the function to your code, use the output argument number 4 (the buffer string received) of the function server.SendAndReceiveDataByMask. After that, you should prepare the string received, that is, check the end symbols, extract two bytes of the checksum, pass a string up to the cheksum to the function (use the function string.sub), and compare a result of the function with the checksum received from the device.  

After that, you can start to analyze values received by the mask.