forked from AdyRock/com.yolink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
277 lines (245 loc) · 6.64 KB
/
Copy pathapp.js
File metadata and controls
277 lines (245 loc) · 6.64 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
'use strict';
if (process.env.DEBUG === '1')
{
// eslint-disable-next-line node/no-unsupported-features/node-builtins, global-require
require('inspector').open(9223, '0.0.0.0', true);
}
const Homey = require('homey');
const YoLinkAPI = require('./yoLinkAPI');
const nodemailer = require('./nodemailer');
module.exports = class YoLink extends Homey.App
{
/**
* onInit is called when the app is initialized.
*/
async onInit()
{
this.yoLinkAPI = new YoLinkAPI(this);
this.homeyID = await this.homey.cloud.getHomeyId();
this.diagLog = this.diagLog || '';
if (process.env.DEBUG === '1')
{
this.homey.settings.set('debugMode', true);
}
else
{
this.homey.settings.set('debugMode', false);
}
this._triggerButtonPressed = this.homey.flow.getDeviceTriggerCard('button_pressed');
this._triggerButtonLongPressed = this.homey.flow.getDeviceTriggerCard('button_long_pressed');
this.measure_water_depth_changedTrigger = this.homey.flow.getDeviceTriggerCard('measure_water_depth_changed');
this.measure_flushes_changedTrigger = this.homey.flow.getDeviceTriggerCard('measure_flushes_changed');
this.updateLog('YoLink app has been initialized');
}
getSymData()
{
if (process.env.DEBUG === '1')
{
return this.homey.settings.get('simData');
}
return null;
}
// Convert a variable of any type (almost) to a string
varToString(source)
{
try
{
if (source === null)
{
return 'null';
}
if (source === undefined)
{
return 'undefined';
}
if (source instanceof Error)
{
const stack = typeof source.stack === 'string' ? source.stack.replace(/\\n/g, '\n') : '';
return `${source.message}\n${stack}`;
}
if (typeof (source) === 'object')
{
const getCircularReplacer = () =>
{
const seen = new WeakSet();
return (key, value) =>
{
if (typeof value === 'object' && value !== null)
{
if (seen.has(value))
{
return '';
}
seen.add(value);
}
return value;
};
};
return JSON.stringify(source, getCircularReplacer(), 2);
}
if (typeof (source) === 'string')
{
return source;
}
}
catch (err)
{
this.updateLog(`VarToString Error: ${err.message}`);
}
return String(source);
}
// Add a message to the debug log if not running in the cloud
updateLog(newMessage, errorLevel = 1)
{
if ((errorLevel === 0) || this.homey.settings.get('logEnabled'))
{
if (errorLevel === 0)
{
this.error(newMessage);
}
else
{
this.log(newMessage);
}
try
{
const nowTime = new Date(Date.now());
if (typeof this.diagLog !== 'string')
{
this.diagLog = '';
}
this.diagLog += '\r\n* ';
this.diagLog += nowTime.toJSON();
this.diagLog += '\r\n';
this.diagLog += newMessage;
this.diagLog += '\r\n';
if (this.diagLog.length > 60000)
{
this.diagLog = this.diagLog.substr(this.diagLog.length - 60000);
}
if (!this.cloudOnly)
{
this.homey.api.realtime('com.yolink.logupdated', { log: this.diagLog });
}
}
catch (err)
{
this.log(err);
}
}
}
getLog()
{
return this.diagLog;
}
clearLog()
{
this.diagLog = '';
this.homey.api.realtime('com.yolink.logupdated', { log: this.diagLog });
}
// Send the log to the developer (not applicable to Homey cloud)
async sendLog({ email = '', description = '', log = '' })
{
let tries = 5;
let error = null;
while (tries-- > 0)
{
try
{
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport(
{
host: Homey.env.MAIL_HOST, // Homey.env.MAIL_HOST,
port: 465,
ignoreTLS: false,
secure: true, // true for 465, false for other ports
auth:
{
user: Homey.env.MAIL_USER, // generated ethereal user
pass: Homey.env.MAIL_SECRET, // generated ethereal password
},
tls:
{
// do not fail on invalid certs
rejectUnauthorized: false,
},
},
);
// send mail with defined transport object
const info = await transporter.sendMail(
{
from: `"Homey User" <${Homey.env.MAIL_USER}>`, // sender address
to: Homey.env.MAIL_RECIPIENT, // list of receivers
cc: email,
subject: `YoLink log (${Homey.manifest.version})`, // Subject line
text: `${email}\n${description}\n\n${log}`, // plain text body
},
);
this.updateLog(`Message sent: ${info.messageId}`);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
// Preview only available when sending through an Ethereal account
this.log('Preview URL: ', nodemailer.getTestMessageUrl(info));
return this.homey.__('settings.logSent');
}
catch (err)
{
this.updateLog(`Send log error: ${err.message}`, 0);
error = err;
}
}
throw new Error(this.homey.__('settings.logSendFailed') + error.message);
}
async getDeviceList()
{
let deviceList = [];
const uaidList = await this.yoLinkAPI.getUAIDList();
if (uaidList && uaidList.length > 0)
{
// get the device list for all UAIDs
for (const uaid of uaidList)
{
// Append the devices to the list
const newusDevices = await this.yoLinkAPI.getDeviceList(uaid, null, 'us') || [];
deviceList = deviceList.concat(newusDevices);
// Get the list for the EU/UK zone as well but don't add duplicates
const neweuDevices = await this.yoLinkAPI.getDeviceList(uaid, null, 'eu_uk') || [];
// Filter out duplicates
for (const neweuDevice of neweuDevices)
{
if (!deviceList.find((device) => device.UID === neweuDevice.UID))
{
deviceList.push(neweuDevice);
}
}
}
}
return this.varToString(deviceList);
}
async isYoLinkLoggedIn()
{
const uaidList = await this.yoLinkAPI.getUAIDList();
return Array.isArray(uaidList) && uaidList.length > 0;
}
async loginYoLink({ UAID = '', secretKey = '', serviceZone = null } = {})
{
const normalizedUAID = typeof UAID === 'string' ? UAID.trim() : '';
const normalizedSecretKey = typeof secretKey === 'string' ? secretKey.trim() : '';
const normalizedServiceZone = typeof serviceZone === 'string' && serviceZone.trim() ? serviceZone.trim() : null;
if (!normalizedUAID || !normalizedSecretKey)
{
throw new Error('UAID and Secret Key are required');
}
const accessToken = await this.yoLinkAPI.getAccessTokenForUAID(
normalizedUAID,
normalizedSecretKey,
normalizedServiceZone || undefined,
);
if (!accessToken)
{
throw new Error('Login failed. Please check your UAID and Secret Key.');
}
this.homey.settings.set('UAID', normalizedUAID);
this.homey.settings.set('secretKey', normalizedSecretKey);
return { loggedIn: true };
}
};