/
main.ts
293 lines (256 loc) · 10.1 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
* Created with @iobroker/create-adapter v2.3.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
import * as utils from '@iobroker/adapter-core';
import {MeterDefinition, MeterInfoCollection, MeterState} from './lib/typedef';
import Calculator from './calculator';
import Round from './round';
// Load your modules here, e.g.:
// import * as fs from "fs";
class MeterStatistics extends utils.Adapter {
private unloaded = false;
private pendingPromises: Array<Promise<any>> = [];
public constructor(options: Partial<utils.AdapterOptions> = {}) {
super({
...options,
name: 'meter-statistics',
});
this.on('ready', this.onReady.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
private async onReady(): Promise<void> {
await this.assertObjectsExist();
const meterStates = await this.getMeterStates();
const calculator = new Calculator(this.config);
const meterInfos = calculator.calculateMeterInfos(meterStates);
this.writeMeterInfos(meterInfos);
this.end();
}
private writeMeterInfos(meterInfos: MeterInfoCollection): void {
for (const meterName in meterInfos) {
const meterInfo = meterInfos[meterName];
this.writeState(`meters.${meterName}.balance`, Round.costs(meterInfo.balance));
this.writeState(`meters.${meterName}.consumptionAverage`, Round.consumption(meterInfo.consumptionAverage));
this.writeState(`meters.${meterName}.consumptionPredictedTotal`, Round.consumption(meterInfo.consumptionPredictedTotal));
this.writeState(`meters.${meterName}.consumptionTotal`, Round.consumption(meterInfo.consumptionTotal));
this.writeState(`meters.${meterName}.costs`, Round.costs(meterInfo.costs));
this.writeState(`meters.${meterName}.paid`, Round.costs(meterInfo.paid));
this.writeState(`meters.${meterName}.recommendedPayment`, Round.costs(meterInfo.recommendedPayment));
}
}
private writeState(id: string, value: any): void {
const promise = this.setStateAsync(id, {val: value, ack: false});
this.pendingPromises.push(promise);
}
private getNumericStateValue(state: null|undefined|ioBroker.State, onErrorMessage: string): number {
const stateValue = state?.val;
if (typeof stateValue === 'number') {
return stateValue;
}
throw new Error(onErrorMessage);
}
private async getMeterStates(): Promise<MeterState[]> {
const meterStates = [];
for (const meter of this.config.meters) {
meterStates.push(await this.getMeterState(meter));
}
return meterStates;
}
private async getMeterState(meter: MeterDefinition): Promise<MeterState> {
const meterName = meter.alias;
const currentValueState = await this.getForeignStateAsync(meter.objectId);
const currentValue = this.getNumericStateValue(
currentValueState,
`Could not read meter "${meterName}" with id: ${meter.objectId}`
) || 0;
const startValueState = await this.getStateAsync(`configuration.${meterName}.startValue`);
let startValueDateTime: Date|null = null;
if (!startValueState) {
await this.setStateAsync(`configuration.${meterName}.startValue`, {val: currentValue, ack: true});
startValueDateTime = new Date(Round.precise(currentValueState?.ts || Date.now(), -3));
await this.setStateAsync(`configuration.${meterName}.readingDateTime`, {val: startValueDateTime.toISOString(), ack: true});
}
const startValue = this.getNumericStateValue(
startValueState || await this.getStateAsync(`configuration.${meterName}.startValue`),
`Could not read start value for meter "${meterName}".`
);
if (!startValueDateTime) {
const startValueDateTimeValue = (await this.getStateAsync(`configuration.${meterName}.readingDateTime`))?.val;
if (typeof startValueDateTimeValue === 'string') {
try {
startValueDateTime = new Date(Date.parse(startValueDateTimeValue));
} catch (e) {}
}
}
return {
meter,
currentValue,
startValue,
startValueDateTime,
consumption: currentValue - startValue,
};
}
private assertObjectsExist(): Promise<any> {
const promises = [];
for (const meter of this.config.meters) {
promises.push(...this.assertMeterObjectsExist(meter.alias));
}
promises.push(...this.assertMeterObjectsExist(this.config.summaryName, false));
return Promise.allSettled(promises);
}
private assertMeterObjectsExist(meterName: string, hasStartValue = true): ioBroker.SetObjectPromise[] {
const promises = [];
promises.push(this.setObjectNotExistsAsync(`configuration.${meterName}`, {
type: 'device',
common: {
name: `configuration.${meterName}`,
icon: `/icons/${hasStartValue ? 'device' : 'summary'}-icon.svg`,
},
native: {},
}));
if (hasStartValue) {
promises.push(this.setObjectNotExistsAsync(`configuration.${meterName}.startValue`, {
type: 'state',
common: {
name: 'Start value',
type: 'number',
role: 'state',
read: true,
write: true,
unit: this.config.meterUnit,
},
native: {
},
}));
promises.push(this.setObjectNotExistsAsync(`configuration.${meterName}.readingDateTime`, {
type: 'state',
common: {
name: 'Timestamp of reading start value',
desc: 'ONLY INFORMATION: Does not affect any calculation yet.',
type: 'string',
role: 'state',
read: true,
write: true,
},
native: {},
}));
}
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.consumptionAverage`, {
type: 'state',
common: {
name: 'Average consumption in period',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.meterUnit,
},
native: {},
}));
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.consumptionTotal`, {
type: 'state',
common: {
name: 'Total consumption in period',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.meterUnit,
},
native: {},
}));
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.consumptionPredictedTotal`, {
type: 'state',
common: {
name: 'Total predicted consumption in period',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.meterUnit,
},
native: {},
}));
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.costs`, {
type: 'state',
common: {
name: 'Total costs',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.paymentUnit,
},
native: {},
}));
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.paid`, {
type: 'state',
common: {
name: 'Total paid value',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.paymentUnit,
},
native: {},
}));
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.balance`, {
type: 'state',
common: {
name: 'Current balance',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.paymentUnit,
},
native: {},
}));
promises.push(this.setObjectNotExistsAsync(`meters.${meterName}.recommendedPayment`, {
type: 'state',
common: {
name: 'Recommended payment per payment interval',
type: 'number',
role: 'state',
read: true,
write: false,
unit: this.config.paymentUnit,
},
native: {},
}));
return promises;
}
end(): void {
if (this.unloaded) return;
Promise.allSettled(this.pendingPromises).finally(() => {
if (this.stop) {
this.stop();
}
});
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
*/
private onUnload(callback: () => void): void {
this.unloaded = true;
try {
// Here you must clear all timeouts or intervals that may still be active
callback();
} catch (e) {
callback();
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
module.exports = (options: Partial<utils.AdapterOptions> | undefined) => new MeterStatistics(options);
} else {
// otherwise start the instance directly
(() => new MeterStatistics())();
}