-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
256 lines (214 loc) · 7.36 KB
/
test.js
File metadata and controls
256 lines (214 loc) · 7.36 KB
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
import {
TuyaOpenAPIClient,
tuya_asciiArt
} from './lib/index';
import {
TuyaLight,
TuyaSocket
} from './lib/devices/index';
import TuyaLink from '@tuyapi/link';
import { env, exit, stdin } from 'node:process';
import { promisify } from 'node:util';
import { log, error } from 'node:console';
import select, { Separator } from '@inquirer/select';
import input from '@inquirer/input';
import 'dotenv/config';
let sleep = promisify(setTimeout);
const TUYALINK_OPTIONS = {
email: env.TUYA_USER,
password: env.TUYA_PASS,
region: env.TUYA_REGION,
timezone: env.TUYA_TIMEZONE,
apiKey: env.TUYA_API_KEY,
apiSecret: env.TUYA_API_SECRET,
schema: env.TUYA_APP_SCHEMA
};
(async () => {
const tuyaClient = new TuyaOpenAPIClient();
let [prompt, answer] = [null, null];
// Graceful stop
stdin.on('keypress', (_, key) => {
if (['escape', 'q'].includes(key.name)) {
prompt.cancel()
}
});
log(tuya_asciiArt);
log("---------------------------");
await sleep(100);
try {
log('Initialize client ...');
await tuyaClient.init(
env.TUYA_API_KEY,
env.TUYA_API_SECRET,
env.TUYA_REGION
);
if (Object.keys(tuyaClient.deviceMap).length) {
log('Found ' + Object.keys(tuyaClient.deviceMap).length + ' devices');
await sleep(500);
prompt = select({
message: 'View device list JSON?',
choices: [
{ name: 'Yes', value: 'yes', description: 'Print JSON and continue' },
{ name: 'No', value: 'no', description: 'Continue' }
],
default: 'no'
});
answer = await prompt.catch(onExit);
if (answer == 'yes') {
log('Device list');
console.dir(tuyaClient.deviceMap, { depth: null });
}
}
prompt = select({
message: 'Select a device, or ...',
choices: [
...Object.values(tuyaClient.deviceMap).map(d => ({
name: d.title || `(${d.description})`,
value: d,
description: JSON.stringify(d)
})),
new Separator(),
{
name: '+ Add new device',
value: 'add',
description: JSON.stringify(
maskSensitive(
TUYALINK_OPTIONS,
['email', 'password', 'apiKey', 'apiSecret'],
0 // 1
)
)
},
new Separator(),
],
});
answer = await prompt.catch(onExit);
if (answer === 'add') {
await addDeviceProcedure();
}
else {
const tDevice = answer;
log('Is actually online?');
let isOnline = await tDevice._actuallyOnline();
if (!isOnline) {
error('Device is offline?');
exit();
}
log('... yes');
prompt = select({
message: 'Select device action',
choices: [
{ name: 'Test', value: 'test', description: 'Perform automated device tests' },
{ name: 'Rename', value: 'rename', description: 'Give new customName to device' },
{ name: 'Reset', value: 'reset', description: 'Reset factory settings' }
],
default: 'test'
});
answer = await prompt.catch(onExit);
if (answer == 'test') {
await deviceTestProcedure(tDevice);
}
else if (answer == 'rename') {
answer = await input({ message: 'Enter new device name:' });
await deviceRenameProcedure(tDevice, answer);
}
else if (answer == 'reset') {
prompt = select({
message: 'ARE YOU SURE YOU WANT TO RESET THIS DEVICE TO FACTORY SETTINGS?',
choices: [
{ name: 'Yes', value: 'yes', description: 'I said YES' },
{ name: 'No', value: 'no', description: 'Hell NO' }
],
default: 'no'
});
answer = await prompt.catch(onExit);
if (answer == 'yes') {
await deviceResetProcedure(tDevice);
}
}
}
} catch (e) {
console.error('Failed', e);
}
log("---------------------------");
})()
async function deviceTestProcedure(tDevice) {
if (tDevice instanceof TuyaLight) {
// tuyaClient.sendDeviceCommand(tDevice.id, 'switch_led', true);
log('Turn off light...');
await tDevice.turnOff();
await sleep(500);
log('Turn on light...');
await tDevice.turnOn();
await sleep(500);
log('Set light brightness...');
await tDevice.setBrightness(50);
await sleep(500);
log('Set light color mode...');
await tDevice.setWorkMode('colour');
await sleep(1000);
log('Set light color value...');
await tDevice.setColorRGB({ r: 250, g: 0, b: 0 });
await sleep(1000);
log('Check light colors...');
log(JSON.stringify( tDevice.data ));
await sleep(500);
log('Turn off light...');
await tDevice.turnOff();
}
else if (tDevice instanceof TuyaSocket) {
// tuyaClient.sendDeviceCommand(tDevice.id, 'switch_1', true);
log('Turn on socket...');
await tDevice.turnOn();
await sleep(500);
log('Wait 25 sec for reporting to register...');
await sleep(25000);
log('Re-init socket values...');
await tDevice.init();
log('Check socket power consumption...');
log(JSON.stringify( tDevice.data.reporting ));
await sleep(500);
log('Turn off socket...');
await tDevice.turnOff();
await sleep(500);
}
log('✔ Tests completed')
}
async function deviceRenameProcedure(tDevice, name) {
try {
await tDevice.rename(name);
} catch (e) {
error(`Could not reset device ${tDevice.id}`)
}
log(`✔ Device ${tDevice.id} renamed successfully to ${name}!`);
log(`❗ Changes will take effect in at ~30 seconds`);
}
async function deviceResetProcedure(tDevice) {
try {
await tDevice.destroy();
} catch (e) {
error(`Could not reset device ${tDevice.id}`)
}
log(`✔ Device ${tDevice.id} reset successfully!`);
}
async function addDeviceProcedure() {
const register = new TuyaLink.wizard(TUYALINK_OPTIONS);
await register.init();
log('Logged in successfuly');
log('Connecting to device.......')
let devices = await register.linkDevice({ ssid: env.WIFI_SSID, wifiPassword: env.WIFI_PASS, devices: 1 });
log('✔ Added device(s)')
console.log(devices);
}
function onExit() {
console.log('Bye');
exit();
}
function maskSensitive(data, sensKeys, showFirstN = 0) {
for (let key in data) {
if (sensKeys.includes(key)) {
data[key] = data[key].slice(0, showFirstN) + '***';
}
}
return data;
}