-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathyoLinkAPI.js
More file actions
1385 lines (1228 loc) · 43.3 KB
/
Copy pathyoLinkAPI.js
File metadata and controls
1385 lines (1228 loc) · 43.3 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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable operator-linebreak */
/* eslint-disable no-tabs */
'use strict';
/** *******************************************************************************
** YoLink API interface ***
** See http://doc.yosmart.com/docs/protocol/openAPIV2/en.html for details **
******************************************************************************** */
const
{
SimpleClass,
} = require('homey');
const mqtt = require('./mqtt');
// const fetch = require('node-fetch'); // Only needed for Node.js < 18
const yoLinkApi = {
cloudUrl_us: 'https://api.yosmart.com/open/yolink/',
cloudUrl_eu: 'https://api-eu.yosmart.com/open/yolink/',
mqttUrl_us: 'mqtt://api.yosmart.com',
mqttUrl_eu: 'mqtt://api-eu.yosmart.com',
localUrl: 'http://IP:1080/open/yolink/',
apiUrl: 'v2/api',
};
module.exports = class YoLinkAPI extends SimpleClass
{
constructor(app)
{
super();
this.app = app;
// this.UAIDList is used to store the list of objects {UAID: <UAID>, access_token: <accessToken>, refresh_token: <refreshToken>, expires_at: <expires_at>}
this.UAIDList = this.app.homey.settings.get('UAIDList') || [];
this.normalizeStoredUAIDList();
this.MQTTList = []; // List of {UAID, serviceZoneID, MQTTClient}
this.tokenRefreshPromises = {}; // Keyed by UAID
this.mqttSetupPromises = {}; // Keyed by UAID_serviceZoneID
this.mqttAuthFailureState = {}; // Keyed by UAID_serviceZoneID for log de-duplication
}
isMqttAuthenticationError(err)
{
if (!err)
{
return false;
}
const message = typeof err.message === 'string' ? err.message.toLowerCase() : '';
const code = typeof err.code === 'string' ? err.code.toUpperCase() : '';
return code === 'ECONNREFUSED'
|| message.includes('connection refused')
|| message.includes('not authorized')
|| message.includes('authentication failed');
}
shouldLogMqttAuthFailure(UAID, serviceZoneID, tokenPreview)
{
const zone = serviceZoneID === 'eu' ? 'eu' : 'us';
const key = `${UAID}_${zone}`;
const now = Date.now();
const current = this.mqttAuthFailureState[key];
// Suppress duplicate failures for the same token+zone within 10 seconds.
if (current && current.tokenPreview === tokenPreview && (now - current.timestampMs) < 10000)
{
return false;
}
this.mqttAuthFailureState[key] = {
timestampMs: now,
tokenPreview,
};
return true;
}
normalizeUAID(value)
{
if (typeof value !== 'string')
{
return '';
}
const trimmed = value.trim();
if (!trimmed)
{
return '';
}
const noPrefix = trimmed.replace(/^ua_/i, '');
if (/^[A-Fa-f0-9]{32}$/.test(noPrefix))
{
return `ua_${noPrefix.toUpperCase()}`;
}
return trimmed;
}
isValidNormalizedUAID(uaid)
{
return typeof uaid === 'string' && /^ua_[A-F0-9]{32}$/.test(uaid);
}
getTokenFailureReason(message)
{
const msg = typeof message === 'string' ? message.toLowerCase() : '';
if (msg.includes('client_id not existed'))
{
return 'invalid_client_id';
}
if (msg.includes('not support'))
{
return 'unsupported_client_id_format';
}
if (msg.includes('auth failed'))
{
return 'auth_failed';
}
if (msg.includes('invalid_client'))
{
return 'invalid_client';
}
if (msg.includes('invalid_grant'))
{
return 'invalid_grant';
}
if (msg.includes('html') || msg.includes('doctype') || msg.includes('temporary') || msg.includes('service unavailable') || msg.includes('timeout') || msg.includes('network') || msg.includes('fetch'))
{
return 'transport_error';
}
return 'unknown';
}
getTokenFailureHint(reason, zone, grantType)
{
switch (reason)
{
case 'invalid_client_id':
return 'YoLink did not recognize this UAID in the selected region.';
case 'unsupported_client_id_format':
return 'The UAID format is not supported by YoLink.';
case 'auth_failed':
if (grantType === 'refresh_token')
{
return `Refresh token rejected in ${zone.toUpperCase()} zone.`;
}
return `Credentials were rejected in ${zone.toUpperCase()} zone.`;
case 'invalid_client':
return 'Client authentication failed.';
case 'invalid_grant':
return 'Refresh token grant was rejected.';
case 'transport_error':
return 'YoLink token service is temporarily unavailable or returned an unexpected response. Please retry shortly.';
default:
return 'Token request failed for an unknown reason.';
}
}
getTokenFailureUserAction(reason, zone, grantType)
{
switch (reason)
{
case 'invalid_client_id':
return `Verify the UAID in the YoLink app and try again in ${zone.toUpperCase()} zone.`;
case 'unsupported_client_id_format':
return 'Paste the full UAID exactly as shown in YoLink (format: ua_ + 32 characters).';
case 'auth_failed':
if (grantType === 'refresh_token')
{
return 'Reconnect the account (re-enter UAID + Secret Key) to get a fresh token.';
}
return `Check the Secret Key and try the other region if needed (US/EU). Current region: ${zone.toUpperCase()}.`;
case 'invalid_client':
return 'Confirm UAID and Secret Key belong to the same YoLink account.';
case 'invalid_grant':
return 'Re-enter UAID and Secret Key to refresh authentication.';
case 'transport_error':
return 'Check internet connectivity and retry in a moment.';
case 'unexpected_response_format':
return 'Retry shortly; if it continues, send diagnostics.';
default:
return 'Retry and, if it fails again, send diagnostics to support.';
}
}
normalizeTokenResponse(data, UAID, serviceZoneID, grantType)
{
if (!data || typeof data !== 'object' || Array.isArray(data))
{
const preview = typeof data === 'string' ? data.substring(0, 160) : this.app.varToString(data);
return {
state: 'error',
msg: `Unexpected non-JSON token response: ${preview}`,
reason: 'unexpected_response_format',
hint: 'Token endpoint did not return expected JSON payload.',
zone: serviceZoneID,
grantType,
UAID,
};
}
if (data.state === 'error' || !data.access_token)
{
const msg = typeof data.msg === 'string' && data.msg ? data.msg : 'Unknown token error';
const reason = this.getTokenFailureReason(msg);
return {
...data,
state: 'error',
msg,
reason,
hint: this.getTokenFailureHint(reason, serviceZoneID, grantType),
zone: serviceZoneID,
grantType,
UAID,
};
}
return {
...data,
state: data.state || 'ok',
zone: serviceZoneID,
grantType,
UAID,
};
}
logTokenFailure(prefix, tokenData)
{
const details = tokenData && typeof tokenData === 'object' ? tokenData : {};
const zone = details.zone || 'us';
const reason = details.reason || this.getTokenFailureReason(details.msg);
const hint = details.hint || this.getTokenFailureHint(reason, zone, details.grantType || 'client_credentials');
const action = this.normalizeUserAction(this.getTokenFailureUserAction(reason, zone, details.grantType || 'client_credentials'));
const msg = details.msg || 'Unknown error';
this.app.updateLog(`${prefix}. What you can do: ${action} | diag: zone=${zone} grant=${details.grantType || 'unknown'} reason=${reason} msg=${msg} hint=${hint}`, 0);
}
normalizeUserAction(action)
{
const actionText = typeof action === 'string' ? action.trim() : '';
if (!actionText)
{
return 'Please retry and, if it fails again, send diagnostics to support.';
}
if (/^please\b/i.test(actionText))
{
return actionText;
}
if (/^verify\b|^paste\b|^check\b|^confirm\b|^re-enter\b|^reconnect\b|^retry\b|^connect\b|^try\b/i.test(actionText))
{
return `Please ${actionText}`;
}
return `Please ${actionText.charAt(0).toLowerCase()}${actionText.slice(1)}`;
}
logUserFixableFailure(prefix, action, diag = {})
{
const normalizedAction = this.normalizeUserAction(action);
const diagEntries = Object.entries(diag)
.filter(([, value]) => value !== null && value !== undefined && value !== '')
.map(([key, value]) => `${key}=${String(value).replace(/\s+/g, ' ').trim()}`);
const diagSuffix = diagEntries.length > 0 ? ` | diag: ${diagEntries.join(' ')}` : '';
this.app.updateLog(`${prefix}. What you can do: ${normalizedAction}${diagSuffix}`, 0);
}
normalizeStoredUAIDList()
{
if (!Array.isArray(this.UAIDList) || this.UAIDList.length === 0)
{
this.UAIDList = [];
return;
}
const normalizedList = [];
const seenUAID = new Set();
for (const entry of this.UAIDList)
{
if (!entry || typeof entry !== 'object')
{
continue;
}
const normalizedUAID = this.normalizeUAID(entry.UAID);
if (!normalizedUAID || !this.isValidNormalizedUAID(normalizedUAID) || seenUAID.has(normalizedUAID))
{
continue;
}
seenUAID.add(normalizedUAID);
normalizedList.push({
...entry,
UAID: normalizedUAID,
serviceZoneID: entry.serviceZoneID === 'eu' ? 'eu' : 'us',
});
}
if (normalizedList.length !== this.UAIDList.length)
{
this.app.updateLog(`Normalized UAIDList from ${this.UAIDList.length} to ${normalizedList.length} entries`);
}
this.UAIDList = normalizedList;
this.app.homey.settings.set('UAIDList', this.UAIDList);
}
async getUAIDList()
{
// Return the array of UAIDs
return this.UAIDList.map((item) => item.UAID);
}
formatDateForLog(value)
{
const date = new Date(value);
return Number.isFinite(date.getTime()) ? date.toISOString() : `invalid date (${String(value)})`;
}
safeJsonStringify(value)
{
try
{
return JSON.stringify(value);
}
catch (error)
{
return `unserializable value: ${error.message}`;
}
}
getServiceZoneID(serviceZone)
{
if (typeof serviceZone !== 'string' || serviceZone.length < 2)
{
return 'us';
}
return serviceZone.substring(0, 2).toLowerCase();
}
getZoneAttemptOrder(primaryZoneID, fallbackZoneID)
{
const primary = primaryZoneID === 'eu' ? 'eu' : 'us';
const fallback = fallbackZoneID === 'eu' ? 'eu' : 'us';
if (primary === fallback)
{
return [primary];
}
return [primary, fallback];
}
getSafeExpiresAt(expiresInSeconds, UAID)
{
const fallbackSeconds = 300;
const maxSeconds = 30 * 24 * 60 * 60;
const parsed = Number(expiresInSeconds);
if (!Number.isFinite(parsed) || parsed <= 0)
{
this.app.updateLog(`Invalid expires_in for UAID ${UAID}: ${this.app.varToString(expiresInSeconds)}. Using fallback ${fallbackSeconds}s`, 0);
return Date.now() + (fallbackSeconds * 1000);
}
const safeSeconds = Math.min(parsed, maxSeconds);
return Date.now() + (safeSeconds * 1000);
}
isAccessTokenExpired(expiresAt)
{
const parsed = Number(expiresAt);
if (!Number.isFinite(parsed))
{
return true;
}
// Refresh slightly early to avoid edge-case expiry during a request.
const refreshSkewMs = 30 * 1000;
return parsed <= (Date.now() + refreshSkewMs);
}
async getAccessTokenForUAID(UAID, SecretKey, serviceZone)
{
const normalizedUAID = this.normalizeUAID(UAID);
if (!normalizedUAID)
{
this.app.updateLog('Token request rejected: UAID is empty. What you can do: Please enter the full UAID from YoLink and try again. | diag: reason=missing_uaid', 0);
throw new Error('Invalid UAID');
}
if (!this.isValidNormalizedUAID(normalizedUAID))
{
this.app.updateLog(`Token request rejected for UAID ${normalizedUAID}. What you can do: Please use the full UAID from YoLink (ua_ + 32 characters). | diag: reason=invalid_uaid_format expected=ua_<32 hex>`, 0);
throw new Error(`Invalid UAID format: ${normalizedUAID}`);
}
if (normalizedUAID !== UAID)
{
this.app.updateLog(`Normalized UAID ${UAID} -> ${normalizedUAID}`);
}
const requestedServiceZoneID = this.getServiceZoneID(serviceZone);
// Return the accessToken for the given UAID
let entry = this.UAIDList.find((item) => item.UAID === normalizedUAID);
const effectiveServiceZoneID = entry && !serviceZone
? (entry.serviceZoneID || 'us')
: requestedServiceZoneID;
if (entry && this.isAccessTokenExpired(entry.expires_at))
{
const refreshPromise = this.tokenRefreshPromises[normalizedUAID] || (async () =>
{
this.app.updateLog(`Access token for UAID ${normalizedUAID} has expired, attempting refresh`);
const currentEntry = this.UAIDList.find((item) => item.UAID === normalizedUAID);
if (!currentEntry)
{
throw new Error(`No token entry found for UAID ${normalizedUAID} during refresh`);
}
const preferredRefreshZone = currentEntry.serviceZoneID === 'eu' ? 'eu' : 'us';
const requestedRefreshZone = effectiveServiceZoneID === 'eu' ? 'eu' : 'us';
const refreshZoneOrder = this.getZoneAttemptOrder(preferredRefreshZone, requestedRefreshZone);
let refreshZone = refreshZoneOrder[0];
let newTokenData = null;
for (let index = 0; index < refreshZoneOrder.length; index += 1)
{
const attemptZone = refreshZoneOrder[index];
if (index > 0)
{
this.app.updateLog(`Retrying refresh token for UAID ${normalizedUAID} in alternate zone ${attemptZone}`);
}
const attemptData = await this.obtainAccessTokenWithRefreshToken(currentEntry.UAID, currentEntry.refresh_token, attemptZone);
if (attemptData && attemptData.state !== 'error' && attemptData.access_token)
{
newTokenData = attemptData;
refreshZone = attemptZone;
if (index > 0)
{
this.app.updateLog(`Refresh token succeeded for UAID ${normalizedUAID} after zone switch to ${attemptZone}`, 0);
}
break;
}
newTokenData = attemptData;
if (index < refreshZoneOrder.length - 1)
{
this.logTokenFailure(`Refresh token failed for UAID ${normalizedUAID}`, attemptData);
}
}
if (!newTokenData || newTokenData.state === 'error' || !newTokenData.access_token)
{
this.logTokenFailure(`Failed to refresh access token for UAID ${normalizedUAID}`, newTokenData);
throw new Error(`Failed to refresh access token for UAID ${normalizedUAID}: ${newTokenData && newTokenData.msg ? newTokenData.msg : 'Unknown error'}`);
}
this.app.updateLog(`New token data for UAID ${normalizedUAID}: ${this.app.varToString(newTokenData)}`);
// Update the entry in the UAIDList
currentEntry.access_token = newTokenData.access_token;
currentEntry.refresh_token = newTokenData.refresh_token;
currentEntry.expires_at = this.getSafeExpiresAt(newTokenData.expires_in, normalizedUAID);
currentEntry.serviceZoneID = refreshZone;
this.app.updateLog(`Obtained new access token for UAID ${normalizedUAID}, expires at ${this.formatDateForLog(currentEntry.expires_at)}`, 0);
this.app.homey.settings.set('UAIDList', this.UAIDList);
this.refreshMQTTClientsForUAID(normalizedUAID);
})();
if (!this.tokenRefreshPromises[normalizedUAID])
{
this.tokenRefreshPromises[normalizedUAID] = refreshPromise;
}
try
{
await refreshPromise;
}
finally
{
if (this.tokenRefreshPromises[normalizedUAID] === refreshPromise)
{
delete this.tokenRefreshPromises[normalizedUAID];
}
}
entry = this.UAIDList.find((item) => item.UAID === normalizedUAID);
}
else if (!entry && SecretKey)
{
// No entry found for this UAID, so obtain a new access token using the secret key
this.app.updateLog(`No token cache entry found for UAID ${normalizedUAID}, requesting a new token`);
let resolvedServiceZoneID = effectiveServiceZoneID;
let newTokenData = await this.obtainAccessTokenWithSecret(normalizedUAID, SecretKey, resolvedServiceZoneID);
if (newTokenData && newTokenData.state === 'error' && !serviceZone)
{
const alternateZone = effectiveServiceZoneID === 'eu' ? 'us' : 'eu';
this.logTokenFailure(`Initial token request failed for UAID ${normalizedUAID}`, newTokenData);
this.app.updateLog(`Retrying initial token request for UAID ${normalizedUAID} in alternate zone ${alternateZone}`);
const retryTokenData = await this.obtainAccessTokenWithSecret(normalizedUAID, SecretKey, alternateZone);
if (retryTokenData && retryTokenData.state !== 'error' && retryTokenData.access_token)
{
newTokenData = retryTokenData;
resolvedServiceZoneID = alternateZone;
this.app.updateLog(`Initial token request succeeded for UAID ${normalizedUAID} after zone switch to ${alternateZone}`);
}
}
if (newTokenData.state === 'error')
{
this.logTokenFailure(`Failed to obtain access token for UAID ${normalizedUAID}`, newTokenData);
// return null;
throw new Error(`Failed to obtain access token for UAID ${normalizedUAID}: ${newTokenData.msg}`);
}
this.app.updateLog(`New token data for UAID ${normalizedUAID}: ${this.app.varToString(newTokenData)}`);
this.app.updateLog(`Obtained new access token for UAID ${normalizedUAID}, expires at ${this.formatDateForLog(Date.now() + (newTokenData.expires_in * 1000))}`, 0);
// Add the new entry to the UAIDList
entry = {
UAID: normalizedUAID,
access_token: newTokenData.access_token,
refresh_token: newTokenData.refresh_token,
expires_at: this.getSafeExpiresAt(newTokenData.expires_in, normalizedUAID),
serviceZoneID: resolvedServiceZoneID,
};
this.UAIDList.push(entry);
this.app.homey.settings.set('UAIDList', this.UAIDList);
}
// if (entry && !this.MQTTClient)
// {
// try
// {
// // Setup the MQTT client
// const brokerConfig = {
// UAID,
// url: 'mqtt://api-eu.yosmart.com',
// port: 8003,
// username: entry.access_token,
// password: '',
// };
// this.MQTTClient = this.setupMQTTClient(brokerConfig);
// }
// catch (err)
// {
// this.app.updateLog(`Failed to setup MQTT client for UAID ${UAID}: ${err.message}`, 0);
// }
// }
return entry ? entry.access_token : null;
}
refreshMQTTClientsForUAID(UAID)
{
if (!this.MQTTList || this.MQTTList.length === 0)
{
return;
}
const mqttConnections = this.MQTTList.filter((item) => item.UAID === UAID && item.MQTTClient);
for (const connection of mqttConnections)
{
const accessTokenEntry = this.UAIDList.find((item) => item.UAID === UAID);
if (!accessTokenEntry || !accessTokenEntry.access_token)
{
continue;
}
const { serviceZoneID } = connection;
const brokerConfig = {
UAID,
url: serviceZoneID === 'eu' ? yoLinkApi.mqttUrl_eu : yoLinkApi.mqttUrl_us,
port: 8003,
username: accessTokenEntry.access_token,
password: '',
serviceZoneID,
};
this.app.updateLog(`Refreshing MQTT client for UAID ${UAID} and serviceZoneID ${serviceZoneID} after token refresh`);
connection.MQTTClient.end(true);
this.setupMQTTClient(brokerConfig).then((mqttConnection) =>
{
if (!mqttConnection)
{
return;
}
const index = this.MQTTList.findIndex((item) => item.UAID === UAID && item.serviceZoneID === serviceZoneID);
if (index >= 0)
{
this.MQTTList[index] = mqttConnection;
}
else
{
this.MQTTList.push(mqttConnection);
}
}).catch((error) =>
{
this.app.updateLog(`Failed to refresh MQTT client for UAID ${UAID} and serviceZoneID ${serviceZoneID}: ${error.message}`, 0);
});
}
}
invalidateAccessTokenForUAID(UAID, serviceZoneID)
{
const normalizedUAID = this.normalizeUAID(UAID);
const normalizedServiceZoneID = serviceZoneID === 'eu' ? 'eu' : 'us';
const entry = this.UAIDList.find((item) => item.UAID === normalizedUAID);
if (!entry)
{
return false;
}
entry.expires_at = 0;
entry.serviceZoneID = normalizedServiceZoneID;
this.app.homey.settings.set('UAIDList', this.UAIDList);
this.app.updateLog(`Invalidated cached access token for UAID ${normalizedUAID} in ${normalizedServiceZoneID.toUpperCase()} zone after MQTT authentication failure`, 0);
return true;
}
getTokenURL(serviceZoneID)
{
if (serviceZoneID === 'eu')
{
return `${yoLinkApi.cloudUrl_eu}token`;
}
return `${yoLinkApi.cloudUrl_us}token`;
}
async request(method = 'GET', url, body = null, headers = {})
{
this.app.updateLog(`API request: ${method} ${url} ${this.safeJsonStringify(body)}`);
const options = {
method,
headers: {
'Content-Type': 'application/json',
...headers,
},
body: body === null ? null : this.safeJsonStringify(body),
};
try
{
const response = await fetch(url, options);
const data = await response.json();
this.app.updateLog(`API response: ${JSON.stringify(data)}`);
return data;
}
catch (error)
{
this.logUserFixableFailure(
'Cloud request failed',
'Check internet connectivity and retry in a moment.',
{ method, url, reason: 'request_error', msg: error.message },
);
return { state: 'error', msg: error.message };
}
}
// Obtain access token using UAID and secretKey
async obtainAccessTokenWithSecret(UAID, secretKey, serviceZoneID = 'us')
{
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
const body = `grant_type=client_credentials&client_id=${encodeURIComponent(UAID)}&client_secret=${encodeURIComponent(secretKey)}`;
const init = {
method: 'POST',
headers,
body,
};
try
{
this.app.updateLog(`Token request start | zone=${serviceZoneID} | grant=client_credentials | UAID=${UAID}`);
const response = await fetch(this.getTokenURL(serviceZoneID), init);
this.app.updateLog(`Token request response | zone=${serviceZoneID} | grant=client_credentials | status=${response.status}`);
const mediaType = response.headers.get('content-type');
let data;
if (mediaType && mediaType.includes('json'))
{
data = await response.json();
}
else
{
data = await response.text();
}
const normalizedData = this.normalizeTokenResponse(data, UAID, serviceZoneID, 'client_credentials');
if (normalizedData.state === 'error')
{
this.logTokenFailure(`Token endpoint rejected client_credentials for UAID ${UAID}`, normalizedData);
}
return normalizedData;
}
catch (error)
{
const errorData = this.normalizeTokenResponse({ state: 'error', msg: error.message }, UAID, serviceZoneID, 'client_credentials');
this.logTokenFailure(`Failed to obtain access token with secret for UAID ${UAID}`, errorData);
return errorData;
}
}
async obtainAccessTokenWithRefreshToken(UAID, refreshToken, serviceZoneID = 'us')
{
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
const body = `grant_type=refresh_token&client_id=${encodeURIComponent(UAID)}&refresh_token=${encodeURIComponent(refreshToken)}`;
const init = {
method: 'POST',
headers,
body,
};
try
{
this.app.updateLog(`Token request start | zone=${serviceZoneID} | grant=refresh_token | UAID=${UAID}`);
const response = await fetch(this.getTokenURL(serviceZoneID), init);
this.app.updateLog(`Token request response | zone=${serviceZoneID} | grant=refresh_token | status=${response.status}`);
const mediaType = response.headers.get('content-type');
let data;
if (mediaType && mediaType.includes('json'))
{
data = await response.json();
}
else
{
data = await response.text();
}
const normalizedData = this.normalizeTokenResponse(data, UAID, serviceZoneID, 'refresh_token');
if (normalizedData.state === 'error')
{
this.logTokenFailure(`Token endpoint rejected refresh_token for UAID ${UAID}`, normalizedData);
}
return normalizedData;
}
catch (error)
{
const errorData = this.normalizeTokenResponse({ state: 'error', msg: error.message }, UAID, serviceZoneID, 'refresh_token');
this.logTokenFailure(`Failed to obtain access token with refresh token for UAID ${UAID}`, errorData);
return errorData;
}
}
async getDeviceList(UAID, SecretKey, serviceZone)
{
// Get the access token for the UAID. The SecretKey is only needed if there is no valid access token yet
let accessToken = null;
try
{
accessToken = await this.getAccessTokenForUAID(UAID, SecretKey, serviceZone);
}
catch (error)
{
this.logUserFixableFailure(
`Unable to list devices for UAID ${UAID}`,
'Reconnect the account by re-entering UAID and Secret Key, then try again.',
{ operation: 'getDeviceList', reason: 'access_token_error', msg: error.message, zone: this.getServiceZoneID(serviceZone) },
);
return null;
}
if (!accessToken)
{
this.logUserFixableFailure(
`Unable to list devices for UAID ${UAID}`,
'Reconnect the account by re-entering UAID and Secret Key, then try again.',
{ operation: 'getDeviceList', reason: 'missing_access_token', zone: this.getServiceZoneID(serviceZone) },
);
return null;
}
const headers = {
Authorization: `Bearer ${accessToken}`,
};
const body = {
method: 'Home.getDeviceList',
time: Math.floor(Date.now() / 1000),
};
const serviceZoneID = this.getServiceZoneID(serviceZone);
const response = await this.request('POST', this.getZoneURL(serviceZoneID), body, headers);
if (response && response.desc === 'Success')
{
if (response && response.data && response.data.devices && response.data.devices.length > 0)
{
this.lastDeviceList = response.data.devices;
return response.data.devices;
}
throw new Error(`No devices found for UAID ${UAID}`);
}
else if (response)
{
this.logUserFixableFailure(
`Device list request failed for UAID ${UAID}`,
'Check that the correct region is selected (US/EU) and retry.',
{ operation: 'getDeviceList', zone: serviceZoneID, desc: response.desc },
);
throw new Error(`Failed to obtain device list for UAID ${UAID}: ${response.desc}`);
}
throw new Error(`Failed to obtain device list for UAID ${UAID}`);
}
getZoneURL(serviceZoneID)
{
if (serviceZoneID === 'eu')
{
return `${yoLinkApi.cloudUrl_eu}${yoLinkApi.apiUrl}`;
}
return `${yoLinkApi.cloudUrl_us}${yoLinkApi.apiUrl}`;
}
async getDeviceStatus(UAID, type, deviceId, deviceToken, serviceZone)
{
let accessToken = null;
try
{
accessToken = await this.getAccessTokenForUAID(UAID, null, serviceZone);
}
catch (error)
{
this.logUserFixableFailure(
`Unable to fetch device status for UAID ${UAID}`,
'Reconnect the account by re-entering UAID and Secret Key, then try again.',
{ operation: 'getDeviceStatus', reason: 'access_token_error', msg: error.message, zone: this.getServiceZoneID(serviceZone) },
);
return null;
}
if (!accessToken)
{
this.logUserFixableFailure(
`Unable to fetch device status for UAID ${UAID}`,
'Reconnect the account by re-entering UAID and Secret Key, then try again.',
{ operation: 'getDeviceStatus', reason: 'missing_access_token', zone: this.getServiceZoneID(serviceZone) },
);
return null;
}
const headers = {
Authorization: `Bearer ${accessToken}`,
};
const body = {
method: `${type}.getState`,
time: Math.floor(Date.now() / 1000),
targetDevice: deviceId,
token: deviceToken,
params: {},
};
// Get the service zone ID, which is the first two characters of the serviceZone string
const serviceZoneID = this.getServiceZoneID(serviceZone);
const url = this.getZoneURL(serviceZoneID);
const setupKey = `${UAID}_${serviceZoneID}`;
while (this.mqttSetupPromises[setupKey])
{
this.app.updateLog(`Waiting for MQTT client setup to complete for UAID ${UAID} and serviceZoneID ${serviceZoneID}`);
await this.mqttSetupPromises[setupKey];
}
const setupPromise = (async () =>
{
const retryKey = `${UAID}_${serviceZoneID}`;
if (this.mqttRetryTimers && this.mqttRetryTimers[retryKey])
{
// A retry timer exists for this UAID/serviceZoneID, so don't try setting up MQTT client now
this.app.updateLog(`Skipping wait for MQTT client setup for UAID ${UAID} and serviceZoneID ${serviceZoneID} as a retry timer exists`);
return;
}
// Ensure an MQTT client is setup for this UAID and serviceZoneID
const entry = this.MQTTList.find((item) => (item.UAID === UAID) && (item.serviceZoneID === serviceZoneID));
if (!entry)
{
try
{
this.app.updateLog(`MQTT client for UAID ${UAID} and serviceZoneID ${serviceZoneID} not found, setting up now`);
// Setup the MQTT client
let mqttURL;
if (serviceZoneID === 'eu')
{
mqttURL = yoLinkApi.mqttUrl_eu;
}
else
{
mqttURL = yoLinkApi.mqttUrl_us;
}
const brokerConfig = {
UAID,
url: mqttURL,
port: 8003,
username: accessToken,
password: '',
serviceZoneID,
};
const MQTTConnection = await this.setupMQTTClient(brokerConfig);
if (MQTTConnection)
{
this.MQTTList.push(MQTTConnection);
this.app.updateLog(`MQTT client setup complete for UAID ${UAID}. Number of MQTT clients: ${this.MQTTList.length}`);
}
}
catch (err)
{
this.logUserFixableFailure(
`Failed to setup MQTT for UAID ${UAID}`,
'Check that the selected region matches your YoLink account, then retry.',
{ operation: 'mqtt_setup', zone: serviceZoneID, msg: err.message },
);
}
}
else
{
this.app.updateLog(`MQTT client already setup for UAID ${UAID} and serviceZoneID ${serviceZoneID}`);
}
})();
this.mqttSetupPromises[setupKey] = setupPromise;
try
{
await setupPromise;
}
finally
{
if (this.mqttSetupPromises[setupKey] === setupPromise)
{
delete this.mqttSetupPromises[setupKey];
}
}
return this.request('POST', url, body, headers);
}
async controlDevice(UAID, deviceId, deviceToken, serviceZone, command, params = {})
{
let accessToken = null;
try
{
accessToken = await this.getAccessTokenForUAID(UAID, null, serviceZone);
}
catch (error)
{
this.logUserFixableFailure(
`Unable to control device for UAID ${UAID}`,
'Reconnect the account by re-entering UAID and Secret Key, then try again.',
{ operation: 'controlDevice', command, reason: 'access_token_error', msg: error.message, zone: this.getServiceZoneID(serviceZone) },
);
return { desc: `Failed to obtain access token for UAID ${UAID}` };
}
if (!accessToken)
{
this.logUserFixableFailure(
`Unable to control device for UAID ${UAID}`,
'Reconnect the account by re-entering UAID and Secret Key, then try again.',
{ operation: 'controlDevice', command, reason: 'missing_access_token', zone: this.getServiceZoneID(serviceZone) },
);
return { desc: `Failed to obtain access token for UAID ${UAID}` };
}
const headers = {
Authorization: `Bearer ${accessToken}`,
};
const body = {
method: command,
time: Math.floor(Date.now() / 1000),
targetDevice: deviceId,
token: deviceToken,
params,
};
// Get the service zone ID, which is the first two characters of the serviceZone string
const serviceZoneID = this.getServiceZoneID(serviceZone);
const url = this.getZoneURL(serviceZoneID);
return this.request('POST', url, body, headers);
}
async getHomeInfo(UAID, serviceZone)
{
let accessToken = null;
try