homebridge-tuya-plus 3.14.0-dev.4 → 3.14.0-dev.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish-dev.yml +298 -31
- package/AGENTS.md +162 -0
- package/CLAUDE.md +1 -0
- package/Changelog.md +16 -3
- package/Readme.MD +8 -32
- package/config.schema.json +63 -78
- package/index.js +599 -358
- package/lib/AirPurifierAccessory.js +1 -1
- package/lib/BaseAccessory.js +54 -17
- package/lib/ConvectorAccessory.js +1 -1
- package/lib/CustomMultiOutletAccessory.js +2 -1
- package/lib/DoorbellAccessory.js +9 -16
- package/lib/GarageDoorAccessory.js +1 -1
- package/lib/IrrigationSystemAccessory.js +93 -114
- package/lib/MultiOutletAccessory.js +3 -2
- package/lib/OilDiffuserAccessory.js +10 -8
- package/lib/RGBTWLightAccessory.js +13 -11
- package/lib/RGBTWOutletAccessory.js +11 -9
- package/lib/SimpleBlindsAccessory.js +5 -5
- package/lib/SimpleDimmer2Accessory.js +1 -1
- package/lib/SimpleDimmerAccessory.js +10 -6
- package/lib/SimpleGarageDoorAccessory.js +78 -24
- package/lib/SimpleHeaterAccessory.js +4 -4
- package/lib/SimpleLightAccessory.js +1 -1
- package/lib/SwitchAccessory.js +3 -2
- package/lib/TWLightAccessory.js +2 -2
- package/lib/TuyaAccessory.js +75 -42
- package/lib/TuyaCloudApi.js +90 -4
- package/lib/TuyaCloudDevice.js +204 -25
- package/lib/TuyaCloudMessaging.js +28 -41
- package/lib/TuyaDevice.js +269 -0
- package/lib/TuyaDiscovery.js +25 -9
- package/lib/ValveAccessory.js +16 -12
- package/lib/VerticalBlindsWithTilt.js +27 -25
- package/lib/WledDimmerAccessory.js +46 -81
- package/package.json +5 -6
- package/scripts/cleanup-pr-tags.js +122 -0
- package/test/BaseAccessory.test.js +94 -15
- package/test/IrrigationSystemAccessory.test.js +122 -68
- package/test/MultiOutletAccessory.test.js +18 -3
- package/test/RGBTWLightAccessory.test.js +3 -3
- package/test/SimpleFanLightAccessory.test.js +3 -3
- package/test/SimpleGarageDoorAccessory.test.js +63 -9
- package/test/TuyaAccessory.protocol.test.js +76 -3
- package/test/TuyaCloudApi.test.js +80 -0
- package/test/TuyaCloudDevice.test.js +253 -1
- package/test/TuyaCloudMessaging.test.js +24 -5
- package/test/TuyaDevice.test.js +266 -0
- package/test/getCategory.test.js +1 -0
- package/test/index.test.js +271 -0
- package/test/support/mocks.js +13 -0
- package/wiki/Supported-Device-Types.md +48 -30
- package/wiki/Tuya-Cloud-Setup.md +24 -113
package/lib/TuyaCloudDevice.js
CHANGED
|
@@ -39,17 +39,35 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
39
39
|
this.api = props.cloudApi;
|
|
40
40
|
this.messaging = props.messaging || null; // shared realtime stream
|
|
41
41
|
|
|
42
|
+
// Lets the cloud backend ask its parent TuyaDevice whether the SAME device
|
|
43
|
+
// is currently reachable over the LAN. A cloud-fallback failure is harmless
|
|
44
|
+
// when the LAN is up and worth surfacing when it isn't, so the failure log
|
|
45
|
+
// adapts to it. Null when used standalone (no LAN sibling).
|
|
46
|
+
this.isLanConnected = typeof props.isLanConnected === 'function' ? props.isLanConnected : null;
|
|
47
|
+
|
|
42
48
|
// Keep a plain config object on `context`, mirroring TuyaAccessory, but
|
|
43
49
|
// without the live helper objects we were handed.
|
|
44
50
|
this.context = {...props};
|
|
45
51
|
delete this.context.cloudApi;
|
|
46
52
|
delete this.context.messaging;
|
|
47
53
|
delete this.context.log;
|
|
54
|
+
delete this.context.isLanConnected;
|
|
48
55
|
|
|
49
56
|
this.state = {};
|
|
50
57
|
this.connected = false;
|
|
51
58
|
this._stopped = false;
|
|
52
59
|
this._retryTimer = null;
|
|
60
|
+
this._retryDelay = 0; // current connect-retry backoff (ms); grows on repeated failure
|
|
61
|
+
this._lastConnectError = null; // last surfaced connect error, so identical repeats stay quiet
|
|
62
|
+
|
|
63
|
+
// Bidirectional data-point maps, learned from the device's thing-shadow on
|
|
64
|
+
// connect. They let this cloud transport (and the LAN+cloud TuyaDevice that
|
|
65
|
+
// may wrap it) translate between the LAN's numeric data-point ids and the
|
|
66
|
+
// cloud's string codes. Empty until the shadow is read; empty means
|
|
67
|
+
// "code-only" (no numeric bridge), which is still fully functional for a
|
|
68
|
+
// cloud-configured accessory.
|
|
69
|
+
this.codeByDpId = {}; // '20' -> 'switch_led'
|
|
70
|
+
this.dpIdByCode = {}; // 'switch_led' -> '20'
|
|
53
71
|
|
|
54
72
|
if (props.connect !== false) this._connect();
|
|
55
73
|
}
|
|
@@ -63,12 +81,33 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
63
81
|
return this.log.error(`${this.context.name}: Tuya Cloud is not configured (missing accessId/accessKey).`);
|
|
64
82
|
}
|
|
65
83
|
|
|
84
|
+
// First connect only: stagger the initial read so a large install doesn't
|
|
85
|
+
// fire every device's OpenAPI call in the same instant (rate limits). The
|
|
86
|
+
// platform hands each device an increasing cloudStartDelay.
|
|
87
|
+
if (!this._staggered) {
|
|
88
|
+
this._staggered = true;
|
|
89
|
+
const delay = parseInt(this.context.cloudStartDelay) || 0;
|
|
90
|
+
if (delay > 0) {
|
|
91
|
+
await new Promise(resolve => { const t = setTimeout(resolve, delay); if (t.unref) t.unref(); });
|
|
92
|
+
if (this._stopped) return;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
66
96
|
try {
|
|
67
|
-
const
|
|
68
|
-
this.
|
|
69
|
-
this.
|
|
97
|
+
const props = await this._readInitialProperties();
|
|
98
|
+
this._learnDpMap(props);
|
|
99
|
+
this.state = this._propsToState(props);
|
|
100
|
+
this.connected = await this._readOnline();
|
|
101
|
+
|
|
102
|
+
this._logDiscoveredCodes(props);
|
|
70
103
|
|
|
71
|
-
|
|
104
|
+
// Connected: announce recovery from any earlier failure once, and
|
|
105
|
+
// reset the retry backoff.
|
|
106
|
+
if (this._lastConnectError) {
|
|
107
|
+
this.log.info(`${this.context.name}: Tuya Cloud connection restored.`);
|
|
108
|
+
this._lastConnectError = null;
|
|
109
|
+
}
|
|
110
|
+
this._retryDelay = 0;
|
|
72
111
|
|
|
73
112
|
this.emit('connect');
|
|
74
113
|
// Accessories register their characteristics off the first 'change'.
|
|
@@ -76,12 +115,74 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
76
115
|
|
|
77
116
|
this._subscribeRealtime();
|
|
78
117
|
} catch (ex) {
|
|
79
|
-
this.
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
118
|
+
this._onConnectFailure(ex);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// A failed connect is retried, but the cause is frequently permanent — the
|
|
123
|
+
// cloud project can't see this device (permission denied / "no space"), the
|
|
124
|
+
// datacenter region is wrong, or the device isn't linked to the account — and
|
|
125
|
+
// won't clear without the user changing their Tuya project. Since PR #71 the
|
|
126
|
+
// cloud backs *every* device as a fallback, so a LAN-only device whose cloud
|
|
127
|
+
// project lacks permission would otherwise log an error every 30s forever.
|
|
128
|
+
// Two things keep that out of the log: a given message is surfaced once and then
|
|
129
|
+
// suppressed to debug until it changes (or the device connects), and the retry
|
|
130
|
+
// interval backs off (30s → 30m cap) instead of hammering the OpenAPI.
|
|
131
|
+
_onConnectFailure(ex) {
|
|
132
|
+
const message = ex && ex.message ? ex.message : String(ex);
|
|
133
|
+
const {level, text} = this._describeConnectFailure(message);
|
|
134
|
+
|
|
135
|
+
// The full (level + wording) is what the dedup tracks, not just the raw
|
|
136
|
+
// message: it means a device that flips from "reachable over the LAN"
|
|
137
|
+
// (harmless, debug) to "not reachable over the LAN either" (warn) re-surfaces
|
|
138
|
+
// the change, while an unchanged situation stays quiet.
|
|
139
|
+
if (text !== this._lastConnectError) {
|
|
140
|
+
this.log[level](text);
|
|
141
|
+
this._lastConnectError = text;
|
|
142
|
+
} else {
|
|
143
|
+
this.log.debug(`${this.context.name}: Tuya Cloud connection still failing: ${message}`);
|
|
84
144
|
}
|
|
145
|
+
|
|
146
|
+
if (this._stopped) return;
|
|
147
|
+
// Exponential backoff: 30s after the first failure, doubling to a 30m cap.
|
|
148
|
+
this._retryDelay = Math.min(this._retryDelay ? this._retryDelay * 2 : 30000, 1800000);
|
|
149
|
+
this._retryTimer = setTimeout(() => this._connect(), this._retryDelay);
|
|
150
|
+
if (this._retryTimer && this._retryTimer.unref) this._retryTimer.unref();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Pick the log level and wording for a connect failure from what we know about
|
|
154
|
+
// the device: whether the cloud is merely a fallback (the device has a local
|
|
155
|
+
// key) and, if so, whether that LAN path is reachable right now.
|
|
156
|
+
_describeConnectFailure(message) {
|
|
157
|
+
const lanFallback = !!this.context.key;
|
|
158
|
+
const lanReachable = lanFallback && !!(this.isLanConnected && this.isLanConnected());
|
|
159
|
+
|
|
160
|
+
// "permission deny" (1106) is specifically a visibility problem: the cloud
|
|
161
|
+
// project can't see this device. A device that has been offline for a long
|
|
162
|
+
// time is a prime candidate for having been removed/unbound/reset, which
|
|
163
|
+
// produces exactly this — so point at that, but only for this error (a
|
|
164
|
+
// timeout or token failure is unrelated).
|
|
165
|
+
const unbound = /permission deny|\b1106\b/i.test(message)
|
|
166
|
+
? ' Note: a device left offline for a long time can be removed or unbound from the account (e.g. reset or re-paired), which also produces this "permission deny".'
|
|
167
|
+
: '';
|
|
168
|
+
|
|
169
|
+
let level, hint;
|
|
170
|
+
if (lanReachable) {
|
|
171
|
+
// Confirmed reachable over the LAN, so the cloud fallback we couldn't
|
|
172
|
+
// reach isn't needed. Keep it out of the way at debug.
|
|
173
|
+
level = 'debug';
|
|
174
|
+
hint = ' The device is reachable over the LAN, so only the (unused) cloud fallback is affected — harmless.';
|
|
175
|
+
} else if (lanFallback) {
|
|
176
|
+
// LAN-capable but not connected right now, so the cloud is currently the
|
|
177
|
+
// only path and the device may be unresponsive in HomeKit.
|
|
178
|
+
level = 'warn';
|
|
179
|
+
hint = ` The cloud is only a fallback, but the device isn't reachable over the LAN right now either, so it may show as unresponsive in HomeKit. Check that it is linked to this cloud project (matching account/home and datacenter region).${unbound}`;
|
|
180
|
+
} else {
|
|
181
|
+
level = 'error';
|
|
182
|
+
hint = ` This device is cloud-only, so it stays unreachable until this clears — check that it is linked to the cloud project (matching account/home and datacenter region).${unbound}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return {level, text: `${this.context.name}: Tuya Cloud connection failed: ${message}.${hint}`};
|
|
85
186
|
}
|
|
86
187
|
|
|
87
188
|
/* ------------------------------------------------------------------ *
|
|
@@ -102,6 +203,11 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
102
203
|
async _refreshState() {
|
|
103
204
|
if (this._stopped) return;
|
|
104
205
|
try {
|
|
206
|
+
const online = await this._readOnline();
|
|
207
|
+
if (this.connected !== online) {
|
|
208
|
+
this.connected = online;
|
|
209
|
+
this.log.info(`${this.context.name}: Tuya now reports the device ${online ? 'online' : 'offline'}.`);
|
|
210
|
+
}
|
|
105
211
|
const status = await this.api.getStatus(this.context.id);
|
|
106
212
|
this._applyStatus(status);
|
|
107
213
|
} catch (ex) {
|
|
@@ -109,27 +215,76 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
109
215
|
}
|
|
110
216
|
}
|
|
111
217
|
|
|
218
|
+
// Resolve the device's reachability from Tuya's `online` flag, so HomeKit
|
|
219
|
+
// shows "No Response" when the device is genuinely offline. If the lookup
|
|
220
|
+
// isn't available (e.g. the project lacks the device-management API) fall
|
|
221
|
+
// back to reachable so control is never blocked.
|
|
222
|
+
async _readOnline() {
|
|
223
|
+
try {
|
|
224
|
+
const info = await this.api.getDeviceInfo(this.context.id);
|
|
225
|
+
if (info && typeof info.online === 'boolean') return info.online;
|
|
226
|
+
} catch (ex) {
|
|
227
|
+
this.log.debug(`${this.context.name}: online-status check failed: ${ex.message}`);
|
|
228
|
+
}
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
|
|
112
232
|
/* ------------------------------------------------------------------ *
|
|
113
233
|
* State helpers
|
|
114
234
|
* ------------------------------------------------------------------ */
|
|
115
235
|
|
|
116
|
-
//
|
|
117
|
-
|
|
236
|
+
// Read the device's initial data-points. Prefer the thing-shadow (it carries
|
|
237
|
+
// the numeric dp_id alongside each code, so LAN<->cloud bridging works); fall
|
|
238
|
+
// back to the plain status endpoint (code+value only) when the shadow isn't
|
|
239
|
+
// available. Returns an array of {code, value, dp_id?}.
|
|
240
|
+
async _readInitialProperties() {
|
|
241
|
+
if (typeof this.api.getShadowProperties === 'function') {
|
|
242
|
+
const props = await this.api.getShadowProperties(this.context.id);
|
|
243
|
+
if (Array.isArray(props)) return props;
|
|
244
|
+
}
|
|
245
|
+
return this.api.getStatus(this.context.id);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Learn the code <-> numeric dp_id mapping from a shadow-properties read.
|
|
249
|
+
_learnDpMap(props) {
|
|
250
|
+
(props || []).forEach(p => {
|
|
251
|
+
if (!p || typeof p.code !== 'string' || p.dp_id == null) return;
|
|
252
|
+
const dp = String(p.dp_id);
|
|
253
|
+
this.codeByDpId[dp] = p.code;
|
|
254
|
+
this.dpIdByCode[p.code] = dp;
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Index a data-point under BOTH its string code and (when known) its numeric
|
|
259
|
+
// dp id, so an accessory configured the LAN way (numeric) or the cloud way
|
|
260
|
+
// (code) both resolve. The dp id comes from the shadow item, or — for code-only
|
|
261
|
+
// realtime deltas — from the map learned on connect.
|
|
262
|
+
_indexInto(target, code, value, dpId) {
|
|
263
|
+
target[code] = value;
|
|
264
|
+
const dp = dpId != null ? String(dpId) : this.dpIdByCode[code];
|
|
265
|
+
if (dp != null) target[dp] = value;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Build the dual-keyed state object from a properties/status array.
|
|
269
|
+
_propsToState(props) {
|
|
118
270
|
const state = {};
|
|
119
|
-
(
|
|
120
|
-
if (item && typeof item.code === 'string')
|
|
271
|
+
(props || []).forEach(item => {
|
|
272
|
+
if (item && typeof item.code === 'string') {
|
|
273
|
+
this._indexInto(state, item.code, item.value, item.dp_id != null ? item.dp_id : item.dpId);
|
|
274
|
+
}
|
|
121
275
|
});
|
|
122
276
|
return state;
|
|
123
277
|
}
|
|
124
278
|
|
|
125
279
|
// Apply a fresh snapshot (initial / catch-up) or a realtime delta, diff it
|
|
126
280
|
// against what we hold, and emit only what changed — exactly mirroring
|
|
127
|
-
// TuyaAccessory._change so accessories behave identically.
|
|
281
|
+
// TuyaAccessory._change so accessories behave identically. State is dual-keyed
|
|
282
|
+
// (code + numeric dp) so a LAN-style or cloud-style config both resolve.
|
|
128
283
|
_applyStatus(status) {
|
|
129
|
-
const incoming = this.
|
|
284
|
+
const incoming = this._propsToState(status);
|
|
130
285
|
const changes = {};
|
|
131
|
-
Object.keys(incoming).forEach(
|
|
132
|
-
if (incoming[
|
|
286
|
+
Object.keys(incoming).forEach(key => {
|
|
287
|
+
if (incoming[key] !== this.state[key]) changes[key] = incoming[key];
|
|
133
288
|
});
|
|
134
289
|
if (Object.keys(changes).length) {
|
|
135
290
|
this.state = {...this.state, ...incoming};
|
|
@@ -138,10 +293,13 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
138
293
|
return changes;
|
|
139
294
|
}
|
|
140
295
|
|
|
141
|
-
_logDiscoveredCodes(
|
|
296
|
+
_logDiscoveredCodes(props) {
|
|
142
297
|
try {
|
|
143
|
-
const list = (
|
|
144
|
-
|
|
298
|
+
const list = (props || []).map(i => {
|
|
299
|
+
const dp = i.dp_id != null ? i.dp_id : (i.dpId != null ? i.dpId : this.dpIdByCode[i.code]);
|
|
300
|
+
return `${i.code}${dp != null ? `(dp ${dp})` : ''}=${JSON.stringify(i.value)}`;
|
|
301
|
+
}).join(', ');
|
|
302
|
+
this.log.debug(`${this.context.name}: Tuya Cloud data-points → ${list || '(none reported)'}`);
|
|
145
303
|
} catch (_) { /* logging must never throw */ }
|
|
146
304
|
}
|
|
147
305
|
|
|
@@ -154,11 +312,22 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
154
312
|
// `this.state`: the accessory already reflects the user's intent in HomeKit
|
|
155
313
|
// immediately, and leaving `state` untouched lets the realtime stream
|
|
156
314
|
// confirm the real device state without a spurious "revert" while a sleepy
|
|
157
|
-
// device catches up.
|
|
315
|
+
// device catches up.
|
|
316
|
+
//
|
|
317
|
+
// Return contract mirrors TuyaAccessory.update() as far as a synchronous
|
|
318
|
+
// caller is concerned (truthy on a no-op, `false` when not connected) but,
|
|
319
|
+
// unlike the LAN class, the actual command travels over HTTP and only its
|
|
320
|
+
// outcome reveals a failure. So when a command IS dispatched we return the
|
|
321
|
+
// promise that resolves to the boolean result (and never rejects), letting
|
|
322
|
+
// `BaseAccessory.setMultiStateAsync` await it and surface a rejected cloud
|
|
323
|
+
// command to HomeKit instead of silently dropping it.
|
|
158
324
|
update(dps) {
|
|
159
325
|
if (!dps || typeof dps !== 'object') return true;
|
|
160
326
|
|
|
161
|
-
|
|
327
|
+
// Keys may be numeric LAN dp ids (when a LAN-configured accessory falls
|
|
328
|
+
// back to the cloud) or string codes (a cloud-configured accessory); the
|
|
329
|
+
// commands API speaks codes, so translate via the learned map.
|
|
330
|
+
const commands = Object.keys(dps).map(key => ({code: this._toCode(key), value: dps[key]}));
|
|
162
331
|
if (!commands.length) return true;
|
|
163
332
|
|
|
164
333
|
if (!this.connected) {
|
|
@@ -166,13 +335,23 @@ class TuyaCloudDevice extends EventEmitter {
|
|
|
166
335
|
return false;
|
|
167
336
|
}
|
|
168
337
|
|
|
169
|
-
this.api.sendCommands(this.context.id, commands)
|
|
338
|
+
return this.api.sendCommands(this.context.id, commands)
|
|
170
339
|
.then(ok => {
|
|
171
340
|
if (!ok) this.log.warn(`${this.context.name}: Tuya Cloud rejected command ${JSON.stringify(commands)}`);
|
|
341
|
+
return ok;
|
|
172
342
|
})
|
|
173
|
-
.catch(ex =>
|
|
343
|
+
.catch(ex => {
|
|
344
|
+
this.log.error(`${this.context.name}: cloud command failed: ${ex.message}`);
|
|
345
|
+
return false;
|
|
346
|
+
});
|
|
347
|
+
}
|
|
174
348
|
|
|
175
|
-
|
|
349
|
+
// Resolve a write key (a numeric LAN dp id or a string code) to the Tuya Cloud
|
|
350
|
+
// `code` the commands API expects. A numeric id with a known code is
|
|
351
|
+
// translated; anything else (already a code, or an unmapped id) is passed
|
|
352
|
+
// through unchanged.
|
|
353
|
+
_toCode(key) {
|
|
354
|
+
return this.codeByDpId[key] || key;
|
|
176
355
|
}
|
|
177
356
|
|
|
178
357
|
/* ------------------------------------------------------------------ *
|
|
@@ -6,36 +6,27 @@ const crypto = require('crypto');
|
|
|
6
6
|
/*
|
|
7
7
|
* TuyaCloudMessaging
|
|
8
8
|
* ------------------
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
9
|
+
* Realtime updates for cloud-backed devices, over Tuya's MQTT message service.
|
|
10
|
+
* ONE instance is shared by every cloud device on the same Tuya project (one
|
|
11
|
+
* broker connection delivers status for all of them); messages are fanned out
|
|
12
|
+
* to the right device by its `devId`.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
14
|
+
* Cloud updates (including physical button presses and the rain sensor) arrive
|
|
15
|
+
* over this stream rather than by polling, so they show up in HomeKit within a
|
|
16
|
+
* second or two. `mqtt` is a required dependency; if the broker can't be
|
|
17
|
+
* reached or a message can't be decrypted nothing crashes — the stream simply
|
|
18
|
+
* reconnects and the cloud REST reads still cover initial state.
|
|
19
19
|
*
|
|
20
20
|
* The connection + AES-GCM message decryption are faithful to the
|
|
21
21
|
* actively-maintained `0x5e/homebridge-tuya-platform` (`src/core/TuyaOpenMQ.ts`),
|
|
22
22
|
* re-implemented here with Node's built-in `crypto`.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
+
const mqtt = require('mqtt');
|
|
26
|
+
|
|
25
27
|
const GCM_TAG_LENGTH = 16;
|
|
26
28
|
const PROTOCOL_DEVICE_STATUS = 4;
|
|
27
29
|
|
|
28
|
-
// `mqtt` is an OPTIONAL dependency: realtime is a bonus, polling is the
|
|
29
|
-
// guarantee. Loading it lazily keeps the plugin LAN-first and lets it run in
|
|
30
|
-
// environments where mqtt isn't (or can't be) installed.
|
|
31
|
-
let mqtt = null;
|
|
32
|
-
let mqttLoadError = null;
|
|
33
|
-
try {
|
|
34
|
-
mqtt = require('mqtt');
|
|
35
|
-
} catch (ex) {
|
|
36
|
-
mqttLoadError = ex;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
30
|
class TuyaCloudMessaging extends EventEmitter {
|
|
40
31
|
constructor({api, log} = {}) {
|
|
41
32
|
super();
|
|
@@ -56,10 +47,6 @@ class TuyaCloudMessaging extends EventEmitter {
|
|
|
56
47
|
this.setMaxListeners(0);
|
|
57
48
|
}
|
|
58
49
|
|
|
59
|
-
static isAvailable() {
|
|
60
|
-
return !!mqtt;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
50
|
// Register a device's status handler and lazily start the shared connection.
|
|
64
51
|
subscribeDevice(devId, handler) {
|
|
65
52
|
const id = '' + devId;
|
|
@@ -72,13 +59,8 @@ class TuyaCloudMessaging extends EventEmitter {
|
|
|
72
59
|
if (this._stopped || this._started) return;
|
|
73
60
|
this._started = true;
|
|
74
61
|
|
|
75
|
-
if (!mqtt) {
|
|
76
|
-
this.log.warn(`Tuya Cloud realtime disabled: the optional "mqtt" package is not installed${mqttLoadError ? ` (${mqttLoadError.message})` : ''}. Devices will poll instead. Install it with "npm install mqtt" in the plugin folder to enable instant updates.`);
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
62
|
this._connect().catch(ex => {
|
|
81
|
-
this.log.warn(`Tuya Cloud realtime could not start (${ex.message});
|
|
63
|
+
this.log.warn(`Tuya Cloud realtime could not start (${ex.message}); it will keep retrying.`);
|
|
82
64
|
this._scheduleRenew(60);
|
|
83
65
|
});
|
|
84
66
|
}
|
|
@@ -145,12 +127,12 @@ class TuyaCloudMessaging extends EventEmitter {
|
|
|
145
127
|
envelope = JSON.parse(payload.toString());
|
|
146
128
|
} catch (_) { return; }
|
|
147
129
|
|
|
148
|
-
const {protocol, data
|
|
130
|
+
const {protocol, data} = envelope;
|
|
149
131
|
if (!data) return;
|
|
150
132
|
|
|
151
133
|
let plaintext;
|
|
152
134
|
try {
|
|
153
|
-
plaintext = this._decrypt(data, this.config && this.config.password
|
|
135
|
+
plaintext = this._decrypt(data, this.config && this.config.password);
|
|
154
136
|
} catch (ex) {
|
|
155
137
|
this.log.debug(`Tuya Cloud realtime decrypt failed: ${ex.message}`);
|
|
156
138
|
return;
|
|
@@ -179,26 +161,31 @@ class TuyaCloudMessaging extends EventEmitter {
|
|
|
179
161
|
// Decrypt the MQTT `data` field. msg_encrypted_version 2.0 → AES-128-GCM,
|
|
180
162
|
// 1.0 → AES-128-ECB. The AES key is the middle 16 chars of the broker
|
|
181
163
|
// password (NOT the project Access Secret).
|
|
182
|
-
|
|
164
|
+
//
|
|
165
|
+
// The GCM auth tag is intentionally NOT verified: Tuya's real status frames
|
|
166
|
+
// do not carry a tag that verifies against the documented AAD, so calling
|
|
167
|
+
// `decipher.final()` would throw on every genuine message and silently drop
|
|
168
|
+
// all realtime updates. AES-GCM is a stream cipher, so `update()` alone
|
|
169
|
+
// recovers the plaintext correctly regardless of the tag; a wrong key just
|
|
170
|
+
// yields garbage that the subsequent JSON.parse rejects. Both the official
|
|
171
|
+
// `tuya/tuya-homebridge` and `0x5e/homebridge-tuya-platform` decrypt with
|
|
172
|
+
// `update()` only, for exactly this reason — `final()` here was the bug that
|
|
173
|
+
// stopped external changes (physical buttons, the Tuya app) from showing up.
|
|
174
|
+
_decrypt(data, password) {
|
|
183
175
|
const key = Buffer.from(('' + (password || '')).substring(8, 24), 'utf8');
|
|
184
176
|
const buf = Buffer.from(data, 'base64');
|
|
185
177
|
|
|
186
178
|
// GCM (v2.0) layout: [ivLen(4) BE][iv(ivLen)][ciphertext][tag(16)].
|
|
187
|
-
// Try it first; if the header doesn't look like a sane IV length,
|
|
188
|
-
//
|
|
179
|
+
// Try it first; if the header doesn't look like a sane IV length, fall
|
|
180
|
+
// back to ECB (v1.0).
|
|
189
181
|
if (buf.length > 4 + GCM_TAG_LENGTH) {
|
|
190
182
|
const ivLen = buf.readUIntBE(0, 4);
|
|
191
183
|
if (ivLen >= 12 && ivLen <= 16 && (4 + ivLen + GCM_TAG_LENGTH) <= buf.length) {
|
|
192
184
|
try {
|
|
193
185
|
const iv = buf.slice(4, 4 + ivLen);
|
|
194
186
|
const ciphertext = buf.slice(4 + ivLen, buf.length - GCM_TAG_LENGTH);
|
|
195
|
-
const tag = buf.slice(buf.length - GCM_TAG_LENGTH);
|
|
196
187
|
const decipher = crypto.createDecipheriv('aes-128-gcm', key, iv);
|
|
197
|
-
decipher.
|
|
198
|
-
const aad = Buffer.allocUnsafe(6);
|
|
199
|
-
aad.writeUIntBE(Number(t) || 0, 0, 6);
|
|
200
|
-
decipher.setAAD(aad);
|
|
201
|
-
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
|
188
|
+
return decipher.update(ciphertext).toString('utf8');
|
|
202
189
|
} catch (gcmEx) {
|
|
203
190
|
// fall through to ECB
|
|
204
191
|
}
|