MqttDispatcher/dist/espthermtojson.js
Wolfgang Hottgenroth f44a7109b4 error handling
2017-08-28 15:00:30 +02:00

75 lines
2.6 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const log = require("./log");
const utils = require("./utils");
class EspThermError extends Error {
constructor(message) {
super(message);
}
}
exports.EspThermError = EspThermError;
class EspThermData {
constructor(temperature, voltage, timeConsumed) {
this.temperature = temperature;
this.voltage = voltage;
this.timeConsumed = timeConsumed;
}
toString() {
return JSON.stringify(this);
}
toJSON() {
return utils.jsonPrepaper(this, []);
}
}
exports.EspThermData = EspThermData;
class EspThermMetadata {
constructor(client, timestamp) {
this.client = client;
this.timestamp = (timestamp) ? timestamp : new Date();
}
toString() {
return JSON.stringify(this);
}
toJSON() {
return utils.jsonPrepaper(this, []);
}
}
exports.EspThermMetadata = EspThermMetadata;
class EspThermMessage {
constructor(client, temperature, voltage, timeConsumed) {
this.data = new EspThermData(temperature, voltage, timeConsumed);
this.metadata = new EspThermMetadata(client);
}
toString() {
return JSON.stringify(this);
}
toJSON() {
return utils.jsonPrepaper(this, []);
}
}
exports.EspThermMessage = EspThermMessage;
function espThermToJson(message) {
let messageStr = "" + message;
let parts = messageStr.split(' ');
if (parts.length != 4) {
throw new EspThermError(`too few or too much, ${parts.length} elements in message, it was "${message}"`);
}
let clientId = parts[0];
let temperature = parseFloat(parts[1]);
log.info(`temperature: ${temperature}`);
if ((typeof (temperature) != "number") || (temperature == null) || isNaN(temperature)) {
throw new EspThermError(`temperature element should be a number, message was "${message}"`);
}
let voltage = parseFloat(parts[2]);
if ((typeof (voltage) != "number") || (voltage == null) || isNaN(voltage)) {
throw new EspThermError(`voltage element should be a number, message was "${message}"`);
}
let timeConsumed = parseInt(parts[3]);
if ((typeof (timeConsumed) != "number") || (timeConsumed == null) || isNaN(timeConsumed)) {
throw new EspThermError(`timeConsumed element should be a number, message was "${message}"`);
}
let espThermMessage = new EspThermMessage(clientId, temperature, voltage, timeConsumed);
return espThermMessage;
}
exports.espThermToJson = espThermToJson;
//# sourceMappingURL=espthermtojson.js.map