-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtuya1.js
98 lines (79 loc) · 2.21 KB
/
tuya1.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
const TuyAPI = require('tuyapi');
const express = require('express')
var app = express();
var server = require('http').Server(app);
app.get('/tuya/switch', (req, res) => {
switchNumber = req.query.switch
state = req.query.state
deviceid = req.query.deviceid
devicekey = req.query.devicekey
version = req.query.version
console.log(deviceid, devicekey, version)
if (deviceid == undefined || devicekey == undefined || version == undefined){
res.send('Device ID/ Device Key/ version is missing')
}
const device = new TuyAPI({
//id: '44536070b4e62d127f6c',
id: deviceid,
//key: 'e6ed32406cd6d82d',
key: devicekey,
//version: '3.3'
version: version
});
console.log(state, switchNumber)
if (state=='on' || state == 'true'){
state = true
}
else if(state=='off' || state=='false'){
state=false
}
else{
res.send('state params can be (true/false) or (on/off)')
}
if (switchNumber < 1 || switchNumber > 3){
res.send('Switch number can be in range: (1-3)' )
}
dothis(device, switchNumber, state, res)
// Disconnect after 10 seconds
setTimeout(() => {
}, 10000);
})
function dothis(device, switchNumber, state, res){
let stateHasChanged = false;
device.find().then(() => {
// Connect to device
console.log('here')
device.connect().then(()=>{
if (!stateHasChanged && !(res.headersSent)) {
console.log('state',state)
console.log('switchNumber',switchNumber)
device.set({dps:parseInt(switchNumber),set: state});
stateHasChanged = true;
res.send({'code': 200,
'status': 'actions is performed'
})
}
device.disconnect();
if (!(res.headersSent)){
res.send({'code': 400,
'status': 'device is disconnected'});
}
})
});
/*device.on('connected', () => {
console.log('Connected to device!');
});*/
console.log(res.headersSent)
device.on('disconnected', () => {
console.log('Disconnected from device.');
});
device.on('error', error => {
console.log('Error!', error);
res.send(error)
});
device.on('data', data => {
// Set default property to opposite
//device.disconnect()
});
}
server.listen(3050)