-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
231 lines (206 loc) · 5.82 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
"use strict";
/*
* Created with @iobroker/create-adapter v2.5.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require("@iobroker/adapter-core");
// Load your modules here, e.g.:
const axios = require("axios");
// const https = require("https");
class Kebahp extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: "kebahp",
});
this.apiClient = null;
this.timer = null;
this.on("ready", this.onReady.bind(this));
this.on("unload", this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
try {
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// this.config:
if (!this.config.ipAddress) {
this.log.error(`Heatpump IP address is empty - please check configuration of ${this.namespace}`);
return;
}
if (!this.config.ipAddress.match("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}")) {
this.log.error(`IP address has wrong format - please check configuration of ${this.namespace}`);
return;
}
this.log.debug("Adapter successful started.");
this.apiClient = axios.create({
baseURL: `http://${this.config.ipAddress}`,
timeout: 5000,
responseType: "json",
responseEncoding: "utf8"
});
this.log.debug("axios instance successful created.");
await this.loadData();
}
catch (err) {
this.log.error(`Error during startup wiht message: ${err.message}`);
}
}
async loadData() {
try {
this.log.debug("Load data from heatpump.");
if (!this.apiClient) {
this.log.error("Apiclient not instanced.");
return;
}
const body = this.prepareBody();
this.log.debug(`Parameters for request: ${JSON.stringify(body)}`);
const response = await this.apiClient.post("/var/readWriteVars?languageCode=de", JSON.stringify(body));
this.log.debug(`response ${response.status}: ${JSON.stringify(response.data)}`);
if (response.status === 200) {
await this.updateAllStates(response.data);
}
}
catch (err) {
this.log.error(`Error during loading data: ${err.message}`);
}
finally{
// Restart request load Data!
this.timer = setTimeout(async () => {
this.log.debug("Start next request.");
this.timer = null;
await this.loadData();
}, this.config.refreshIntervall * 1000);
}
}
prepareBody() {
return this.config.datapointsTable.map(f => ({ name: f.datapointName }));
}
/**
* Updates all states.
* @param {object} data JSON Data Array
*/
async updateAllStates(data) {
// Zahlen und Boolen zum richtigen Typen konvertieren!
try {
this.log.debug("Start with Update all States.");
for (let i = 0; i < data.length; i++) {
const obj = data[i];
for (const prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop) && (!isNaN(obj[prop]) || obj[prop] === "false" || obj[prop] === "false")) {
obj[prop] = JSON.parse(obj[prop]);
}
}
}
for (const obj of data) {
const item = this.config.datapointsTable.find(f => f.datapointName == obj.name);
if (item != undefined) {
await this.writeDataToState(
`${item.datapointGroup}.${item.datapointFriendlyName}`,
item.datapointFriendlyName,
item.datapointType,
item.datapointUnit,
obj.value);
}
}
} catch (err) {
this.log.error("Can't update states. " + err.message);
}
}
isInt(n) {
return Number(n) === n && n % 1 === 0;
}
/**
* @param {string | number | boolean} n
*/
isFloat(n) {
return Number(n) === n && n % 1 !== 0;
}
/**
* @param {string} id
* @param {string} name
* @param {any} type
* @param {string | number | boolean} val
*/
async writeDataToState(id, name, type, unit, val) {
await this.extendObjectAsync(id,
{
common: {
name: name,
role: "value",
write: false,
read: true,
type: type,
unit: unit
},
type: "state",
native: {}
});
if (this.isFloat(val)) {
await this.setStateAsync(id, Math.round(Number(val) * 100) / 100, true);
}
else{
await this.setStateAsync(id, val, true);
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
if (state) {
// The state was changed
this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
} else {
// The state was deleted
this.log.info(`state ${id} deleted`);
}
}
// If you need to accept messages in your adapter, uncomment the following block and the corresponding line in the constructor.
// /**
// * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
// * Using this method requires "common.messagebox" property to be set to true in io-package.json
// * @param {ioBroker.Message} obj
// */
// onMessage(obj) {
// if (typeof obj === "object" && obj.message) {
// if (obj.command === "send") {
// // e.g. send email or pushover or whatever
// this.log.info("send command");
// // Send response in callback if required
// if (obj.callback) this.sendTo(obj.from, obj.command, "Message received", obj.callback);
// }
// }
// }
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new Kebahp(options);
} else {
// otherwise start the instance directly
new Kebahp();
}