homebridge-tuya-plus 3.14.0-dev.4 → 3.14.0-dev.41

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.
Files changed (53) hide show
  1. package/.github/workflows/publish-dev.yml +298 -31
  2. package/AGENTS.md +162 -0
  3. package/CLAUDE.md +1 -0
  4. package/Changelog.md +16 -3
  5. package/Readme.MD +8 -32
  6. package/config.schema.json +63 -78
  7. package/index.js +599 -358
  8. package/lib/AirPurifierAccessory.js +1 -1
  9. package/lib/BaseAccessory.js +54 -17
  10. package/lib/ConvectorAccessory.js +1 -1
  11. package/lib/CustomMultiOutletAccessory.js +2 -1
  12. package/lib/DoorbellAccessory.js +9 -16
  13. package/lib/GarageDoorAccessory.js +1 -1
  14. package/lib/IrrigationSystemAccessory.js +93 -114
  15. package/lib/MultiOutletAccessory.js +3 -2
  16. package/lib/OilDiffuserAccessory.js +10 -8
  17. package/lib/RGBTWLightAccessory.js +13 -11
  18. package/lib/RGBTWOutletAccessory.js +11 -9
  19. package/lib/SimpleBlindsAccessory.js +5 -5
  20. package/lib/SimpleDimmer2Accessory.js +1 -1
  21. package/lib/SimpleDimmerAccessory.js +10 -6
  22. package/lib/SimpleGarageDoorAccessory.js +78 -24
  23. package/lib/SimpleHeaterAccessory.js +4 -4
  24. package/lib/SimpleLightAccessory.js +1 -1
  25. package/lib/SwitchAccessory.js +3 -2
  26. package/lib/TWLightAccessory.js +2 -2
  27. package/lib/TuyaAccessory.js +75 -42
  28. package/lib/TuyaCloudApi.js +115 -7
  29. package/lib/TuyaCloudDevice.js +351 -28
  30. package/lib/TuyaCloudMessaging.js +28 -41
  31. package/lib/TuyaDevice.js +269 -0
  32. package/lib/TuyaDiscovery.js +25 -9
  33. package/lib/ValveAccessory.js +16 -12
  34. package/lib/VerticalBlindsWithTilt.js +27 -25
  35. package/lib/WledDimmerAccessory.js +46 -81
  36. package/package.json +5 -6
  37. package/scripts/cleanup-pr-tags.js +122 -0
  38. package/test/BaseAccessory.test.js +94 -15
  39. package/test/IrrigationSystemAccessory.test.js +122 -68
  40. package/test/MultiOutletAccessory.test.js +18 -3
  41. package/test/RGBTWLightAccessory.test.js +3 -3
  42. package/test/SimpleFanLightAccessory.test.js +3 -3
  43. package/test/SimpleGarageDoorAccessory.test.js +63 -9
  44. package/test/TuyaAccessory.protocol.test.js +76 -3
  45. package/test/TuyaCloudApi.test.js +110 -1
  46. package/test/TuyaCloudDevice.test.js +438 -2
  47. package/test/TuyaCloudMessaging.test.js +24 -5
  48. package/test/TuyaDevice.test.js +266 -0
  49. package/test/getCategory.test.js +1 -0
  50. package/test/index.test.js +271 -0
  51. package/test/support/mocks.js +13 -0
  52. package/wiki/Supported-Device-Types.md +48 -30
  53. package/wiki/Tuya-Cloud-Setup.md +31 -108
