forked from DJONvl/ioBroker.mysensors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysensors.js
344 lines (282 loc) · 11.7 KB
/
mysensors.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";
// you have to require the utils module and call adapter function
var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var adapter = utils.adapter('mysensors');
var stopTimer = null;
var Sensors = require('sensors');
var serialport = require('serialport');//.SerialPort;
var SerialPort = serialport.SerialPort;
var portConfig = {baudRate: 115200, parser: serialport.parsers.readline('\n')};
var G_myPort;
//принимаем и обрабатываем сообщения
adapter.on('message', function (obj) {
if (obj) {
switch (obj.command) {
case 'list_uart':
//ToDo отдать список портов
serialport.list(function (err, ports) {
if (obj.callback) {
adapter.log.info('obj.callback...ToDo выслать список СОМ портов');
adapter.sendTo(obj.from, obj.command, ports, obj.callback);
}
});
break;
case 'list_dbsU'://ToDo отдать список юнитов
if (obj.callback) {
adapter.log.info('obj.callback...ToDo выслать список юнитов');
adapter.sendTo(obj.from, obj.command, dbsUnique, obj.callback);
}
break;
}
}
});
var mysdevs = []; // список устройств mysensor
function pingAll() {
adapter.log.info('Ping-all' + adapter.config.comlst);
if (stopTimer) clearTimeout(stopTimer);
var count = mysdevs.length;
adapter.log.info('count-' + mysdevs.length);
mysdevs.forEach(function (_mysdevice) {
adapter.log.info('tada-- ' + _mysdevice);
});
}
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
try {
adapter.log.info('cleaned everything up...');
callback();
} catch (e) {
callback();
}
});
// is called if a subscribed object changes
adapter.on('objectChange', function (id, obj) {
// Warning, obj can be null if it was deleted
adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj));
});
// is called if a subscribed state changes
adapter.on('stateChange', function (id, state) {
// Warning, state can be null if it was deleted
// if (!state && state.ack) return;
adapter.log.info('stateChange ' + id + ' ' + JSON.stringify(state));
// If no serial port configured, but state change received
if (!G_myPort) return;
//________________выводим в порт___________________________________________
for (var co = 0; co < adapter.config.devices.length; co++) {
if (id == adapter.namespace + '.' + adapter.config.devices[co].name){
var msg_s;
msg_s = adapter.config.devices[co].raw + ';' +
state.val + '\n';
G_myPort.write(msg_s);
adapter.log.info('mesage-'+msg_s);
}
adapter.log.info(adapter.config.devices[co].name+ ';' + adapter.config.devices[co].node_id)
}
//----------------------------------------------------------------------------
// you can use the ack flag to detect if it is status (true) or command (false)
if (state && !state.ack) {
adapter.log.info('ack is not set!');
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', function () {
main();
});
var dbsUnique = [];//будут хранится уникальные посылки от всех юнитов, из ком порта
// ---------------------------------------------------------
// node-id; child-sensor-id; message-type; ack; sub-type; payload\n
// ---------------------------------------------------------
function mkdbmsgUnique(str) {
var valcsv = str.split( ";" ); //элементы строки лога
var fl = false;
var result = Sensors.parse(str.toString());
if (!result || !result.length) {
adapter.log.warn('Cannot parse data: ' + str);
return null;
}
var i=0;
var raw=valcsv[0]+';'+valcsv[1]+';'+valcsv[2]+';'+valcsv[3]+';'+valcsv[4];
valcsv[0] = result[i].id ;
valcsv[1] =result[i].childId ;
valcsv[2] =result[i].type ;
valcsv[3] = result[i].ack ;
valcsv[4] =result[i].subType ;
valcsv[5] =result[i].payload;
adapter.log.debug("количество сообщений " + dbsUnique.length);
for (var n = 0; n < dbsUnique.length; n++) {
if (dbsUnique[n].NodeId == valcsv[0] &&
dbsUnique[n].ChildId == valcsv[1] &&
dbsUnique[n].MsgType == valcsv[2] &&
dbsUnique[n].Data_type == valcsv[4]
){
// dbsUnique[n].==valcsv[3] &&
// dbsUnique[n].==valcsv[4] &&
// dbsUnique[n].==valcsv[5] &&
// dbsUnique[n].==valcsv[6] //sub-type
fl = true;
dbsUnique[n].Value = valcsv[5];//todo сравнить с олд вал и изменить стейт
}
}
// if (fl == false && valcsv[0] !== "0"){//не добавляем ноду шлюза
if (fl == false ){//не добавляем ноду шлюза
dbsUnique.push({
"NodeId": valcsv[0],
"ChildId": valcsv[1],
"MsgType": valcsv[2],
"Ack": valcsv[3],
"Data_type": valcsv[4],
"Value": valcsv[5],
"raw": raw
});
// tree.push( str );
}
return result;
}
function syncObjects(index, cb) {
if (typeof index === 'function') {
cb = index;
index = 0;
}
index = index || 0;
if (!adapter.config.devices || index >= adapter.config.devices.length) {
cb && cb();
return;
}
var id = adapter.config.devices[index].name.replace(/[.\s]+/g, '_');
adapter.getObject(id, function (err, obj) {
if (err) adapter.log.error(err);
// if new or changed
if (!obj || JSON.stringify(obj.native) !== JSON.stringify(adapter.config.devices[index])) {
adapter.setObject(id, {
common: {
name: adapter.config.devices[index].name,
def: false,
type: 'boolean', // нужный тип надо подставить
read: 'true',
write:'true', // нужный режим надо подставить
role: 'state',
desc: obj ? obj.common.desc : 'Variable from mySensors'
},
type: 'state',
native: adapter.config.devices[index]
}, function (err) {
// Sync Rooms
adapter.deleteStateFromEnum('rooms', '', '', id, function () {
if (adapter.config.devices[index].room) {
adapter.addStateToEnum('rooms', adapter.config.devices[index].room, '', '', id);
}
});
if (err) adapter.log.error(err);
if (!obj) {
adapter.log.info('Create state ' + id);
// if new object => create state
adapter.setState(id, null, true, function () {
setTimeout(function () {
syncObjects(index + 1, cb);
}, 0);
});
} else {
adapter.log.info('Update state ' + id);
setTimeout(function () {
syncObjects(index + 1, cb);
}, 0);
}
});
} else {
setTimeout(function () {
syncObjects(index + 1, cb);
}, 0);
}
});
}
function deleteStates(states, cb) {
if (!states || !states.length) {
cb && cb();
return;
}
var id = states.pop();
adapter.log.info('Delete state ' + id);
adapter.delForeignObject(id, function (err) {
adapter.deleteStateFromEnum('rooms', '', '', id);
if (err) adapter.log.error(err);
adapter.delForeignState(id, function (err) {
if (err) adapter.log.error(err);
setTimeout(function () {
deleteStates(states, cb);
}, 0);
})
});
}
function main() {
// read current existing objects
adapter.getForeignObjects(adapter.namespace + '.*', 'state', function (err, states) {
var toDelete = [];
// delete non existing objects
for (var id in states) {
var isFound = false;
for (var i2 = 0; i2 < adapter.config.devices.length; i2++) {
if (adapter.config.devices[i2].name === states[id].common.name) {
isFound = true;
break;
}
}
if (!isFound) toDelete.push(id);
}
// delete non existing states
deleteStates(toDelete, function () {
// create new or modified states
syncObjects(function () {
// подписываемся на изменения извне
adapter.subscribeStates('*');
for (var i = 0; i < adapter.config.devices.length; i++) {
mysdevs.push(adapter.config.devices[i].name);
}
//------------------------------------------------------------------
adapter.log.debug('Communication port:' + adapter.config.comName);
// open the serial port:
if (adapter.config.comName) {
var myPort = new SerialPort(adapter.config.comName, portConfig);
G_myPort=myPort;
// ловим события порта
myPort.on('data', function(data) {
adapter.log.info('Rx-Raw '+data);
var tmp= data.split( ";" );
if(tmp.length < 6){
adapter.log.info('raw_data_error '+ tmp.length);
}else{
mkdbmsgUnique(data); //пишем в массив уникальных сообщений
var result = Sensors.parse(data.toString());
//___________________________Устанавливаем значение переменной по имени из ком порта____________________________________________
for (var co = 0; co < adapter.config.devices.length; co++) {
if ( result[0].subType +
'_' + result[0].id +
'_' + result[0].childId == adapter.config.devices[co].name){
adapter.setState(adapter.config.devices[co].name, result[0].payload);
}
}
//------------------------------------------------------------------------------------------------------------------------------
for(var i in result) {
adapter.log.info('__' +
result[i].id + '_|_' +
result[i].childId + '_|_' +
result[i].type + '_|_' +
result[i].ack + '_|_' +
result[i].subType + '_|_' +
result[i].payload);
}
}
});
}
//-----------------------------------------------------------------
// myPort.write("1;1;1;1;3;0\n");
// myPort.write("2;1;1;1;2;1\n");
// pingAll();
// timer = setInterval(pingAll, adapter.config.interval);
});
});
});
if (adapter.config.interval < 5000) adapter.config.interval = 5000;
}