-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtuya_api_mqtt.js
494 lines (445 loc) · 12.3 KB
/
tuya_api_mqtt.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
var n$ = require('./JsNodeFix.js');
var mqtt = require('mqtt');
var util = require('./Utility.js');
var clone = require('clone');
var appPort = 8082;
var cdnPort = 2362;
n$.trackCL();
util.init(cdnPort, appPort);
var tad = util.devicesList;
var cTad = function()
{
return clone(util.devicesList);
}
var aply = [
{PropertyName: 'telePeriodComplete', PropertyValue : null},
{PropertyName: 'teleTimeoutcb', PropertyValue : null},
{PropertyName: 'mqttSubscribeComplete', PropertyValue : null},
{PropertyName: 'virtualDeviceComplete', PropertyValue : null}
];
var localDevList = n$.LinqIt(util.devicesList).Select([{PropertyName : 'nodeId'}]).ApplyToAll(aply);
setTimeout(function ()
{
for(var i=0; i < tad.length; i++)
{
var v = tad[i];
var vl = n$.LinqIt(localDevList).Where([{PropertyName:'nodeId', PropertyValue: v.nodeId}]).FirstOrDefault()
vl.telePeriodComplete = true;
if(!n$.isNullOrUndef(vl.teleTimeoutcb))
{
clearTimeout(vl.teleTimeoutcb)
}
setTelePeriod(clone(v),vl);
vl.telePeriodComplete = true;
}
}, 15000);
var setTelePeriod = function(v,vl)
{
var t = n$.getTimeOut(v.telePeriod);
var teleCallback = function(args)
{
var d = n$.LinqIt(cTad(),true).Where([{PropertyName : 'nodeId', PropertyValue : args.nodeId}]).FirstOrDefault();
var topic = mqtt_cmnds.tel.format(d.nodeId);
var msg = JSON.stringify(d.getData());
if(n$.isNull(d.setOption19, false))
{
msg = JSON.stringify(d.getData()).toLowerCase();
}
console.log('Publish topic('+topic+')', mqtt.value);
client.publish(topic, msg);
}
vl.teleTimeoutcb = setInterval(teleCallback,t, {nodeId : v.nodeId});
}
var doMqttSubscribe = function(v)
{
//var v = n$.LinqIt(tad,true).Where([{PropertyName : 'nodeId', PropertyValue : nodeId}]).FirstOrDefault();
var nodeId = v.nodeId;
for(var p = 0; p < v.powers.length; p++)
{
var powerId = v.powers[p];
var subTopic = "";
if(n$.isNull(v.isSetOption19,false))
{
subTopic = mqtt_ha_cmnds.sub.power.format(nodeId.toLowerCase(), powerId);
}
else {
subTopic = mqtt_cmnds.sub.power.format(nodeId.toLowerCase(), powerId);
}
client.subscribe(subTopic);
devTopics.push({topic: subTopic, nodeId : nodeId.toLowerCase(), deviceId : powerId, type: 'power'});
}
// Default Power cmnd support
var powerId = "";
var subTopic = "";
if(n$.isNull(v.isSetOption19,false))
{
subTopic = mqtt_ha_cmnds.sub.power.format(nodeId.toLowerCase(), powerId);
}
else {
subTopic = mqtt_cmnds.sub.power.format(nodeId.toLowerCase(), powerId);
}
client.subscribe(subTopic);
devTopics.push({topic: subTopic, nodeId : nodeId.toLowerCase(), deviceId : powerId, type: 'power'});
if(v.isDimmer)
{
var subTopic = ""
if(n$.isNull(v.isSetOption19,false))
{
subTopic = mqtt_ha_cmnds.sub.dimmer.format(nodeId.toLowerCase());
}
else {
subTopic = mqtt_cmnds.sub.dimmer.format(nodeId.toLowerCase());
}
client.subscribe(subTopic);
devTopics.push({topic: subTopic, nodeId : nodeId.toLowerCase(), deviceId : v.dimmerId, type: 'dimmer'});
}
}
var client = {};
if(util.mqttUseSequreLogin)
{
client = mqtt.connect(util.mqttServer, {username: util.mqttUsername, password: util.mqttPassword ,clientId : util.mqttClientId});
}
else
{
client = mqtt.connect(util.mqttServer);
}
var devTopics = [];
var ignoreTopic = [];
var createDevice = function() {};
var mqtt_cmnds = {sub:{power:'cmnd/{0}/power{1}', dimmer : 'cmnd/{0}/dimmer', tele: 'cmnd/{0}/teleperiod'}, pub: 'stat/{0}/RESULT', tel : 'tele/{0}/STATE'};
var mqtt_ha_cmnds = {sub:{power:'cmnd/{0}/power{1}', dimmer : 'cmnd/{0}/dimmer', tele: 'cmnd/{0}/teleperiod'}, pub: 'stat/{0}/result', tel : 'tele/{0}/state'};
client.on('connect', function ()
{
for(var i=0; i < tad.length; i++)
{
var v = tad[i];
doMqttSubscribe(v);
var vl = n$.LinqIt(localDevList).Where([{PropertyName:'nodeId', PropertyValue: v.nodeId}]).FirstOrDefault()
vl.mqttSubscribeComplete = true;
}
});
client.on('message', function (topic, message)
{
var msg = message.toString();
if(msg == "")
{
console.log('topic ('+topic+') with no message data ignored');
return;
}
var devtopic = n$.LinqIt(devTopics).Where([{PropertyName: 'topic' , PropertyValue: topic.toLowerCase()}]).FirstOrDefault();
var nodeId = devtopic.nodeId;
var device = n$.LinqIt(dil, true).Where([{PropertyName: 'nodeId' , PropertyValue: nodeId}]).FirstOrDefault();
if(!device.instance.isReady)
{
console.log('topic ('+topic+') with message ('+msg+') ignored as device is offline ');
return;
}
var req = {query : {}};
req.query = {nodeId: nodeId}
var cdeviceId = devtopic.deviceId == '' ? '1' : devtopic.deviceId;
console.log('Mqtt message device ID ' + cdeviceId);
if(devtopic.type == 'dimmer')
{
var val = n$.isNull(parseInt(msg),1);
req.query['d'] = val;
}
if(devtopic.type == 'power')
{
req.query['o'] = cdeviceId;
req.query['p'] = msg;
}
util.processSetRequest(req, device);
});
var TuyAPI = require('tuyapi');
var publishMqtt = function(mqtt)
{
//console.log('Publish Mqtt:', mqtt)
var topic = "";
if(n$.isNull(mqtt.isHa, false))
{
if(mqtt.type == 'Result')
{
topic = 'stat/{0}/result'.format(mqtt.nodeId);
}
if(mqtt.type == 'Power')
{
topic = 'stat/{0}/power{1}'.format(mqtt.nodeId, mqtt.param);
}
if(mqtt.type == 'Dimmer')
{
topic = 'stat/{0}/result'.format(mqtt.nodeId);
}
}
else {
if(mqtt.type == 'Result')
{
topic = 'stat/{0}/RESULT'.format(mqtt.nodeId);
}
if(mqtt.type == 'Power')
{
topic = 'stat/{0}/POWER{1}'.format(mqtt.nodeId, mqtt.param);
}
if(mqtt.type == 'Dimmer')
{
topic = 'stat/{0}/RESULT'.format(mqtt.nodeId);
}
}
console.log('Publish topic('+topic+')', mqtt.value);
client.publish(topic, mqtt.value);
}
var processData = function(data, di)
{
console.log('called processData: for '+di, data)
var dip = n$.LinqIt(tad, true).Where([{PropertyName : 'nodeId', PropertyValue: di}]).FirstOrDefault();
//dimmer
if(!n$.isNullOrUndef(data.dps[dip.dimmerId]))
{
var mcuDimmer = dip.parseDimmer(data.dps[dip.dimmerId]);
var webDimmer = dip.getDimmer();
dip.setDimmer(data.dps[dip.dimmerId]);
console.log(dip.nodeId + ' dip.setDimmer()' , dip.getDimmerP());
console.log(dip.nodeId + ' mcuDimmer' , mcuDimmer);
var mqtt = {};
mqtt.type = 'Dimmer';
mqtt.value = mqtt.value = '{"'+'POWER1":"' + dip.data['POWER1'] + '","Dimmer":' +mcuDimmer+'}';
if(n$.isNull(dip.setOption19, false))
{
mqtt.isHa = true;
mqtt.value = mqtt.value = '{"'+'power1":"' + dip.data['POWER1'] + '","dimmer":' +mcuDimmer+'}';
}
mqtt.nodeId = di;
mqtt.param = "";
publishMqtt(mqtt);
}
//power
var power= 0;
for(var p =0 ; p< dip.powers.length;p++)
{
pow = dip.powers[p];
if(!n$.isNullOrUndef(data.dps[pow]))
{
var pushPower = data.dps[pow] ? 'ON' : 'OFF';
//if(dip.data['POWER' + pow] != pushPower)
//{
dip.data['POWER' + pow] = pushPower;
var mqtt = {};
mqtt.type = 'Result';
mqtt.value = '{"'+'POWER' + pow + '" : "' + dip.data['POWER' + pow] +'"}';
if(n$.isNull(dip.setOption19, false))
{
mqtt.isHa = true;
mqtt.value = '{"'+'power' + pow + '" : "' + dip.data['POWER' + pow] +'"}';
}
mqtt.nodeId = di;
mqtt.param = "";
publishMqtt(mqtt);
if(pow == 1)
{
var mqtt = {};
mqtt.type = 'Power';
mqtt.value = dip.data['POWER' + pow];
if(n$.isNull(dip.setOption19, false))
{
mqtt.isHa = true;
}
mqtt.nodeId = di;
mqtt.param = pow.toString();
publishMqtt(mqtt);
}
//}
}
}
}
var createDevice = function(devId, key, nodeId)
{
var device = new TuyAPI({
id: devId,
key: key});
device.nodeId = nodeId;
device.isReady = false;
// Find device on network
device.find().then(() =>
{
// Connect to device
device.connect();
});
// Add event listeners
device.on('connected', () => {
console.log('Connected to ' +device.nodeId);
device.isReady = true;
//console.log('Connected to: ', device);
});
device.on('disconnected', () => {
//console.log('Disconnected from device.');
device.isReady = false;
});
device.on('error', error => {
////console.log('Error!', error);
device.isReady = false;
setTimeout(function() {
device.find().then(() => {
// Connect to device
device.connect();
});
}, 10000);
});
device.on('data', data => {
console.log('Data from device:', data);
// process Data Here
processData(data,device.nodeId);
});
return device;
}
var dil = [];
var createVirtualTasmotaDevice = function(devId,key,nodeId)
{
var dev = createDevice(devId,key,nodeId);
dil.push({nodeId : nodeId, instance : dev});
}
for(var t = 0; t < tad.length; t++)
{
var d = tad[t];
createVirtualTasmotaDevice(d.devId,d.key,d.nodeId);
var vl = n$.LinqIt(localDevList).Where([{PropertyName:'nodeId', PropertyValue: d.nodeId}]).FirstOrDefault()
vl.mqttSubscribeComplete = true;
}
var http = require('http');
var httpnds = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var cPath = require('path');
var fs = require('fs');
var userInfo = {};
var session = require('express-session');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded(
{
extended: true
}));
app.use(session(
{
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(function (req, res, next)
{
if (!req.session.key) {
req.session.key = {};
}
if (!req.session.isValid)
{
req.session.isValid = false;
}
if (!req.session.data)
{
req.session.data = {};
}
next()
})
app.get('/', function (req, res)
{
var pageData = util.processPageRequest(req);
res.send(pageData);
});
app.get('/gd', function (req, res)
{
var gReq = util.processGetRequest(req);
res.send(gReq);
});
app.get('/sd', function (req, res)
{
var device = n$.LinqIt(dil, true).Where([{PropertyName: 'nodeId' , PropertyValue: req.query.nodeId}]).FirstOrDefault();
var gReq = util.processSetRequest(req, device);
res.send(gReq);
});
app.get('/font-awesome/css/font-awesome.min.css',function(req,res)
{
res.set('Content-Type', 'text/css');
res.send(util.getFontawsome(req));
});
app.get('/gettemplate',function(req,res)
{
res.send(util.getTemplate(req));
});
app.get('/cn',function(req,res)
{
res.send(util.getTasmotaConfig(req));
});
app.get('/cl',function(req,res)
{
res.send(util.getTasmotaConsole(req));
});
app.get('/ax',function(req,res)
{
res.send(n$.g_log.join('\n'));
});
app.get('/ccl',function(req,res)
{
n$.g_log = [];
res.send("Console is cleared !");
});
app.get('/nu',function(req,res)
{
res.send(util.getNewTasmotaDev(req));
});
app.get('/dcu',function(req,res)
{
res.send(util.updateTasmotaDev(req));
});
app.get('/and',function(req,res)
{
var result = util.addNewTasmotaDev(req);
for(var i=0; i < util.devicesList.length; i++)
{
var v = util.devicesList[i];
var i = n$.LinqIt(localDevList).Where([{PropertyName : 'nodeId', PropertyValue: v.nodeId}]).FirstOrDefault();
if(n$.isNullOrUndef(i))
{
localDevList.push({
nodeId : v.nodeId,
telePeriodComplete:null,
teleTimeoutcb:null,
mqttSubscribeComplete:null,
virtualDeviceComplete:null
});
}
}
for(var i=0; i < localDevList.length; i++)
{
var vl = localDevList[i];
var v = n$.LinqIt(util.devicesList).Where([{PropertyName : 'nodeId', PropertyValue: v.nodeId}]).FirstOrDefault();
if(!vl.telePeriodComplete)
{
setTelePeriod(v,vl);
}
if(!vl.mqttSubscribeComplete)
{
doMqttSubscribe(v);
}
if(!vl.virtualDeviceComplete)
{
var vc = clone(v);
createVirtualTasmotaDevice(vc.devId, vc.key, vc.nodeId);
v.virtualDeviceComplete = true;
}
}
res.send(result.message);
});
// ------------------------------ Mqtt Ends -----------------------------------------
// htpp Server
var httpServer = http.createServer(app);
httpServer.listen (appPort);
console.log('Web Server Running on Port 8082');
var express = require('express');
var path = require('path');
var app = express();
// Define the port to run on
app.set('port', cdnPort);
app.use(express.static(path.join(__dirname, 'cdn2')));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('CDN Running on Port ' + port);
});