@@ -9,7 +9,9 @@ function makeApi(status = [{code: 'switch_1', value: false}, {code: 'battery_per
9
9
  return {
10
10
  isConfigured: () => true,
11
11
  getStatus: jest.fn().mockResolvedValue(status),
12
- sendCommands: jest.fn().mockResolvedValue(true)
12
+ getDeviceInfo: jest.fn().mockResolvedValue({online: true}),
13
+ sendCommands: jest.fn().mockResolvedValue(true),
14
+ sendProperties: jest.fn().mockResolvedValue(true)
13
15
  };
14
16
  }
15
17
 
@@ -55,10 +57,31 @@ describe('TuyaCloudDevice', () => {
55
57
  const api = makeApi();
56
58
  const dev = makeDevice(api);
57
59
  expect(dev.connected).toBe(false);
58
- expect(() => dev.update({switch_1: true})).not.toThrow();
60
+ expect(dev.update({switch_1: true})).toBe(false);
59
61
  expect(api.sendCommands).not.toHaveBeenCalled();
60
62
  });
61
63
 
64
+ test('update resolves to the cloud command result so failures are awaitable', async () => {
65
+ const api = makeApi();
66
+ const dev = makeDevice(api);
67
+ await dev._connect();
68
+
69
+ api.sendCommands.mockResolvedValueOnce(true);
70
+ await expect(dev.update({switch_1: true})).resolves.toBe(true);
71
+
72
+ api.sendCommands.mockResolvedValueOnce(false);
73
+ await expect(dev.update({switch_1: true})).resolves.toBe(false);
74
+ });
75
+
76
+ test('update resolves to false (never rejects) when the cloud request throws', async () => {
77
+ const api = makeApi();
78
+ const dev = makeDevice(api);
79
+ await dev._connect();
80
+
81
+ api.sendCommands.mockRejectedValueOnce(new Error('network down'));
82
+ await expect(dev.update({switch_1: true})).resolves.toBe(false);
83
+ });
84
+
62
85
  test('applyStatus emits only the changed data-points', async () => {
63
86
  const api = makeApi();
64
87
  const dev = makeDevice(api);
@@ -77,6 +100,173 @@ describe('TuyaCloudDevice', () => {
77
100
  expect(changes).toHaveLength(0);
78
101
  });
79
102
 
103
+ test('connect reflects the device online status (offline → not connected)', async () => {
104
+ const api = makeApi();
105
+ api.getDeviceInfo.mockResolvedValue({online: false});
106
+ const dev = makeDevice(api);
107
+ await dev._connect();
108
+ expect(api.getDeviceInfo).toHaveBeenCalledWith('dev1');
109
+ expect(dev.connected).toBe(false);
110
+ });
111
+
112
+ test('online lookup failure → assume reachable (never block control)', async () => {
113
+ const api = makeApi();
114
+ api.getDeviceInfo.mockRejectedValue(new Error('no device-management permission'));
115
+ const dev = makeDevice(api);
116
+ await dev._connect();
117
+ expect(dev.connected).toBe(true);
118
+ });
119
+
120
+ test('a state refresh re-checks online and flips connected', async () => {
121
+ const api = makeApi();
122
+ const dev = makeDevice(api);
123
+ await dev._connect();
124
+ expect(dev.connected).toBe(true);
125
+
126
+ api.getDeviceInfo.mockResolvedValue({online: false});
127
+ await dev._refreshState();
128
+ expect(dev.connected).toBe(false);
129
+ });
130
+
131
+ test('builds the code<->dp_id map and dual-keys state from the shadow', async () => {
132
+ const props = [{code: 'switch_1', dp_id: 1, value: false}, {code: 'battery_percentage', dp_id: 46, value: 99}];
133
+ const api = makeApi();
134
+ api.getShadowProperties = jest.fn().mockResolvedValue(props);
135
+ const dev = makeDevice(api);
136
+ await dev._connect();
137
+
138
+ expect(api.getShadowProperties).toHaveBeenCalledWith('dev1');
139
+ expect(dev.codeByDpId).toEqual({'1': 'switch_1', '46': 'battery_percentage'});
140
+ expect(dev.dpIdByCode).toEqual({'switch_1': '1', 'battery_percentage': '46'});
141
+ // state is addressable by BOTH the cloud code and the numeric LAN dp id
142
+ expect(dev.state).toEqual({switch_1: false, '1': false, battery_percentage: 99, '46': 99});
143
+ });
144
+
145
+ test('update translates a numeric dp id to its cloud code', async () => {
146
+ const api = makeApi();
147
+ api.getShadowProperties = jest.fn().mockResolvedValue([{code: 'switch_1', dp_id: 1, value: false}]);
148
+ const dev = makeDevice(api);
149
+ await dev._connect();
150
+
151
+ dev.update({'1': true}); // a LAN-style numeric write
152
+ expect(api.sendCommands).toHaveBeenCalledWith('dev1', [{code: 'switch_1', value: true}]);
153
+ });
154
+
155
+ test('a translated write is dispatched to the (iot-03) commands API', async () => {
156
+ const api = makeApi();
157
+ api.getShadowProperties = jest.fn().mockResolvedValue([{code: 'wfh_close', dp_id: 102, value: false}]);
158
+ const dev = makeDevice(api, null, {key: 'abc'});
159
+ await dev._connect();
160
+
161
+ await dev.update({'102': true});
162
+ expect(api.sendCommands).toHaveBeenCalledWith('dev1', [{code: 'wfh_close', value: true}]);
163
+ expect(api.sendProperties).not.toHaveBeenCalled();
164
+ });
165
+
166
+ // A fully-custom device (e.g. a gate controller) is rejected by every /commands
167
+ // API with 2008; the plugin must fall back to the thing-model property endpoint
168
+ // on its own, with no configuration.
169
+ describe('automatic control-endpoint fallback', () => {
170
+ const gate = async () => {
171
+ const api = makeApi();
172
+ api.getShadowProperties = jest.fn().mockResolvedValue([{code: 'wfh_close', dp_id: 102, value: false}]);
173
+ const dev = makeDevice(api, null, {key: 'abc'});
174
+ await dev._connect();
175
+ return {api, dev};
176
+ };
177
+
178
+ test('a 2008 from commands falls back to the thing-model property endpoint', async () => {
179
+ const {api, dev} = await gate();
180
+ api.sendCommands.mockRejectedValue(new Error('POST /v1.0/iot-03/devices/dev1/commands failed: command or value not support (code 2008)'));
181
+
182
+ await expect(dev.update({'102': true})).resolves.toBe(true);
183
+ expect(api.sendCommands).toHaveBeenCalledWith('dev1', [{code: 'wfh_close', value: true}]);
184
+ expect(api.sendProperties).toHaveBeenCalledWith('dev1', [{code: 'wfh_close', value: true}]);
185
+ });
186
+
187
+ test('once the property endpoint works it is used directly (no repeat doomed command)', async () => {
188
+ const {api, dev} = await gate();
189
+ api.sendCommands.mockRejectedValue(new Error('command or value not support (code 2008)'));
190
+
191
+ await dev.update({'102': true}); // probes: commands → properties
192
+ await dev.update({'102': false}); // should go straight to properties
193
+ expect(api.sendCommands).toHaveBeenCalledTimes(1);
194
+ expect(api.sendProperties).toHaveBeenCalledTimes(2);
195
+ });
196
+
197
+ test('a non-instruction failure (network) does NOT probe the thing model', async () => {
198
+ const {api, dev} = await gate();
199
+ api.sendCommands.mockRejectedValue(new Error('request timed out'));
200
+
201
+ await expect(dev.update({'102': true})).resolves.toBe(false);
202
+ expect(api.sendProperties).not.toHaveBeenCalled();
203
+ });
204
+
205
+ test('the property fallback is probed only once when it also fails', async () => {
206
+ const {api, dev} = await gate();
207
+ api.sendCommands.mockRejectedValue(new Error('command or value not support (code 2008)'));
208
+ api.sendProperties.mockRejectedValue(new Error('command or value not support (code 2008)'));
209
+
210
+ await dev.update({'102': true});
211
+ await dev.update({'102': true});
212
+ expect(api.sendProperties).toHaveBeenCalledTimes(1);
213
+ expect(api.sendCommands).toHaveBeenCalledTimes(2);
214
+ });
215
+
216
+ // The crux: a single device with a normal DP (standard instruction set) and
217
+ // a custom DP (thing model only) must drive EACH over its own endpoint.
218
+ test('a mixed device routes each data-point to the endpoint it accepts', async () => {
219
+ const api = makeApi();
220
+ api.getShadowProperties = jest.fn().mockResolvedValue([
221
+ {code: 'switch_1', dp_id: 1, value: false}, // standard → commands
222
+ {code: 'wfh_open', dp_id: 101, value: false} // custom → properties only
223
+ ]);
224
+ // The commands API accepts switch_1 but rejects any batch containing wfh_open.
225
+ api.sendCommands.mockImplementation((id, cmds) =>
226
+ cmds.some(c => c.code === 'wfh_open')
227
+ ? Promise.reject(new Error('command or value not support (code 2008)'))
228
+ : Promise.resolve(true));
229
+ const dev = makeDevice(api, null, {key: 'abc'});
230
+ await dev._connect();
231
+
232
+ await dev.update({'1': true}); // learns switch_1 → commands
233
+ await dev.update({'101': true}); // commands 2008 → learns wfh_open → properties
234
+
235
+ api.sendCommands.mockClear();
236
+ api.sendProperties.mockClear();
237
+
238
+ // A write touching both now splits: switch_1 over commands, wfh_open over properties.
239
+ await expect(dev.update({'1': false, '101': true})).resolves.toBe(true);
240
+ expect(api.sendCommands).toHaveBeenCalledWith('dev1', [{code: 'switch_1', value: false}]);
241
+ expect(api.sendProperties).toHaveBeenCalledWith('dev1', [{code: 'wfh_open', value: true}]);
242
+ });
243
+ });
244
+
245
+ test('realtime code-only deltas are mirrored to numeric ids via the learned map', async () => {
246
+ const api = makeApi();
247
+ api.getShadowProperties = jest.fn().mockResolvedValue([{code: 'switch_1', dp_id: 1, value: false}]);
248
+ const dev = makeDevice(api);
249
+ await dev._connect();
250
+
251
+ const changes = [];
252
+ dev.on('change', c => changes.push(c));
253
+ dev._applyStatus([{code: 'switch_1', value: true}]); // code-only (as MQTT delivers)
254
+ expect(dev.state.switch_1).toBe(true);
255
+ expect(dev.state['1']).toBe(true);
256
+ expect(changes[0]).toEqual({switch_1: true, '1': true});
257
+ });
258
+
259
+ test('falls back to /status (code-only) when the shadow is unavailable', async () => {
260
+ const api = makeApi();
261
+ api.getShadowProperties = jest.fn().mockResolvedValue(null);
262
+ const dev = makeDevice(api);
263
+ await dev._connect();
264
+
265
+ expect(dev.codeByDpId).toEqual({});
266
+ expect(dev.state).toEqual({switch_1: false, battery_percentage: 99}); // code-only, no numeric mirror
267
+ expect(api.getStatus).toHaveBeenCalledWith('dev1');
268
+ });
269
+
80
270
  test('subscribes to realtime and re-reads state when the stream (re)connects', async () => {
81
271
  const api = makeApi();
82
272
  const messaging = Object.assign(new EventEmitter(), {
@@ -102,4 +292,250 @@ describe('TuyaCloudDevice', () => {
102
292
  await new Promise(r => setImmediate(r));
103
293
  expect(api.getStatus).toHaveBeenCalledWith('dev1');
104
294
  });
295
+
296
+ describe('connect-failure handling (no log spam)', () => {
297
+ afterEach(() => jest.restoreAllMocks());
298
+
299
+ test('a repeated failure is surfaced once, suppressed after, and backs off', () => {
300
+ jest.useFakeTimers();
301
+ try {
302
+ const dev = makeDevice(makeApi(), null, {key: 'abc'}); // LAN-capable → fallback
303
+ const warn = jest.spyOn(log, 'warn');
304
+ const debug = jest.spyOn(log, 'debug');
305
+ const err = new Error('GET /v1.0/devices/dev1/status failed: permission deny (code 1106)');
306
+
307
+ dev._onConnectFailure(err);
308
+ expect(warn).toHaveBeenCalledTimes(1);
309
+ expect(warn.mock.calls[0][0]).toContain('permission deny (code 1106)');
310
+ expect(dev._retryDelay).toBe(30000);
311
+
312
+ dev._onConnectFailure(err); // identical → not surfaced again, just debug + backoff
313
+ expect(warn).toHaveBeenCalledTimes(1);
314
+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('still failing'));
315
+ expect(dev._retryDelay).toBe(60000);
316
+
317
+ dev._onConnectFailure(err);
318
+ expect(dev._retryDelay).toBe(120000);
319
+ } finally {
320
+ jest.useRealTimers();
321
+ }
322
+ });
323
+
324
+ test('a cloud-only device (no key) surfaces the failure at error level', () => {
325
+ jest.useFakeTimers();
326
+ try {
327
+ const dev = makeDevice(makeApi()); // no key → cloud is the only path
328
+ const error = jest.spyOn(log, 'error');
329
+ const warn = jest.spyOn(log, 'warn');
330
+
331
+ dev._onConnectFailure(new Error('permission deny (code 1106)'));
332
+ expect(warn).not.toHaveBeenCalled();
333
+ expect(error).toHaveBeenCalledTimes(1);
334
+ expect(error.mock.calls[0][0]).toContain('cloud-only');
335
+ } finally {
336
+ jest.useRealTimers();
337
+ }
338
+ });
339
+
340
+ test('a device reachable over the LAN logs the fallback failure as harmless (debug, not warn)', () => {
341
+ jest.useFakeTimers();
342
+ try {
343
+ const dev = makeDevice(makeApi(), null, {key: 'abc', isLanConnected: () => true});
344
+ const warn = jest.spyOn(log, 'warn');
345
+ const debug = jest.spyOn(log, 'debug');
346
+
347
+ dev._onConnectFailure(new Error('permission deny (code 1106)'));
348
+
349
+ expect(warn).not.toHaveBeenCalled();
350
+ expect(debug).toHaveBeenCalledTimes(1);
351
+ expect(debug.mock.calls[0][0]).toContain('reachable over the LAN');
352
+ } finally {
353
+ jest.useRealTimers();
354
+ }
355
+ });
356
+
357
+ test('the same failure re-surfaces (debug → warn) when the LAN path drops', () => {
358
+ jest.useFakeTimers();
359
+ try {
360
+ let lanUp = true;
361
+ const dev = makeDevice(makeApi(), null, {key: 'abc', isLanConnected: () => lanUp});
362
+ const warn = jest.spyOn(log, 'warn');
363
+ const err = new Error('permission deny (code 1106)');
364
+
365
+ dev._onConnectFailure(err); // LAN up → harmless, debug only
366
+ expect(warn).not.toHaveBeenCalled();
367
+
368
+ lanUp = false;
369
+ dev._onConnectFailure(err); // identical error, but LAN now down → surfaced
370
+ expect(warn).toHaveBeenCalledTimes(1);
371
+ expect(warn.mock.calls[0][0]).toContain("isn't reachable over the LAN");
372
+ } finally {
373
+ jest.useRealTimers();
374
+ }
375
+ });
376
+
377
+ test('permission-deny adds the offline-unbinding hint; an unrelated error does not', () => {
378
+ jest.useFakeTimers();
379
+ try {
380
+ const dev = makeDevice(makeApi(), null, {key: 'abc'}); // LAN-capable, LAN down
381
+ const warn = jest.spyOn(log, 'warn');
382
+
383
+ dev._onConnectFailure(new Error('permission deny (code 1106)'));
384
+ expect(warn.mock.calls[0][0]).toContain('offline for a long time');
385
+
386
+ dev._onConnectFailure(new Error('request timed out'));
387
+ expect(warn.mock.calls[1][0]).not.toContain('offline for a long time');
388
+ } finally {
389
+ jest.useRealTimers();
390
+ }
391
+ });
392
+
393
+ test('a different error message is surfaced again, not suppressed', () => {
394
+ jest.useFakeTimers();
395
+ try {
396
+ const dev = makeDevice(makeApi(), null, {key: 'abc'});
397
+ const warn = jest.spyOn(log, 'warn');
398
+
399
+ dev._onConnectFailure(new Error('permission deny (code 1106)'));
400
+ dev._onConnectFailure(new Error('request timed out'));
401
+ expect(warn).toHaveBeenCalledTimes(2);
402
+ } finally {
403
+ jest.useRealTimers();
404
+ }
405
+ });
406
+
407
+ test('backoff is capped at 30 minutes', () => {
408
+ jest.useFakeTimers();
409
+ try {
410
+ const dev = makeDevice(makeApi(), null, {key: 'abc'});
411
+ jest.spyOn(log, 'warn');
412
+ jest.spyOn(log, 'debug');
413
+ const err = new Error('permission deny (code 1106)');
414
+
415
+ for (let i = 0; i < 20; i++) dev._onConnectFailure(err);
416
+ expect(dev._retryDelay).toBe(1800000);
417
+ } finally {
418
+ jest.useRealTimers();
419
+ }
420
+ });
421
+
422
+ test('reconnecting after a failure logs recovery once and resets backoff', async () => {
423
+ const dev = makeDevice(makeApi(), null, {key: 'abc'});
424
+ dev._lastConnectError = 'permission deny (code 1106)';
425
+ dev._retryDelay = 240000;
426
+ const info = jest.spyOn(log, 'info');
427
+
428
+ await dev._connect(); // mocked api resolves → success path runs
429
+
430
+ expect(dev._lastConnectError).toBeNull();
431
+ expect(dev._retryDelay).toBe(0);
432
+ expect(info).toHaveBeenCalledWith(expect.stringContaining('connection restored'));
433
+ });
434
+
435
+ test('a stopped device does not schedule another retry', () => {
436
+ jest.useFakeTimers();
437
+ try {
438
+ const dev = makeDevice(makeApi(), null, {key: 'abc'});
439
+ jest.spyOn(log, 'warn');
440
+ dev.stop();
441
+ dev._onConnectFailure(new Error('permission deny (code 1106)'));
442
+ expect(dev._retryTimer).toBeNull();
443
+ } finally {
444
+ jest.useRealTimers();
445
+ }
446
+ });
447
+ });
448
+
449
+ describe('write-failure handling (no log spam)', () => {
450
+ afterEach(() => jest.restoreAllMocks());
451
+
452
+ // A LAN-style accessory (numeric dps) over a cloud project that never
453
+ // learned the id→code map: the write can't be addressed, so it must not be
454
+ // fired (it would always be a 2008), and the cause is surfaced just once.
455
+ test('a numeric write with no learned code map is skipped, not sent, and surfaced once', async () => {
456
+ const api = makeApi(); // /status only → no dp map
457
+ const dev = makeDevice(api, null, {key: 'abc'}); // LAN-capable, LAN down here
458
+ await dev._connect();
459
+ expect(dev.codeByDpId).toEqual({});
460
+
461
+ const warn = jest.spyOn(log, 'warn');
462
+ const debug = jest.spyOn(log, 'debug');
463
+
464
+ expect(dev.update({'1': true})).toBe(false);
465
+ expect(api.sendCommands).not.toHaveBeenCalled();
466
+ expect(warn).toHaveBeenCalledTimes(1);
467
+ expect(warn.mock.calls[0][0]).toContain('over the Tuya Cloud');
468
+
469
+ dev.update({'1': true}); // identical → quiet at debug, still not sent
470
+ expect(warn).toHaveBeenCalledTimes(1);
471
+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('cloud write skipped'));
472
+ expect(api.sendCommands).not.toHaveBeenCalled();
473
+ });
474
+
475
+ test('the undeliverable-write note is harmless (debug) while the device is reachable over the LAN', async () => {
476
+ const dev = makeDevice(makeApi(), null, {key: 'abc', isLanConnected: () => true});
477
+ await dev._connect();
478
+ const warn = jest.spyOn(log, 'warn');
479
+ const debug = jest.spyOn(log, 'debug');
480
+
481
+ expect(dev.update({'1': true})).toBe(false);
482
+ expect(warn).not.toHaveBeenCalled();
483
+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('over the Tuya Cloud'));
484
+ });
485
+
486
+ test('a cloud-only device (no key) surfaces the undeliverable write at error level', async () => {
487
+ const dev = makeDevice(makeApi()); // no key → cloud is the only path
488
+ await dev._connect();
489
+ const error = jest.spyOn(log, 'error');
490
+ const warn = jest.spyOn(log, 'warn');
491
+
492
+ expect(dev.update({'1': true})).toBe(false);
493
+ expect(warn).not.toHaveBeenCalled();
494
+ expect(error).toHaveBeenCalledTimes(1);
495
+ });
496
+
497
+ // A genuinely dispatched command that the cloud rejects (e.g. a real 2008
498
+ // on a mapped code): surface once, then suppress identical repeats to debug.
499
+ test('a repeated cloud command failure is surfaced once then suppressed to debug', async () => {
500
+ const api = makeApi();
501
+ api.getShadowProperties = jest.fn().mockResolvedValue([{code: 'switch_1', dp_id: 1, value: false}]);
502
+ const dev = makeDevice(api, null, {key: 'abc'});
503
+ await dev._connect();
504
+
505
+ const warn = jest.spyOn(log, 'warn');
506
+ const debug = jest.spyOn(log, 'debug');
507
+ const ex = new Error('POST /v1.0/iot-03/devices/dev1/commands failed: command or value not support (code 2008)');
508
+ api.sendCommands.mockRejectedValue(ex);
509
+ api.sendProperties.mockRejectedValue(ex); // thing-model fallback can't rescue it either
510
+
511
+ await dev.update({'1': true}); // mapped → dispatched → rejected by both endpoints
512
+ expect(api.sendCommands).toHaveBeenCalledWith('dev1', [{code: 'switch_1', value: true}]);
513
+ expect(warn).toHaveBeenCalledTimes(1);
514
+ expect(warn.mock.calls[0][0]).toContain('code 2008');
515
+
516
+ await dev.update({'1': true}); // identical failure → quiet
517
+ expect(warn).toHaveBeenCalledTimes(1);
518
+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('still failing'));
519
+ });
520
+
521
+ test('a command failure re-surfaces after an intervening success', async () => {
522
+ const api = makeApi();
523
+ api.getShadowProperties = jest.fn().mockResolvedValue([{code: 'switch_1', dp_id: 1, value: false}]);
524
+ const dev = makeDevice(api, null, {key: 'abc'});
525
+ await dev._connect();
526
+ const warn = jest.spyOn(log, 'warn');
527
+ api.sendProperties.mockRejectedValue(new Error('command or value not support (code 2008)')); // fallback can't rescue
528
+
529
+ api.sendCommands.mockRejectedValueOnce(new Error('command or value not support (code 2008)'));
530
+ await dev.update({'1': true});
531
+ expect(warn).toHaveBeenCalledTimes(1);
532
+
533
+ api.sendCommands.mockResolvedValueOnce(true); // success clears the dedup
534
+ await dev.update({'1': true});
535
+
536
+ api.sendCommands.mockRejectedValueOnce(new Error('command or value not support (code 2008)'));
537
+ await dev.update({'1': true});
538
+ expect(warn).toHaveBeenCalledTimes(2);
539
+ });
540
+ });
105
541
  });
@@ -56,6 +56,30 @@ describe('TuyaCloudMessaging — decryption + dispatch', () => {
56
56
  expect(received[0]).toEqual([{code: 'switch_1', value: true, t}, {code: 'battery_percentage', value: 80, t}]);
57
57
  });
58
58
 
59
+ test('decrypts a GCM frame even when the auth tag does not verify (Tuya quirk)', () => {
60
+ // Real Tuya status frames carry a GCM tag that does NOT verify against
61
+ // the documented AAD. We must decrypt with update() only (no final(),
62
+ // no tag check) or every realtime update is silently dropped — which is
63
+ // exactly what stopped external changes from reaching HomeKit. Simulate
64
+ // it by clobbering the trailing 16-byte tag: the plaintext must still
65
+ // come through.
66
+ const mq = makeIdle();
67
+ const received = [];
68
+ mq.subscribeDevice('DEV1', status => received.push(status));
69
+
70
+ const t = Date.now();
71
+ const raw = Buffer.from(
72
+ encryptGCM(JSON.stringify({devId: 'DEV1', status: [{code: 'switch_1', value: true}]}), mq.config.password, t),
73
+ 'base64'
74
+ );
75
+ crypto.randomBytes(16).copy(raw, raw.length - 16); // corrupt the auth tag
76
+
77
+ mq._onMessage('topic', Buffer.from(JSON.stringify({protocol: 4, data: raw.toString('base64'), t})));
78
+
79
+ expect(received).toHaveLength(1);
80
+ expect(received[0]).toEqual([{code: 'switch_1', value: true}]);
81
+ });
82
+
59
83
  test('decrypts a legacy ECB (v1.0) frame too', () => {
60
84
  const mq = makeIdle();
61
85
  const received = [];
@@ -86,9 +110,4 @@ describe('TuyaCloudMessaging — decryption + dispatch', () => {
86
110
  mq.subscribeDevice('DEV1', () => { throw new Error('should not be called'); });
87
111
  expect(() => mq._onMessage('topic', Buffer.from('not json'))).not.toThrow();
88
112
  });
89
-
90
- test('reports whether realtime is available (mqtt installed)', () => {
91
- // mqtt is an (optional) dependency of this project, so it should load.
92
- expect(typeof TuyaCloudMessaging.isAvailable()).toBe('boolean');
93
- });
94
113
  });