smartmeter2mqtt
Version:
Publish data from your Smartmeter with a P1 interface to your MQTT server.
248 lines • 12.5 kB
JavaScript
"use strict";
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var serialport_1 = __importDefault(require("serialport"));
var net_1 = require("net");
var events_1 = require("events");
var p1_parser_1 = __importDefault(require("./p1-parser"));
var p1_reader_events_1 = __importDefault(require("./p1-reader-events"));
var P1Reader = /** @class */ (function (_super) {
__extends(P1Reader, _super);
function P1Reader() {
var _this = _super.call(this) || this;
_this.dataBuffer = '';
_this.usage = 0;
_this.gasUsage = 0;
_this.gasReading = 0;
_this.gasReadingTimestamp = 0;
_this.reading = false;
_this.parsing = false;
return _this;
}
P1Reader.prototype.startWithSerialPort = function (path, baudRate) {
var _this = this;
if (baudRate === void 0) { baudRate = 115200; }
if (this.reading)
throw new Error('Already reading');
this.serialPort = new serialport_1.default(path, { baudRate: baudRate });
this.serialParser = new serialport_1.default.parsers.Readline({ delimiter: '\r\n' });
this.serialPort.pipe(this.serialParser);
this.serialParser.on('data', function (line) {
_this.emit(p1_reader_events_1.default.Line, line);
if (p1_parser_1.default.isStart(line))
_this.emit(p1_reader_events_1.default.Line, '');
});
this.reading = true;
};
P1Reader.prototype.startWithSocket = function (host, port) {
var _this = this;
this.socket = new net_1.Socket();
this.socket.connect(port, host);
this.socket.setEncoding('ascii');
this.socket.on('data', function (data) {
if (_this.bufferInterval) {
clearTimeout(_this.bufferInterval);
}
_this.dataBuffer += data.toString();
_this.bufferInterval = setTimeout(function () {
var lines = _this.dataBuffer.trim().split('\r\n');
lines.forEach(function (line) {
_this.emit(p1_reader_events_1.default.Line, line);
});
_this.dataBuffer = '';
}, 100);
});
this.socket.on('close', function () {
console.warn('Socket connection closed');
process.exit(10);
});
};
P1Reader.prototype.startParsing = function () {
var _this = this;
if (this.parsing)
return;
this.parser = new p1_parser_1.default();
this.on(p1_reader_events_1.default.Line, function (line) { _this.parseLine(line.trim()); });
this.parsing = true;
};
P1Reader.prototype.addSolarInput = function (input) {
this.solarInput = input;
};
P1Reader.prototype.parseLine = function (line) {
if (p1_parser_1.default.isStart(line)) {
this.parser = new p1_parser_1.default();
this.parser.addLine(line);
}
else if (this.parser && this.parser.addLine(line)) {
this.handleEnd();
}
};
P1Reader.prototype.handleEnd = function () {
var _a, _b, _c, _d, _e, _f;
return __awaiter(this, void 0, void 0, function () {
var originalMessage, result, solar, _g, _h, newUsage, relative, gas, currentGasReadingTimestamp, period, newGasReading, relative, newGasUsage;
return __generator(this, function (_j) {
switch (_j.label) {
case 0:
if (this.parser === undefined) {
throw new Error('Parser not running');
}
originalMessage = this.parser.message;
this.emit(p1_reader_events_1.default.Raw, originalMessage);
result = this.parser.data;
if (!result.crc) {
this.emit(p1_reader_events_1.default.ErrorMessage, 'CRC failed');
return [2 /*return*/];
}
if (!this.solarInput) return [3 /*break*/, 2];
return [4 /*yield*/, this.solarInput.getSolarData()];
case 1:
_g = _j.sent();
return [3 /*break*/, 3];
case 2:
_g = undefined;
_j.label = 3;
case 3:
solar = _g;
if (!solar) return [3 /*break*/, 5];
result.calculatedUsage = Math.round(((result.currentUsage || 0.0) - (result.currentDelivery || 0.0)) * 1000);
_h = result;
return [4 /*yield*/, ((_a = this.solarInput) === null || _a === void 0 ? void 0 : _a.getCurrentProduction())];
case 4:
_h.solarProduction = _j.sent();
result.houseUsage = Math.round(((_b = result.solarProduction) !== null && _b !== void 0 ? _b : 0) + result.calculatedUsage);
this.emit(p1_reader_events_1.default.SolarResult, solar);
return [3 /*break*/, 6];
case 5:
result.calculatedUsage = Math.round(((result.currentUsage || 0.0) - (result.currentDelivery || 0.0)) * 1000);
_j.label = 6;
case 6:
this.lastResult = result;
this.emit(p1_reader_events_1.default.ParsedResult, this.lastResult);
newUsage = ((_c = result.houseUsage) !== null && _c !== void 0 ? _c : result.calculatedUsage);
if (this.usage !== newUsage) {
relative = (newUsage - this.usage);
this.emit(p1_reader_events_1.default.UsageChanged, {
previousUsage: this.usage,
currentUsage: newUsage,
relative: relative,
message: "Usage " + (relative > 0 ? 'increased +' : 'decreased ') + relative + " to " + newUsage,
});
this.usage = newUsage;
}
gas = (_d = result.xGas) !== null && _d !== void 0 ? _d : result.gas;
if (gas) {
currentGasReadingTimestamp = (new Date((_e = gas.ts) !== null && _e !== void 0 ? _e : 0).getTime() / 1000);
period = currentGasReadingTimestamp - this.gasReadingTimestamp;
/**
* Report for every new timestamp
*/
if (period) {
newGasReading = ((_f = gas.totalUse) !== null && _f !== void 0 ? _f : 0);
relative = this.gasReading ? (newGasReading - this.gasReading) : 0;
newGasUsage = 0;
/**
* Gas usage in m3 per hour
*/
newGasUsage = relative * (3600 / period);
/**
* Gas usage is measured in thousands (0.001) - round the numbers
* accordingly
*/
this.emit(p1_reader_events_1.default.GasUsageChanged, {
previousUsage: parseFloat(this.gasUsage.toFixed(3)),
currentUsage: parseFloat(newGasUsage.toFixed(3)),
relative: parseFloat(relative.toFixed(3)),
message: "Reading increased +" + relative + " to " + newGasReading,
});
this.gasReadingTimestamp = currentGasReadingTimestamp;
this.gasReading = newGasReading;
this.gasUsage = newGasUsage;
}
}
return [2 /*return*/];
}
});
});
};
P1Reader.prototype.close = function () {
var _this = this;
if (this.solarInput) {
this.solarInput = undefined;
}
return new Promise(function (resolve, reject) {
_this.reading = false;
if (_this.serialPort) {
_this.serialPort.close(function (err) {
if (err)
reject(err);
else
resolve();
});
}
else if (_this.socket) {
_this.socket.destroy();
resolve();
}
else {
resolve();
}
}).then(function () {
console.log(' - Reader closed');
});
};
return P1Reader;
}(events_1.EventEmitter));
exports.default = P1Reader;
//# sourceMappingURL=p1-reader.js.map