-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
310 lines (287 loc) · 12.1 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
'use strict';
/*
* Created with @iobroker/create-adapter v2.0.1
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const net = require("net");
const Json2iob = require("./lib/json2iob");
class Pilightapi extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'pilightapi',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
this.setState("info.connection", false, true);
this.config = {
pilightip: this.config.pilightip || 'localhost',
pilightdaemonport: this.config.pilightdaemonport || 5000
};
this.jsonString = "";
this.countS = 0;
this.sentiob = 0;
this.json2iob = new Json2iob(this);
this.subscribeStates('*');
await this.connectToNet();
}
/**
* Connected Pilight
*
*/
async connectToNet() {
if (this.client) {
this.client.end();
}
this.countS = 0;
this.sentiob = 0;
this.client = net.createConnection({ host: this.config.pilightip, port: this.config.pilightdaemonport }, () => {
this.client.write('{"action": "identify","options":{"core": 1,"receiver": 1,"config": 1,"forward": 1},"uuid": "0000-d0-63-00-000000","media": "all"}\n');
});
this.client.on('data', async (data) => {
if (this.wsHeartbeatTimeout) {
clearTimeout(this.wsHeartbeatTimeout);
}
this.wsHeartbeatTimeout = setTimeout(() => {
this.log.info("Lost Socket connection. Reconnect Socket");
this.client.end();
setTimeout(() => {
this.connectToNet();
}, 2000);
}, 60 * 1000);
try {
this.log.debug("Data: " + data.toString("utf-8"));
const result = data.toString("utf-8").split('\n\n');
if (result.length === 1) {
this.jsonString += data;
if (this.jsonString.toString("utf-8") === "1") {
this.log.warn("Pilight stopped!!!");
this.jsonString = "";
return;
}
this.log.debug("Datafirst: " + this.jsonString.toString("utf-8"));
} else {
this.log.debug("Dataall1: " + this.jsonString + " -- " + data);
this.jsonString += data;
this.log.debug("Dataall2: " + this.jsonString);
this.jsonString = this.jsonString.replace(/\}{/g, '}\n{');
this.log.debug("Dataall3: " + this.jsonString);
this.jsonString.split('\n').forEach( async (v) => {
if (v) {
this.log.debug("Data: " + v.trim());
await this.jsonEvaluate(v.trim())
}
});
this.jsonString = "";
}
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
}
this.heartbeatInterval = setInterval(() => {
this.log.debug("Send heartbeat!");
this.client.write('HEART\n');
}, 10 * 1000);
} catch (err) {
this.log.error("connectToNet: " + err);
}
});
this.client.on('end', () => {
this.log.info('disconnected from server');
});
this.client.on('error', (err) => {
this.log.error('Error: ' + err);
});
}
/**
* json string evaluate!
* @param JSON -> Callback
*/
async jsonEvaluate(JsonStr) {
if(JsonStr === "BEAT") {
this.log.debug("Heartbeat OK!");
return true;
}
try {
let jsonMessage = JSON.parse(JsonStr.replace(/\]/g, '').replace(/\[/g, '').replace(/\"on\"/g, '"true"').replace(/\"off\"/g, '"false"'));
//if(jsonMessage.origin !== "core") this.log.info("Jsonparse: " + JSON.stringify(jsonMessage));
this.log.debug("Jsonparse: " + JSON.stringify(jsonMessage));
if(jsonMessage.status === "success" && this.countS === 0) {
this.log.info("Server connected!");
this.client.write('{"action": "request config"}\n');
this.log.info("Send request for the config!");
this.setState("info.connection", true, true);
return true;
}
if(jsonMessage.status === "failure" && this.countS === 0) {
this.log.info("Server not connected!");
this.setState("info.connection", false, true);
return false;
}
if(jsonMessage.status === "success" && this.countS === 1) {
this.log.debug("Command was sent!");
return true;
}
if(jsonMessage.status === "failure" && this.countS === 1) {
this.log.debug("Command was not sent!");
return false;
}
if(jsonMessage.message === "config") {
//const items = ['devices', 'rules', 'gui', 'settings', 'hardware', 'registry'];
const items = ['devices'];
for (let i=0; i<items.length; i++) {
if (Object.keys( jsonMessage["config"][items[i]] ).length > 0) {
this.log.info("Create data point " + items[i] + ": " + Object.keys( jsonMessage["config"][items[i]] ).length);
this.setObjectNotExistsAsync(items[i], {
type: "channel",
common: {
name: items[i],
},
native: {},
});
if (items[i] === 'devices') {
this.json2iob.parse(jsonMessage["config"]["gui"], items[i], jsonMessage["config"][items[i]]);
} else {
this.json2iob.parse("", items[i], jsonMessage["config"][items[i]]);
}
}
}
return true;
}
if(jsonMessage.action === "send") {
this.countS = 1;
this.log.debug("Send request for the config!");
return true;
}
if(jsonMessage.origin === "update" && this.sentiob === 0) {
this.log.debug("Receive input!");
Object.keys(jsonMessage).forEach((n) => {
if(n === "values") {
Object.keys(jsonMessage[n]).forEach((v) => {
this.log.debug(this.namespace + ".devices." + jsonMessage["devices"] + "." + v);
this.getForeignObject(this.namespace + ".devices." + jsonMessage["devices"] + "." + v, async (err, obj) => {
let statebol = jsonMessage[n][v];
if(statebol === "false") {
statebol = false;
} else if(statebol === "true") {
statebol = true;
}
if (!obj || !obj.common) {
this.setObjectNotExists(this.namespace + ".devices." + jsonMessage["devices"] + "." + v, {
type: 'state',
common: {
name: v,
type: 'number',
read: true,
write: false,
role: 'level',
def: 0,
desc: 'Create Timestamp'
},
native: {}
});
await this.sleep(2000);
this.setState(this.namespace + ".devices." + jsonMessage["devices"] + "." + v, statebol, true);
} else {
this.setState(this.namespace + ".devices." + jsonMessage["devices"] + "." + v, statebol, true);
}
});
});
}
});
return true;
} else if(jsonMessage.origin === "update" && this.sentiob === 1) {
this.log.debug("Receive input from iobroker!");
this.sentiob = 0;
return true;
}
} catch (err) {
this.log.error("jsonEvaluate: " + err + " - " + JsonStr);
}
}
/**
* Sleep!
*
*/
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.setState("info.connection", false, true);
clearInterval(this.heartbeatInterval);
clearInterval(this.wsHeartbeatTimeout);
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 && !state.ack) {
this.log.debug('Send id: ' + id);
this.log.debug('Send state: ' + state.val);
let states = null;
const lastsplit = id.split('.')[id.split('.').length-1];
const name = id.split('.')[id.split('.').length-2];
this.log.debug('Send last: ' + lastsplit);
if(lastsplit === "state") {
states = (state.val) ? "on" : "off";
this.sentiob = 1;
this.client.write(JSON.stringify({
"action": "control",
"code": {
"device": name,
"state": states
}
}));
} else if(lastsplit === "dimlevel") {
states = (state.val === 0) ? "off" : "on";
this.sentiob = 1;
this.client.write(JSON.stringify({
"action": "control",
"code": {
"device": name,
"state": states,
"values": {
"dimlevel": state.val
}
}
}));
} else {
this.log.info("Command " + lastsplit + " not implemented");
this.log.info("Path: " + lastsplit);
this.log.info("Value: " + lastsplit);
}
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new Pilightapi(options);
} else {
// otherwise start the instance directly
new Pilightapi();
}