-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcloudtuya.js
258 lines (241 loc) · 6.88 KB
/
cloudtuya.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
/**
* CloudTuya
* A module that uses the tuya cloud api, to get and set device states
* It usues your tuya/smartlife email and pass
*/
const request = require('request');
const debug = require('debug')('cloudtuya');
// DEBUG=* node cloudtuya to enable debug logs
const name = 'cloudtuya';
debug('booting %s', name);
/**
* A CloudTuya object
* @class
* @param {Object} options construction options
* @param {String} [options.region='eu'] region us=Americas, cn=Asia, eu=Europe)
* @param {String} [options.deviceID] ID of device calling API (defaults to a random value)
* @param {String} options.userName App email to login to App on phone
* @param {String} options.password App password
* @param {String} [options.bizType='smart_life'] App business ('tuya' or 'smart_life')
* @param {String} [options.countryCode='44'] Country code (International dialing number)
* */
class CloudTuya {
constructor(options) {
// Set to empty object if undefined
const config = (options) || {};
this.devices = [];
if(!config.userName || !config.password) {
throw new Error('Missing loging email/pass');
} else{
this.core = {
userName: config.userName,
password: config.password,
countryCode: config.countryCode || '44',
bizType: config.bizType || 'smart_life',
from: 'tuya',
};
}
this.tokenValidTo = 0;
// Specific endpoint where no key/secret required
config.region = (config.region && (config.region.toLowerCase() in ['cn', 'eu', 'us']))
? config.region
: 'eu';
this.uri = 'https://px1.tuyaeu.com/homeassistant'.replace('eu', config.region);
}
/**
* POSTS request with options arg
* @param {Object} options request options
* @param {String} options.uri uri/url
* @param {String} [options.method='POST'] Request type
* @param {Object} options.headers Request headers
* @param {Object} options.json JSON request data OR
* @param {Object} options.form Form request data
*/
async post(options) {
// get token if missing or expired
// Only run if uri not auth.do
if(!options.uri.includes('auth.do')) {
if(!this.tokens) await this.getToken();
if((this.tokenValidTo - (new Date()).getTime()) < 360) await this.refreshToken();
}
// Set to empty object if undefined
const config = (options) || {};
config.method = 'POST';
debug(`REQUEST POST: ${JSON.stringify(config)}`);
return new Promise((resolve, reject) => {
request(config, (err, response, body) => {
if(!err && response.statusCode === 200) {
debug(body);
resolve(body);
} else if(err) reject(err);
});
});
}
/**
* Find devices
* @param {String} id Get id or find all if missing
*/
async find(id) {
// Set options to find devices
const uri = `${this.uri}/skill`;
const data = {
header: {
name: 'Discovery',
namespace: 'discovery',
payloadVersion: 1,
},
payload: {
accessToken: this.accessToken,
},
};
const headers = {
'Content-Type': 'application/json',
};
const postConfig = {
uri,
method: 'POST',
headers,
json: data,
};
// Get devices from request
const{ payload: { devices } } = await this.post(postConfig);
this.devices = devices;
this.currentDevices = devices;
debug(devices);
// Check if device is in device list first
if(id) {
const matchDevice = await this.devices.filter(device => device.id === id);
if(matchDevice) this.currentDevices = matchDevice;
}
return this.currentDevices;
}
/**
* Converts true/false to ON/OFF
* @param {boolean} itemState
*/
static smap(itemState) {
return(itemState && 'ON') || 'OFF';
}
/**
* Convert text on/off, logic and numbers into 1/0 values
* @param {String/Boolean/Number} itemState
*/
static lmap(itemState) {
if((typeof itemState === 'number')
&& (itemState === 0
|| itemState === 1)) {
return itemState;
}
if(typeof itemState === typeof true) {
return(itemState && 1) || 0;
}
if(typeof itemState === 'string') {
return(['on', 'true', '1']
.includes(itemState.toLowerCase)
&& 1) || 0;
}
return itemState;
}
/**
* Gets state of item/s
* @param {String} id
*/
async state(id) {
const devices = await this.find(id);
const states = {};
const returnMap = await devices.map((device) => {
states[device.id] = CloudTuya.smap(device.data.state);
return states;
});
debug(`Return map ${JSON.stringify(returnMap)}`);
debug(`States: ${states}`);
return states;
}
/**
* Sets device with id to state
* @param {String} id Device id to set
* @param {Number/String} state State to apply
* @param {String} [cmd='turnOnOff'] Command type: modeSet, temperatureSet, turnOnOff, startStop,
* windSpeedSet, swingOpen, swingClose, brightnessSet, colorSet, colorTemperatureSet.
*/
async setState(id, state, cmd) {
const uri = `${this.uri}/skill`;
const payload = {
accessToken: this.accessToken,
devId: id,
value: CloudTuya.lmap(state),
};
debug(payload);
const data = {
header: {
name: cmd || 'turnOnOff',
namespace: 'control',
payloadVersion: 1,
},
payload,
};
const headers = {
'Content-Type': 'application/json',
};
const postConfig = {
uri,
method: 'POST',
headers,
json: data,
};
debug(postConfig);
const setProgress = await this.post(postConfig);
return(setProgress.header.code === 'SUCCESS');
}
/**
* login using tuya app email/pass to obtain token to get/set device data
*/
async login() {
const uri = `${this.uri}/auth.do`;
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
const postConfig = {
uri,
method: 'POST',
headers,
form: this.core,
};
const tokens = await this.post(postConfig);
this.tokens = JSON.parse(tokens);
this.accessToken = this.tokens.access_token;
this.tokenValidTo = (new Date()).getTime() + this.tokens.expires_in;
debug(`Token ${this.tokens} expire at ${this.tokenValidTo}`);
return this.tokens;
}
/**
* Refreshes token - untested
*/
refreshToken() {
const uri = `${this.uri}/auth.do`;
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
const postConfig = {
uri,
method: 'POST',
headers,
form: {
grant_type: 'refresh_token',
refresh_token: this.tokens.refresh_token,
},
};
const tokens = this.post(postConfig);
debug(`refresh tokens ${JSON.stringify(tokens)}`);
return this.tokens;
}
/**
* login alias
*/
async getToken() {
if(!this.tokens) return this.login();
this.refreshToken();
return this.tokens;
}
}
module.exports = CloudTuya;