Line 342: |
Line 342: |
| } | | } |
| | | |
− | CRC (Cyclic Redundancy Check) is an error-detecting code using for detect accidental changes to RAW data. The algorithm how to calculate CRC-16 (also known as CRC-16/IBM) you will find below.
| + | RC(Cyclic Redundancy Check) is an error - detecting code using for detect accidental changes to RAW data. |
| + | The algorithm how to calculate CRC - 16(also known as CRC - 16 / IBM) you will find below. |
| | | |
− | var crc = {
| + | var crc = { |
− | extractCRC: function(message){
| + | extractCRC: function (message) { |
− | crcData = message.slice(message.length-2,message.length);
| + | crcData = message.slice(message.length - 2, message.length); |
− | return crcData[0] * 256 + crcData[1];
| + | return crcData[0] * 256 + crcData[1]; |
− | },<br>
| + | }, |
− | crcCam: function(message, previous_crc){
| + | calculateCRC: function(message, previous_crc) { |
− | payload = message.slice(2, message.length-2);
| + | let crc_poly = 0x8408; |
− | crc = 0x0000;
| + | let idx = 0; |
− | bitOne = 0x0001;
| + | let crc = 0x0000; |
− | crcpoly = 0x8408;
| + | |
− | idx = 0;<br>
| + | /* the payload length is calculated with removing size of header and CRC (4 + 2 bytes) */ |
− | /*At this point you should start with the init value for CRC calculation. Init value for
| + | let payload_length = message.length - 6; |
− | * the first packet is zero and for the upcoming packets it is the CRC value of the previous package
| + | |
− | */
| + | /* the payload is separated from the message header and CRC (4 bytes ofset + length)*/ |
− | crc = previous_crc<br>
| + | let payload = message.slice(4, 4 + payload_length); |
− | while (idx < payload.length) {
| + | |
− | /* Use XOR operation for initial value and payload */
| + | /* Init value for the first message is zero and for the upcoming messages it is the CRC value of the previous message */ |
− | crc ^= payload[idx];
| + | crc = previous_crc; |
− | bitcounter = 0;<br>
| + | |
− | while (bitcounter < 8) {
| + | for (idx = 0; idx < payload_length; idx++) { |
− | crcFirstBit = crc & bitOne;
| + | let bit; |
− | crc >>= 1;<br>
| + | |
− | if (crcFirstBit) {
| + | /* Use XOR operation for initial value and payload */ |
− | crc ^= crcpoly;
| + | crc ^= payload[idx]; |
− | }
| + | |
− | }
| + | for (bit = 0; bit < 8; bit++) { |
− | idx = idx + 1;
| + | let carry_bit = crc & 0x01; |
− | }
| + | crc >>= 0x01; |
− | return crc;
| + | if (carry_bit != 0) { |
− | }
| + | crc ^= crc_poly; |
− | };
| + | } |
− | exports.crc = crc;
| + | } |
| + | } |
| + | |
| + | return crc; |
| + | } |
| + | }; |
| + | exports.crc = crc; |
| | | |
| ==File transfer visual flow== | | ==File transfer visual flow== |