forked from iobroker-community-adapters/ioBroker.opendtu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
276 lines (240 loc) · 9 KB
/
main.js
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
'use strict';
const utils = require('@iobroker/adapter-core');
const { default: axios } = require('axios');
// @ts-ignore
const schedule = require('node-schedule');
// @ts-ignore
const WebsocketController = require('./lib/websocketController').WebsocketController;
const DataController = require('./lib/dataController').DataController;
let dtuApiURL;
let dtuNetworkApiURL;
let limitApiURL;
let powerApiURL;
let websocketController;
let dataController;
class Opendtu extends utils.Adapter {
constructor(options) {
super({
...options,
name: 'opendtu',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
}
async onReady() {
// Check if webUIServer is configured, log warning message and return if not
if (!this.config.webUIServer) {
this.log.warn('Please configure the Websoket connection!');
return;
}
// Construct the base URL for API calls using configuration variables
const baseURL = `${this.config.webUIScheme}://${this.config.webUIServer}:${this.config.webUIPort}/api`;
// Construct URLs for various API endpoints using the base URL
dtuApiURL = `${baseURL}/system/status`;
dtuNetworkApiURL = `${baseURL}/network/status`;
limitApiURL = `${baseURL}/limit/config`;
powerApiURL = `${baseURL}/power/config`;
// Set default authentication credentials for Axios requests
axios.defaults.auth = { username: this.config.userName, password: this.config.password };
// Instantiate a new DataController object with necessary arguments
dataController = new DataController(this);
// Start the websocket connection and initiate data retrieval from DTU
this.startWebsocket();
this.getDTUData();
// Schedule jobs to run at specified intervals using Cron-style syntax
schedule.scheduleJob('rewriteYildTotal', '0 1 0 * * *', () => this.rewriteYildTotal());
schedule.scheduleJob('getDTUData', '*/10 * * * * *', () => this.getDTUData());
}
// This function gets called whenever there's a state change in the system.
async onStateChange(id, state) {
// Check that the new state is not an acknowledgement of a previous command.
if (state && state.ack == false) {
// Split the ID into parts to get the serial number and state identifier.
const idParts = id.split('.');
const serial = idParts[2];
const stateID = idParts[4];
// Use a switch statement to handle different types of state changes.
switch (stateID) {
case 'limit_persistent_relative':
// Set the inverter limit based on the new value and a fixed parameter.
this.setInverterLimit(serial, state.val, 257);
break;
case 'limit_persistent_absolute':
this.setInverterLimit(serial, state.val, 256);
break;
case 'limit_nonpersistent_relative':
this.setInverterLimit(serial, state.val, 1);
break;
case 'limit_nonpersistent_absolute':
this.setInverterLimit(serial, state.val, 0);
break;
case 'power_on':
// Switch the inverter power status based on the new value.
if (state.val == true) {
this.setInverterPower(serial, true);
}
break;
case 'power_off':
// Switch the inverter power status based on the new value.
if (state.val == true) {
this.setInverterPower(serial, false);
}
break;
case 'restart':
// Restart the inverter based on the new value.
if (state.val == true) {
this.setInverterRestart(serial, true);
}
break;
default:
// If the state change isn't recognized, do nothing.
return;
}
// Update the state with the new values and acknowledge the change.
this.setStateAsync(id, state, true);
}
}
async onUnload(callback) {
try {
this.allAvailableToFalse();
} catch (e) {
this.log.error(e);
}
// Websocket
try {
if (websocketController) {
websocketController.closeConnection();
}
} catch (e) {
this.log.error(e);
}
// Clear all websocket timers
try {
if (websocketController) {
await websocketController.allTimerClear();
}
} catch (e) {
this.log.error(e);
}
try {
schedule.cancelJob('dayEndJob');
} catch (e) {
this.log.error(e);
}
try {
schedule.cancelJob('rewriteYildTotal');
} catch (e) {
this.log.error(e);
}
try {
schedule.cancelJob('getDTUData');
} catch (e) {
this.log.error(e);
}
callback();
}
startWebsocket() {
websocketController = new WebsocketController(this);
const wsClient = websocketController.initWsClient();
wsClient.on('open', () => {
this.log.info('Connect to OpenDTU over websocket connection.');
});
wsClient.on('message', (message) => {
this.processMessage(message);
});
wsClient.on('close', async () => {
this.allAvailableToFalse();
});
}
// @ts-ignore
async processMessage(message, isObject) {
try {
if (!isObject) {
message = JSON.parse(message);
}
}
catch (err) {
this.log.error(err);
this.log.debug(message);
}
// Create inverter rootfolder
if (message.inverters) {
dataController.processInverterData(message.inverters);
}
// Total
if (message.total) {
dataController.processTotalData(message.total);
}
// DTU
if (message.dtu) {
dataController.processDTUData(message.dtu);
}
}
async getDTUData() {
try {
const res = await axios.all([axios.get(dtuNetworkApiURL), axios.get(dtuApiURL)]);
const dtuData = res[0].data;
dtuData.uptime = res[1].data.uptime;
dtuData.reachable = true;
this.processMessage({ dtu: dtuData }, true);
} catch (err) {
this.log.debug(`getDTUData axios error: ${err}`);
this.processMessage({ dtu: { reachable: false } }, true);
}
}
async setInverterLimit(serial, limit_value, limit_type) {
try {
const payload = `data=${JSON.stringify({ serial, limit_type, limit_value })}`;
await axios.post(limitApiURL, payload);
} catch (err) {
this.log.warn(`setInverterLimit axios error: ${err}`);
}
}
async setInverterPower(serial, power) {
try {
const payload = `data=${JSON.stringify({ serial, power })}`;
await axios.post(powerApiURL, payload);
} catch (err) {
this.log.warn(`setInverterPower axios error: ${err}`);
}
}
async setInverterRestart(serial, restart) {
try {
const payload = `data=${JSON.stringify({ serial, restart })}`;
await axios.post(powerApiURL, payload);
} catch (err) {
this.log.warn(`setInverterRestart axios error: ${err}`);
}
}
async rewriteYildTotal() {
// Get all StateIDs
const allStateIDs = Object.keys(await this.getAdapterObjectsAsync());
// Get all yieldtotal StateIDs to reset for eg. sourceanalytix
const idsSetToReset = allStateIDs.filter(x => x.endsWith('yieldtotal'));
for (const id of idsSetToReset) {
const currentState = await this.getStateAsync(id);
if (currentState) {
this.setStateAsync(id, currentState.val, true);
}
}
}
async allAvailableToFalse() {
// Get all available StateIDs
const allAvailableStates = Object.keys(await this.getAdapterObjectsAsync()).filter(x => x.endsWith('.available'));
// Set all available StateIDs to false
for (const id of allAvailableStates) {
this.setStateChangedAsync(id, false, true);
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new Opendtu(options);
} else {
// otherwise start the instance directly
new Opendtu();
}