dlms-protocol
Version:
DLMS Protocol parser for JavaScript
84 lines (83 loc) • 2.67 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
require("core-js/modules/es.parse-int.js");
require("core-js/modules/es.regexp.to-string.js");
require("core-js/modules/esnext.iterator.map.js");
require("core-js/modules/web.dom-collections.iterator.js");
var _DlmsDataType = _interopRequireDefault(require("../enum/DlmsDataType"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
class DlmsOctetString {
constructor() {
let data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let insert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.tag = _DlmsDataType.default.OCTET_STRING;
this.totalBytes = 0;
this.rawValue = [];
this.bodyBytes = [];
this.value = '';
this.len = 0;
if (data) {
if (typeof data === 'string') {
this.insertValue(data);
} else if (Array.isArray(data)) {
if (insert) {
this.initializeFromBytes(data, insert);
} else {
this.insertData(data);
}
}
}
}
getStandardLength() {
return 2;
}
getValue() {
return this.value;
}
initializeFromBytes(data) {
let insert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.len = data.length;
this.bodyBytes = Array.from(data);
this.value = this._bytesToString(this.bodyBytes);
this.totalBytes = this.bodyBytes.length + 2;
this.rawValue = [this.tag, this.len, ...this.bodyBytes];
}
insertData(data) {
if (this.tag !== data[0]) {
throw new Error("Tag mismatch.");
}
let size = data[1];
if (size < 0x80) {
this.len = size;
size = 0;
} else {
size = size - 0x80;
const lenArray = data.slice(2, 2 + size);
this.len = parseInt(this._bytesToHex(lenArray), 16);
}
this.bodyBytes = data.slice(2 + size, 2 + size + this.len);
this.value = this._bytesToString(this.bodyBytes);
this.rawValue = [this.tag, ...data.slice(1)];
this.totalBytes = this.rawValue.length;
}
insertValue(data) {
this.value = data;
this.len = data.length / 2;
this.bodyBytes = [];
for (let i = 0; i < data.length; i += 2) {
this.bodyBytes.push(parseInt(data.substr(i, 2), 16));
}
this.rawValue = [this.tag, this.len, ...this.bodyBytes];
this.totalBytes = this.rawValue.length;
}
_bytesToString(bytes) {
return String.fromCharCode(...bytes);
}
_bytesToHex(bytes) {
return bytes.map(byte => byte.toString(16).padStart(2, '0')).join('');
}
}
exports.default = DlmsOctetString;