iobroker.meter-statistics 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,120 @@
1
+ ![Logo](admin/meter-statistics.png)
2
+ # ioBroker.meter-statistics
3
+
4
+ [![NPM version](https://img.shields.io/npm/v/iobroker.meter-statistics.svg)](https://www.npmjs.com/package/iobroker.meter-statistics)
5
+ [![Downloads](https://img.shields.io/npm/dm/iobroker.meter-statistics.svg)](https://www.npmjs.com/package/iobroker.meter-statistics)
6
+ ![Number of Installations](https://iobroker.live/badges/meter-statistics-installed.svg)
7
+ ![Current version in stable repository](https://iobroker.live/badges/meter-statistics-stable.svg)
8
+
9
+ [![NPM](https://nodei.co/npm/iobroker.meter-statistics.png?downloads=true)](https://nodei.co/npm/iobroker.meter-statistics/)
10
+
11
+ **Tests:** ![Test and Release](https://github.com/jb-io/ioBroker.meter-statistics/workflows/Test%20and%20Release/badge.svg)
12
+
13
+ ## meter-statistics adapter for ioBroker
14
+
15
+ Calculate statistics from any smart meter
16
+
17
+ ## Developer manual
18
+ This section is intended for the developer. It can be deleted later
19
+
20
+ ### Getting started
21
+
22
+ You are almost done, only a few steps left:
23
+ 1. Create a new repository on GitHub with the name `ioBroker.meter-statistics`
24
+ 1. Initialize the current folder as a new git repository:
25
+ ```bash
26
+ git init -b master
27
+ git add .
28
+ git commit -m "Initial commit"
29
+ ```
30
+ 1. Link your local repository with the one on GitHub:
31
+ ```bash
32
+ git remote add origin https://github.com/jb-io/ioBroker.meter-statistics
33
+ ```
34
+
35
+ 1. Push all files to the GitHub repo:
36
+ ```bash
37
+ git push origin master
38
+ ```
39
+ 1. Add a new secret under https://github.com/jb-io/ioBroker.meter-statistics/settings/secrets. It must be named `AUTO_MERGE_TOKEN` and contain a personal access token with push access to the repository, e.g. yours. You can create a new token under https://github.com/settings/tokens.
40
+
41
+ 1. Head over to [src/main.ts](src/main.ts) and start programming!
42
+
43
+ ### Best Practices
44
+ We've collected some [best practices](https://github.com/ioBroker/ioBroker.repositories#development-and-coding-best-practices) regarding ioBroker development and coding in general. If you're new to ioBroker or Node.js, you should
45
+ check them out. If you're already experienced, you should also take a look at them - you might learn something new :)
46
+
47
+ ### Scripts in `package.json`
48
+ Several npm scripts are predefined for your convenience. You can run them using `npm run <scriptname>`
49
+ | Script name | Description |
50
+ |-------------|-------------|
51
+ | `build` | Compile the TypeScript sources. |
52
+ | `watch` | Compile the TypeScript sources and watch for changes. |
53
+ | `test:ts` | Executes the tests you defined in `*.test.ts` files. |
54
+ | `test:package` | Ensures your `package.json` and `io-package.json` are valid. |
55
+ | `test:integration` | Tests the adapter startup with an actual instance of ioBroker. |
56
+ | `test` | Performs a minimal test run on package files and your tests. |
57
+ | `check` | Performs a type-check on your code (without compiling anything). |
58
+ | `lint` | Runs `ESLint` to check your code for formatting errors and potential bugs. |
59
+ | `translate` | Translates texts in your adapter to all required languages, see [`@iobroker/adapter-dev`](https://github.com/ioBroker/adapter-dev#manage-translations) for more details. |
60
+ | `release` | Creates a new release, see [`@alcalzone/release-script`](https://github.com/AlCalzone/release-script#usage) for more details. |
61
+
62
+ ### Configuring the compilation
63
+ The adapter template uses [esbuild](https://esbuild.github.io/) to compile TypeScript and/or React code. You can configure many compilation settings
64
+ either in `tsconfig.json` or by changing options for the build tasks. These options are described in detail in the
65
+ [`@iobroker/adapter-dev` documentation](https://github.com/ioBroker/adapter-dev#compile-adapter-files).
66
+
67
+ ### Writing tests
68
+ When done right, testing code is invaluable, because it gives you the
69
+ confidence to change your code while knowing exactly if and when
70
+ something breaks. A good read on the topic of test-driven development
71
+ is https://hackernoon.com/introduction-to-test-driven-development-tdd-61a13bc92d92.
72
+ Although writing tests before the code might seem strange at first, but it has very
73
+ clear upsides.
74
+
75
+ The template provides you with basic tests for the adapter startup and package files.
76
+ It is recommended that you add your own tests into the mix.
77
+
78
+ ### Publishing the adapter
79
+ Using GitHub Actions, you can enable automatic releases on npm whenever you push a new git tag that matches the form
80
+ `v<major>.<minor>.<patch>`. We **strongly recommend** that you do. The necessary steps are described in `.github/workflows/test-and-release.yml`.
81
+
82
+ Since you installed the release script, you can create a new
83
+ release simply by calling:
84
+ ```bash
85
+ npm run release
86
+ ```
87
+ Additional command line options for the release script are explained in the
88
+ [release-script documentation](https://github.com/AlCalzone/release-script#command-line).
89
+
90
+ To get your adapter released in ioBroker, please refer to the documentation
91
+ of [ioBroker.repositories](https://github.com/ioBroker/ioBroker.repositories#requirements-for-adapter-to-get-added-to-the-latest-repository).
92
+
93
+ ### Test the adapter manually with dev-server
94
+ Since you set up `dev-server`, you can use it to run, test and debug your adapter.
95
+
96
+ You may start `dev-server` by calling from your dev directory:
97
+ ```bash
98
+ dev-server watch
99
+ ```
100
+
101
+ The ioBroker.admin interface will then be available at http://localhost:8081/
102
+
103
+ Please refer to the [`dev-server` documentation](https://github.com/ioBroker/dev-server#command-line) for more details.
104
+
105
+ ## Changelog
106
+ <!--
107
+ Placeholder for the next version (at the beginning of the line):
108
+ ### **WORK IN PROGRESS**
109
+ -->
110
+
111
+ ### **WORK IN PROGRESS**
112
+
113
+
114
+ ### 0.0.1 (2023-03-01)
115
+ * (jb-io) initial release
116
+
117
+ ## Licence
118
+ [Licensed under GPLv3 or later](LICENSE)
119
+
120
+ Copyright (c) 2023 jb-io <96919536+jb-io@users.noreply.github.com>
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Adaptereinstellungen für meter-statistics",
3
+ "option1": "Option 1",
4
+ "option2": "Option 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Adapter settings for meter-statistics",
3
+ "option1": "option1",
4
+ "option2": "option2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Ajustes del adaptador para meter-statistics",
3
+ "option1": "Opción 1",
4
+ "option2": "opcion 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Paramètres d'adaptateur pour meter-statistics",
3
+ "option1": "Option 1",
4
+ "option2": "Option 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Impostazioni dell'adattatore per meter-statistics",
3
+ "option1": "opzione 1",
4
+ "option2": "opzione 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Adapterinstellingen voor meter-statistics",
3
+ "option1": "Optie 1",
4
+ "option2": "Optie 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Ustawienia adaptera dla meter-statistics",
3
+ "option1": "opcja 1",
4
+ "option2": "Opcja 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Configurações do adaptador para meter-statistics",
3
+ "option1": "Opção 1",
4
+ "option2": "opção 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Настройки адаптера для meter-statistics",
3
+ "option1": "Опция 1",
4
+ "option2": "вариант 2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "Налаштування адаптера для вимірювальної статистики",
3
+ "option1": "варіант1",
4
+ "option2": "варіант2"
5
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "meter-statistics adapter settings": "meter-statistics的适配器设置",
3
+ "option1": "选项1",
4
+ "option2": "选项2"
5
+ }
@@ -0,0 +1,94 @@
1
+ {
2
+ "i18n": true,
3
+ "type": "panel",
4
+ "items": {
5
+ "headerUnits": {
6
+ "type": "header",
7
+ "text": "Units",
8
+ "size": 2
9
+ },
10
+ "units": {
11
+ "type": "panel",
12
+ "label": "units",
13
+ "items": {
14
+ "meterUnit": {
15
+ "type": "text",
16
+ "label": "Unit of meter value"
17
+ },
18
+ "paymentUnit": {
19
+ "type": "text",
20
+ "label": "Unit of payment"
21
+ }
22
+ }
23
+ },
24
+ "headerPayment": {
25
+ "type": "header",
26
+ "text": "Payment",
27
+ "size": 2
28
+ },
29
+ "payment": {
30
+ "type": "panel",
31
+ "label": "payment",
32
+ "items": {
33
+ "paymentValue": {
34
+ "type": "number",
35
+ "label": "Payment value",
36
+ "newLine": true
37
+ },
38
+ "paymentCount": {
39
+ "type": "number",
40
+ "label": "Payment count",
41
+ "min": 1,
42
+ "newLine": true
43
+ },
44
+ "paymentCorrectionOffset": {
45
+ "type": "number",
46
+ "label": "Payment correction offset",
47
+ "newLine": true
48
+ }
49
+ }
50
+ },
51
+ "headerMeters": {
52
+ "type": "header",
53
+ "text": "Meters",
54
+ "size": 2
55
+ },
56
+ "meters": {
57
+ "type": "table",
58
+ "items": [
59
+ {
60
+ "attr": "objectId",
61
+ "width": "40%",
62
+ "title": "Object ID",
63
+ "type": "objectId",
64
+ "validator": "!!data.objectId",
65
+ "validatorNoSaveOnError": true
66
+ },
67
+ {
68
+ "attr": "alias",
69
+ "width": "30%",
70
+ "title": "Meter alias",
71
+ "type": "text" ,
72
+ "validator": "!!data.alias",
73
+ "validatorNoSaveOnError": true
74
+ },
75
+ {
76
+ "attr": "pricePerUnit",
77
+ "width": "15%",
78
+ "title": "Price per unit",
79
+ "type": "number",
80
+ "validator": "!!data.pricePerUnit",
81
+ "validatorNoSaveOnError": true
82
+ },
83
+ {
84
+ "attr": "basePrice",
85
+ "width": "15%",
86
+ "title": "Base price",
87
+ "type": "number",
88
+ "validator": "!!data.basePrice",
89
+ "validatorNoSaveOnError": true
90
+ }
91
+ ]
92
+ }
93
+ }
94
+ }
Binary file
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var accounting_helper_exports = {};
20
+ __export(accounting_helper_exports, {
21
+ default: () => AccountingHelper
22
+ });
23
+ module.exports = __toCommonJS(accounting_helper_exports);
24
+ class AccountingHelper {
25
+ }
26
+ // Annotate the CommonJS export names for ESM import in node:
27
+ 0 && (module.exports = {});
28
+ //# sourceMappingURL=accounting-helper.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/accounting-helper.ts"],
4
+ "sourcesContent": ["export default class AccountingHelper {\n\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAAO,iBAA+B;AAEtC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var typedef_exports = {};
16
+ module.exports = __toCommonJS(typedef_exports);
17
+ //# sourceMappingURL=typedef.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/typedef.ts"],
4
+ "sourcesContent": ["export interface MeterState {\n meter: MeterDefinition;\n startValue: number;\n currentValue: number;\n consumption: number;\n}\n\nexport interface MeterDefinition {\n objectId: string;\n alias: string;\n pricePerUnit: number;\n basePrice: number;\n}\n\nexport interface MeterConsumption {\n total: number;\n average: number;\n}\n\nexport interface DayInfo {\n firstDayOfYear: Date;\n daysInYear: number;\n daysSinceStartOfYear: number;\n}"],
5
+ "mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
6
+ "names": []
7
+ }
package/build/main.js ADDED
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
18
+ mod
19
+ ));
20
+ var utils = __toESM(require("@iobroker/adapter-core"));
21
+ class MeterStatistics extends utils.Adapter {
22
+ constructor(options = {}) {
23
+ super({
24
+ ...options,
25
+ name: "meter-statistics"
26
+ });
27
+ this.unloaded = false;
28
+ this.pendingPromises = [];
29
+ this.on("ready", this.onReady.bind(this));
30
+ this.on("unload", this.onUnload.bind(this));
31
+ }
32
+ async onReady() {
33
+ await this.assertObjectsExist();
34
+ const dayInfo = this.getDayInfo();
35
+ const meterStates = await this.getMeterStates();
36
+ const { total, average } = this.calculateMeterConsumption(meterStates, dayInfo);
37
+ this.writeState("calculated.consumption.total", this.roundConsumption(total));
38
+ this.writeState("calculated.consumption.average", this.roundConsumption(average));
39
+ const costs = this.calculateCosts(meterStates);
40
+ this.writeState("calculated.costs.used", this.roundCosts(costs));
41
+ const paid = this.calculatePaid(dayInfo);
42
+ this.writeState("calculated.costs.paid", this.roundCosts(paid));
43
+ const current = paid - costs;
44
+ this.writeState("calculated.costs.current", this.roundCosts(current));
45
+ const recommendedPayment = this.calculateRecommendation(costs, dayInfo);
46
+ this.writeState("calculated.costs.recommendedPayment", this.roundCosts(recommendedPayment));
47
+ this.end();
48
+ }
49
+ addPendingPromise(promise) {
50
+ this.pendingPromises.push(promise);
51
+ }
52
+ calculateMeterConsumption(meterStates, dayInfo) {
53
+ let totalConsumption = 0;
54
+ for (const meterState of meterStates) {
55
+ totalConsumption += meterState.consumption;
56
+ }
57
+ return {
58
+ total: totalConsumption,
59
+ average: totalConsumption / dayInfo.daysSinceStartOfYear
60
+ };
61
+ }
62
+ calculateCosts(meterStates) {
63
+ let usedCosts = 0;
64
+ for (const meterState of meterStates) {
65
+ usedCosts += meterState.consumption * meterState.meter.price;
66
+ }
67
+ return usedCosts;
68
+ }
69
+ calculatePaid(dayInfo) {
70
+ let paid = this.config.paymentCorrectionOffset;
71
+ paid += this.config.paymentValue * this.config.paymentCount / dayInfo.daysInYear * dayInfo.daysSinceStartOfYear;
72
+ return paid;
73
+ }
74
+ calculateRecommendation(costs, dayInfo) {
75
+ const suggestedPayment = this.roundCosts(costs / dayInfo.daysSinceStartOfYear * dayInfo.daysInYear / this.config.paymentCount);
76
+ return suggestedPayment;
77
+ }
78
+ roundCosts(costs) {
79
+ return Math.round(costs * 100) / 100;
80
+ }
81
+ roundConsumption(consumption) {
82
+ return Math.round(consumption * 1e3) / 1e3;
83
+ }
84
+ getDaysInYear() {
85
+ return 365;
86
+ }
87
+ getDaysSince(start) {
88
+ const now = new Date();
89
+ const diff = now.valueOf() - start.valueOf();
90
+ const oneDay = 1e3 * 60 * 60 * 24;
91
+ return Math.floor(diff / oneDay);
92
+ }
93
+ writeState(id, value) {
94
+ this.addPendingPromise(this.setStateAsync(id, { val: value, ack: true }));
95
+ }
96
+ async getMeterStates() {
97
+ const meterStates = [];
98
+ for (const meter of this.config.meters) {
99
+ meterStates.push(await this.getMeterState(meter));
100
+ }
101
+ return meterStates;
102
+ }
103
+ async getMeterState(meter) {
104
+ const currentValueState = await this.getForeignStateAsync(meter.objectId);
105
+ const currentValue = currentValueState == null ? void 0 : currentValueState.val;
106
+ if (!currentValueState || typeof currentValue !== "number") {
107
+ throw new Error(`Could not read meter "${meter.alias}" with id: ${meter.objectId}`);
108
+ }
109
+ const startValueState = await this.getStateAsync(`meter.${meter.alias}.startValue`);
110
+ const startValue = startValueState == null ? void 0 : startValueState.val;
111
+ if (!currentValueState || typeof startValue !== "number") {
112
+ throw new Error(`Could not read start value for meter "${meter.alias}".`);
113
+ }
114
+ return {
115
+ meter,
116
+ currentValue,
117
+ startValue,
118
+ consumption: currentValue - startValue
119
+ };
120
+ }
121
+ getDayInfo() {
122
+ const firstDayOfYear = new Date(new Date().getFullYear(), 0, 0);
123
+ const daysInYear = this.getDaysInYear();
124
+ const daysSinceStartOfYear = this.getDaysSince(firstDayOfYear);
125
+ return { firstDayOfYear, daysInYear, daysSinceStartOfYear };
126
+ }
127
+ async assertObjectsExist() {
128
+ for (const meter of this.config.meters) {
129
+ await this.setObjectNotExistsAsync(`meter.${meter.alias}.startValue`, {
130
+ type: "state",
131
+ common: {
132
+ name: "Start value",
133
+ type: "number",
134
+ role: "state",
135
+ read: true,
136
+ write: true,
137
+ unit: this.config.meterUnit
138
+ },
139
+ native: {}
140
+ });
141
+ }
142
+ await this.setObjectNotExistsAsync(`calculated.consumption.total`, {
143
+ type: "state",
144
+ common: {
145
+ name: "Total consumption in period",
146
+ type: "number",
147
+ role: "state",
148
+ read: true,
149
+ write: false,
150
+ unit: this.config.meterUnit
151
+ },
152
+ native: {}
153
+ });
154
+ await this.setObjectNotExistsAsync(`calculated.consumption.average`, {
155
+ type: "state",
156
+ common: {
157
+ name: "Average consumption in period",
158
+ type: "number",
159
+ role: "state",
160
+ read: true,
161
+ write: false,
162
+ unit: this.config.meterUnit
163
+ },
164
+ native: {}
165
+ });
166
+ await this.setObjectNotExistsAsync(`calculated.costs.paid`, {
167
+ type: "state",
168
+ common: {
169
+ name: "Total paid value",
170
+ type: "number",
171
+ role: "state",
172
+ read: true,
173
+ write: false,
174
+ unit: this.config.paymentUnit
175
+ },
176
+ native: {}
177
+ });
178
+ await this.setObjectNotExistsAsync(`calculated.costs.used`, {
179
+ type: "state",
180
+ common: {
181
+ name: "Total costs",
182
+ type: "number",
183
+ role: "state",
184
+ read: true,
185
+ write: false,
186
+ unit: this.config.paymentUnit
187
+ },
188
+ native: {}
189
+ });
190
+ await this.setObjectNotExistsAsync(`calculated.costs.current`, {
191
+ type: "state",
192
+ common: {
193
+ name: "Current payment value",
194
+ type: "number",
195
+ role: "state",
196
+ read: true,
197
+ write: false,
198
+ unit: this.config.paymentUnit
199
+ },
200
+ native: {}
201
+ });
202
+ await this.setObjectNotExistsAsync(`calculated.costs.recommendedPayment`, {
203
+ type: "state",
204
+ common: {
205
+ name: "Recommended payment per payment interval",
206
+ type: "number",
207
+ role: "state",
208
+ read: true,
209
+ write: false,
210
+ unit: this.config.paymentUnit
211
+ },
212
+ native: {}
213
+ });
214
+ }
215
+ end() {
216
+ if (this.unloaded)
217
+ return;
218
+ Promise.allSettled(this.pendingPromises).finally(() => {
219
+ if (this.stop) {
220
+ this.stop();
221
+ }
222
+ });
223
+ }
224
+ onUnload(callback) {
225
+ this.unloaded = true;
226
+ try {
227
+ callback();
228
+ } catch (e) {
229
+ callback();
230
+ }
231
+ }
232
+ }
233
+ if (require.main !== module) {
234
+ module.exports = (options) => new MeterStatistics(options);
235
+ } else {
236
+ (() => new MeterStatistics())();
237
+ }
238
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/main.ts"],
4
+ "sourcesContent": ["/*\n * Created with @iobroker/create-adapter v2.2.0\n */\n\n// The adapter-core module gives you access to the core ioBroker functions\n// you need to create an adapter\nimport * as utils from '@iobroker/adapter-core';\nimport {MeterState, MeterDefinition, MeterConsumption, DayInfo} from './lib/typedef';\n\n// Load your modules here, e.g.:\n// import * as fs from \"fs\";\n\nclass MeterStatistics extends utils.Adapter {\n\n private unloaded = false;\n\n private pendingPromises: Array<Promise<any>> = [];\n\n public constructor(options: Partial<utils.AdapterOptions> = {}) {\n super({\n ...options,\n name: 'meter-statistics',\n });\n this.on('ready', this.onReady.bind(this));\n this.on('unload', this.onUnload.bind(this));\n }\n\n /**\n * Is called when databases are connected and adapter received configuration.\n */\n private async onReady(): Promise<void> {\n\n await this.assertObjectsExist();\n\n const dayInfo = this.getDayInfo();\n const meterStates = await this.getMeterStates();\n\n const {total, average} = this.calculateMeterConsumption(meterStates, dayInfo);\n this.writeState('calculated.consumption.total', this.roundConsumption(total));\n this.writeState('calculated.consumption.average', this.roundConsumption(average));\n\n const costs = this.calculateCosts(meterStates);\n this.writeState('calculated.costs.used', this.roundCosts(costs));\n\n const paid = this.calculatePaid(dayInfo);\n this.writeState('calculated.costs.paid', this.roundCosts(paid));\n\n const current = paid - costs;\n this.writeState('calculated.costs.current', this.roundCosts(current));\n\n const recommendedPayment = this.calculateRecommendation(costs, dayInfo);\n this.writeState('calculated.costs.recommendedPayment', this.roundCosts(recommendedPayment));\n\n this.end();\n }\n\n private addPendingPromise(promise: Promise<any>): void {\n this.pendingPromises.push(promise);\n }\n\n private calculateMeterConsumption(meterStates: MeterState[], dayInfo: DayInfo): MeterConsumption {\n\n let totalConsumption = 0;\n\n for (const meterState of meterStates) {\n totalConsumption += meterState.consumption;\n }\n\n return {\n total: totalConsumption,\n average: totalConsumption / dayInfo.daysSinceStartOfYear,\n };\n }\n\n private calculateCosts(meterStates: MeterState[]): number {\n\n let usedCosts = 0;\n\n for (const meterState of meterStates) {\n usedCosts += meterState.consumption * meterState.meter.price;\n }\n\n return usedCosts;\n }\n\n private calculatePaid(dayInfo: DayInfo): number {\n\n let paid = this.config.paymentCorrectionOffset;\n\n paid += (this.config.paymentValue * this.config.paymentCount / dayInfo.daysInYear) * dayInfo.daysSinceStartOfYear;\n\n return paid;\n }\n\n private calculateRecommendation(costs: number, dayInfo: DayInfo): number {\n const suggestedPayment = this.roundCosts(costs / dayInfo.daysSinceStartOfYear * dayInfo.daysInYear / this.config.paymentCount);\n\n return suggestedPayment;\n }\n\n public roundCosts(costs: number): number {\n return Math.round(costs * 100) / 100;\n }\n\n public roundConsumption(consumption: number): number {\n return Math.round(consumption * 1000) / 1000;\n }\n\n public getDaysInYear(): number {\n return 365;\n }\n\n public getDaysSince(start: Date): number {\n const now = new Date();\n const diff = now.valueOf() - start.valueOf();\n const oneDay = 1000 * 60 * 60 * 24;\n return Math.floor(diff / oneDay);\n }\n\n private writeState(id: string, value: any): void {\n this.addPendingPromise(this.setStateAsync(id, {val: value, ack: true}));\n }\n\n private async getMeterStates(): Promise<MeterState[]> {\n\n const meterStates = [];\n\n for (const meter of this.config.meters) {\n meterStates.push(await this.getMeterState(meter));\n }\n\n return meterStates;\n }\n\n private async getMeterState(meter: MeterDefinition): Promise<MeterState> {\n\n const currentValueState = await this.getForeignStateAsync(meter.objectId);\n const currentValue = currentValueState?.val;\n if (!currentValueState || typeof currentValue !== 'number') {\n throw new Error(`Could not read meter \"${meter.alias}\" with id: ${meter.objectId}`);\n }\n\n const startValueState = await this.getStateAsync(`meter.${meter.alias}.startValue`);\n const startValue = startValueState?.val;\n if (!currentValueState || typeof startValue !== 'number') {\n throw new Error(`Could not read start value for meter \"${meter.alias}\".`);\n }\n\n return {\n meter,\n currentValue,\n startValue,\n consumption: currentValue - startValue,\n };\n }\n\n private getDayInfo(): DayInfo {\n\n const firstDayOfYear = new Date((new Date()).getFullYear(), 0, 0);\n const daysInYear = this.getDaysInYear();\n const daysSinceStartOfYear = this.getDaysSince(firstDayOfYear);\n\n return {firstDayOfYear, daysInYear, daysSinceStartOfYear};\n }\n\n private async assertObjectsExist(): Promise<void> {\n\n for (const meter of this.config.meters) {\n\n await this.setObjectNotExistsAsync(`meter.${meter.alias}.startValue`, {\n type: 'state',\n common: {\n name: 'Start value',\n type: 'number',\n role: 'state',\n read: true,\n write: true,\n unit: this.config.meterUnit,\n },\n native: {},\n });\n\n }\n\n await this.setObjectNotExistsAsync(`calculated.consumption.total`, {\n type: 'state',\n common: {\n name: 'Total consumption in period',\n type: 'number',\n role: 'state',\n read: true,\n write: false,\n unit: this.config.meterUnit,\n },\n native: {},\n });\n\n await this.setObjectNotExistsAsync(`calculated.consumption.average`, {\n type: 'state',\n common: {\n name: 'Average consumption in period',\n type: 'number',\n role: 'state',\n read: true,\n write: false,\n unit: this.config.meterUnit,\n },\n native: {},\n });\n\n await this.setObjectNotExistsAsync(`calculated.costs.paid`, {\n type: 'state',\n common: {\n name: 'Total paid value',\n type: 'number',\n role: 'state',\n read: true,\n write: false,\n unit: this.config.paymentUnit,\n },\n native: {},\n });\n\n await this.setObjectNotExistsAsync(`calculated.costs.used`, {\n type: 'state',\n common: {\n name: 'Total costs',\n type: 'number',\n role: 'state',\n read: true,\n write: false,\n unit: this.config.paymentUnit,\n },\n native: {},\n });\n\n await this.setObjectNotExistsAsync(`calculated.costs.current`, {\n type: 'state',\n common: {\n name: 'Current payment value',\n type: 'number',\n role: 'state',\n read: true,\n write: false,\n unit: this.config.paymentUnit,\n },\n native: {},\n });\n\n await this.setObjectNotExistsAsync(`calculated.costs.recommendedPayment`, {\n type: 'state',\n common: {\n name: 'Recommended payment per payment interval',\n type: 'number',\n role: 'state',\n read: true,\n write: false,\n unit: this.config.paymentUnit,\n },\n native: {},\n });\n }\n\n end(): void {\n if (this.unloaded) return;\n Promise.allSettled(this.pendingPromises).finally(() => {\n if (this.stop) {\n this.stop();\n }\n });\n }\n\n /**\n * Is called when adapter shuts down - callback has to be called under any circumstances!\n */\n private onUnload(callback: () => void): void {\n this.unloaded = true;\n try {\n // Here you must clear all timeouts or intervals that may still be active\n callback();\n } catch (e) {\n callback();\n }\n }\n\n}\n\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial<utils.AdapterOptions> | undefined) => new MeterStatistics(options);\n} else {\n // otherwise start the instance directly\n (() => new MeterStatistics())();\n}"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAMA,YAAuB;AAMvB,MAAM,wBAAwB,MAAM,QAAQ;AAAA,EAMjC,YAAY,UAAyC,CAAC,GAAG;AAC5D,UAAM;AAAA,MACF,GAAG;AAAA,MACH,MAAM;AAAA,IACV,CAAC;AARL,SAAQ,WAAW;AAEnB,SAAQ,kBAAuC,CAAC;AAO5C,SAAK,GAAG,SAAS,KAAK,QAAQ,KAAK,IAAI,CAAC;AACxC,SAAK,GAAG,UAAU,KAAK,SAAS,KAAK,IAAI,CAAC;AAAA,EAC9C;AAAA,EAKA,MAAc,UAAyB;AAEnC,UAAM,KAAK,mBAAmB;AAE9B,UAAM,UAAU,KAAK,WAAW;AAChC,UAAM,cAAc,MAAM,KAAK,eAAe;AAE9C,UAAM,EAAC,OAAO,QAAO,IAAI,KAAK,0BAA0B,aAAa,OAAO;AAC5E,SAAK,WAAW,gCAAgC,KAAK,iBAAiB,KAAK,CAAC;AAC5E,SAAK,WAAW,kCAAkC,KAAK,iBAAiB,OAAO,CAAC;AAEhF,UAAM,QAAQ,KAAK,eAAe,WAAW;AAC7C,SAAK,WAAW,yBAAyB,KAAK,WAAW,KAAK,CAAC;AAE/D,UAAM,OAAO,KAAK,cAAc,OAAO;AACvC,SAAK,WAAW,yBAAyB,KAAK,WAAW,IAAI,CAAC;AAE9D,UAAM,UAAU,OAAO;AACvB,SAAK,WAAW,4BAA4B,KAAK,WAAW,OAAO,CAAC;AAEpE,UAAM,qBAAqB,KAAK,wBAAwB,OAAO,OAAO;AACtE,SA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