smartmeter2mqtt
Version:
Publish data from your Smartmeter with a P1 interface to your MQTT server.
86 lines • 3.26 kB
JavaScript
;
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var node_fetch_1 = __importDefault(require("node-fetch"));
var url_1 = require("url");
var interval_output_1 = __importDefault(require("./interval-output"));
var p1_reader_events_1 = __importDefault(require("../p1-reader-events"));
var HttpOutput = /** @class */ (function (_super) {
__extends(HttpOutput, _super);
function HttpOutput(config) {
var _this = _super.call(this, config.interval) || this;
_this.config = config;
return _this;
}
HttpOutput.prototype.start = function (p1Reader) {
var _this = this;
_super.prototype.start.call(this, p1Reader);
this.fields = this.config.fields.split(',');
this.on(p1_reader_events_1.default.ParsedResult, function (data) { return _this.sendEvent(data)
.then(function (result) {
if (!result.ok) {
throw new Error(result.statusText);
}
})
.catch(function (err) {
_this.emit(p1_reader_events_1.default.ErrorMessage, err);
}); });
};
HttpOutput.prototype.sendEvent = function (data) {
var flatData = this.fields
? this.filterData(HttpOutput.flatten(data))
: HttpOutput.flatten(data);
if (this.config.json) {
return node_fetch_1.default(this.config.url, {
method: 'post',
body: JSON.stringify(flatData),
headers: { 'Content-Type': 'application/json' },
});
}
return node_fetch_1.default(this.config.url, {
method: 'post',
body: new url_1.URLSearchParams(flatData),
});
};
HttpOutput.prototype.filterData = function (data) {
if (this.fields === undefined) {
return data;
}
var result = {};
var fields = this.fields;
Object.keys(data)
.filter(function (key) { return fields.includes(key); })
.forEach(function (key) {
result[key] = data[key];
});
return result;
};
HttpOutput.flatten = function (data) {
if (data.gas) {
var result = data;
result.gas_ts = data.gas.ts;
result.gas_totalUse = data.gas.totalUse;
delete result.gas;
return result;
}
return data;
};
return HttpOutput;
}(interval_output_1.default));
exports.default = HttpOutput;
//# sourceMappingURL=http-output.js.map