-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.js
231 lines (197 loc) · 7.3 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
/**
* Oilfox adapter
*/
'use strict';
const utils = require('@iobroker/adapter-core');
const https = require('https');
const adapterName = require('./package.json').name.split('.').pop();
let adapter;
let watchdog;
function onTimeout() {
adapter.log.warn('Timeout occured, adapter terminated by watchdog');
adapter.stop();
}
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: adapterName,
ready: async () => {
try {
adapter.log.debug('adapter.on-ready: << READY >>');
if (adapter.config.email && adapter.config.password) {
watchdog = adapter.setTimeout (onTimeout, 45*1000 );
await main();
} else {
adapter.log.warn('No E-Mail or Password set');
adapter.stop();
}
} catch (err) {
adapter.log.error(err);
adapter.stop();
}
},
unload: (callback) => {
if (watchdog) adapter.clearTimeout(watchdog);
// callback must be called under all circumstances
callback && callback();
}
});
adapter = new utils.Adapter(options);
return adapter;
}
function connectOilfox() {
const postData = JSON.stringify({
email: adapter.config.email,
password: adapter.config.password
});
const request_options = {
host: 'api.oilfox.io',
// host: '10.1.1.1', // test timeout
port: '443',
path: '/customer-api/v1/login',
method: 'POST',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'Connection': 'Keep-Alive',
//'User-Agent': 'okhttp/3.2.0',
'Content-Length': postData.length,
'Accept': '*/*',
'User-Agent': 'ioBroker.oilfox'
}
};
const tokenRequest = https.request(request_options, tokenRequestResult => {
tokenRequestResult.setEncoding('utf8');
let tokenData = '';
tokenRequestResult.on('data', chunk => {
adapter.log.debug(`received chunk: ${chunk}`);
tokenData += chunk;
});
tokenRequestResult.on('end', () => {
adapter.log.debug(`received data: ${tokenData}`);
const tokenObject = JSON.parse(tokenData);
request_options.headers['Authorization'] = `Bearer ${tokenObject.access_token}`;
request_options.path = '/customer-api/v1/device';
request_options.method = 'GET';
const summaryRequest = https.request(request_options, (summaryRequestResult) => {
summaryRequestResult.setEncoding('utf8');
let summaryData = '';
summaryRequestResult.on('data', chunk => {
adapter.log.debug(`received chunk2: ${chunk}`);
summaryData += chunk;
});
summaryRequestResult.on('end', async () => {
adapter.log.debug(`received data 2: ${summaryData}`);
try {
const summaryObject = JSON.parse(summaryData);
await createStateObjectsFromResult(summaryObject);
adapter.log.debug('create state objects from summary');
adapter.log.debug('update states from summary');
await updateStatesFromResult(summaryObject);
} catch (err) {
adapter.log.error(`error processing summary data: ${summaryData}`);
adapter.log.error(`${err}`);
}
adapter.stop();
});
});
summaryRequest.end();
});
});
adapter.log.debug(`send data: ${postData}`);
tokenRequest.write(postData);
tokenRequest.end();
}
async function main() {
adapter.log.debug('adapter.main: << MAIN >>');
const obj = await adapter.getForeignObjectAsync(`system.adapter.${adapter.namespace}`);
adapter.log.info(`adapter scheduling set to ${obj.common.schedule}`);
const schedule = obj.common.schedule || '* * * * *';
if ((schedule === '* * * * *') || ( schedule === '0/59 * * * *')) {
adapter.log.warn('default schedule detected, setting random value');
const minute = Math.trunc(Math.random() * (59-1) + 1); // 1 - 59, omit 0
const newSchedule = `${minute} * * * *`;
adapter.log.warn(`schedule will be set to ${newSchedule}`);
obj.common.schedule = newSchedule;
await adapter.setForeignObjectAsync(`system.adapter.${adapter.namespace}`, obj);
await adapter.stop();
}
connectOilfox();
}
async function createStateObjectsFromResult(summaryObject) {
for (const p in summaryObject) {
if (typeof summaryObject[p] !== 'object') {
await adapter.setObjectNotExistsAsync('info.' + p, {
type: 'state',
common: {
'name': p,
'role': 'state',
'type': typeof summaryObject[p],
'write': false,
'read': true
},
native: {}
});
}
}
let i = 0;
for (const p in summaryObject.items) {
for (const pp in summaryObject.items[p]) {
if (typeof summaryObject.items[p][pp] !== 'object') {
await adapter.setObjectNotExistsAsync(`items.${i}.${pp}`, {
type: 'state',
common: {
'name': 'device.' + pp,
'role': 'state',
'type': typeof summaryObject.items[p][pp],
'write': false,
'read': true
},
native: {}
});
}
}
i++;
}
}
async function updateStatesFromResult(summaryObject) {
try {
for (const p in summaryObject) {
if (typeof summaryObject[p] !== 'object') {
await adapter.setStateAsync('info.' + p, summaryObject[p], true);
}
}
for (const p in summaryObject.items) {
let state = null;
let j = 0;
while (j < summaryObject.items.length) {
state = await adapter.getStateAsync('items.' + j + '.id');
if (state != null && (!state.val || state.val == summaryObject.items[p].id)) {
break;
}
else if (state == null) {
state = true; //first run
break;
}
state = null;
j++;
}
if (state) {
for (const pp in summaryObject.items[p]) {
if (typeof summaryObject.items[p][pp] !== 'object') {
await adapter.setStateAsync(`items.${p}.${pp}`, summaryObject.items[p][pp], true);
}
}
}
}
} catch (err) {
adapter.log.error(err);
}
}
// If started as allInOne/compact mode => return function to create instance
if (module && module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}