/**
* crc16Modus
* @class crc16MODBUS
*/
'use strict';
class crc16MODBUS {
constructor() {
this.CRCMaster = {
StringToCheck: "",
CleanedString: "",
CleanString: function(inputType) {
if (inputType == "ASCII") {
this.CleanedString = this.StringToCheck;
} else {
if (this.StringToCheck.match(/^[0-9A-F \t]+$/gi) !== null) {
this.CleanedString = this._hexStringToString(this.StringToCheck.toUpperCase().replace(/[\t ]/g, ''));
} else {
console.log("String doesn't seem to be a valid Hex input.");
return false;
}
}
return true;
},
CRC16Modbus: function() {
var crc = 0xFFFF;
var str = this.CleanedString;
for (var pos = 0; pos < str.length; pos++) {
crc ^= str.charCodeAt(pos);
for (var i = 8; i !== 0; i--) {
if ((crc & 0x0001) !== 0) {
crc >>= 1;
crc ^= 0xA001;
} else
crc >>= 1;
}
}
return crc;
},
_hexStringToString: function(inputstr) {
var hex = inputstr.toString(); //force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
},
Calculate: function(str, inputType) {
this.StringToCheck = str;
if (this.CleanString(inputType)) {
return this.CRC16Modbus().toString(16).toUpperCase()
}
}
};
}
/**
* Расчет контрольной суммы
* @method transformationCRC16
*/
transformationCRC16( str ) {
return this.CRCMaster.Calculate( str, 'HEX' )
}
}
module.exports = crc16MODBUS