homebridge-tuya-plus 3.14.0-dev.3 → 3.14.0-dev.31

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 (47) hide show
  1. package/.github/workflows/publish-dev.yml +298 -31
  2. package/AGENTS.md +120 -0
  3. package/CLAUDE.md +1 -0
  4. package/Changelog.md +21 -0
  5. package/Readme.MD +8 -24
  6. package/config.schema.json +122 -68
  7. package/index.js +536 -269
  8. package/lib/BaseAccessory.js +53 -16
  9. package/lib/ConvectorAccessory.js +1 -1
  10. package/lib/CustomMultiOutletAccessory.js +2 -1
  11. package/lib/IrrigationSystemAccessory.js +98 -95
  12. package/lib/MultiOutletAccessory.js +2 -1
  13. package/lib/OilDiffuserAccessory.js +10 -8
  14. package/lib/RGBTWLightAccessory.js +13 -11
  15. package/lib/RGBTWOutletAccessory.js +11 -9
  16. package/lib/SimpleBlindsAccessory.js +5 -5
  17. package/lib/SimpleDimmer2Accessory.js +1 -1
  18. package/lib/SimpleDimmerAccessory.js +10 -6
  19. package/lib/SimpleGarageDoorAccessory.js +78 -24
  20. package/lib/SimpleHeaterAccessory.js +3 -3
  21. package/lib/SwitchAccessory.js +2 -1
  22. package/lib/TWLightAccessory.js +2 -2
  23. package/lib/TuyaAccessory.js +0 -1
  24. package/lib/TuyaCloudApi.js +320 -0
  25. package/lib/TuyaCloudDevice.js +367 -0
  26. package/lib/TuyaCloudMessaging.js +219 -0
  27. package/lib/TuyaDevice.js +269 -0
  28. package/lib/ValveAccessory.js +16 -12
  29. package/lib/VerticalBlindsWithTilt.js +5 -3
  30. package/lib/WledDimmerAccessory.js +46 -81
  31. package/package.json +5 -3
  32. package/scripts/cleanup-pr-tags.js +122 -0
  33. package/test/BaseAccessory.test.js +94 -15
  34. package/test/IrrigationSystemAccessory.test.js +134 -31
  35. package/test/MultiOutletAccessory.test.js +18 -3
  36. package/test/RGBTWLightAccessory.test.js +3 -3
  37. package/test/SimpleFanLightAccessory.test.js +3 -3
  38. package/test/SimpleGarageDoorAccessory.test.js +63 -9
  39. package/test/TuyaCloudApi.test.js +221 -0
  40. package/test/TuyaCloudDevice.test.js +357 -0
  41. package/test/TuyaCloudMessaging.test.js +113 -0
  42. package/test/TuyaDevice.test.js +266 -0
  43. package/test/getCategory.test.js +1 -0
  44. package/test/index.test.js +241 -0
  45. package/test/support/mocks.js +13 -0
  46. package/wiki/Supported-Device-Types.md +60 -28
  47. package/wiki/Tuya-Cloud-Setup.md +71 -0
@@ -0,0 +1,269 @@
1
+ 'use strict';
2
+
3
+ const EventEmitter = require('events');
4
+ const TuyaAccessory = require('./TuyaAccessory');
5
+ const TuyaCloudDevice = require('./TuyaCloudDevice');
6
+
7
+ /*
8
+ * TuyaDevice
9
+ * ----------
10
+ * The single `device` object every accessory now talks to. It presents the exact
11
+ * same minimal contract the accessories already rely on —
12
+ *
13
+ * - `context` device config (name, id, type, …)
14
+ * - `state` current data-points
15
+ * - `connected` boolean
16
+ * - `_connect()` start talking to the device
17
+ * - `update(dps)` write data-points
18
+ * - 'connect' / 'change' events (change → (changes, state))
19
+ *
20
+ * — but underneath it transparently spans BOTH transports:
21
+ *
22
+ * - a LAN backend (TuyaAccessory) — the fast, private, local path
23
+ * - a cloud backend (TuyaCloudDevice)— Tuya's internet path, used as a fallback
24
+ *
25
+ * Behaviour mirrors the official Tuya app: control goes over the LAN whenever the
26
+ * device is reachable there; if the LAN is down (or the device never appears on it
27
+ * — e.g. battery-powered "sleepy" units) it falls back to the cloud. Only when
28
+ * BOTH are unreachable does the device report disconnected, so the accessory shows
29
+ * "No Response". Accessories don't know or care which path is live.
30
+ *
31
+ * The one thing that differs between the transports is how a data-point is
32
+ * addressed: the LAN speaks numeric ids (1, 2, …), the cloud speaks string codes
33
+ * (switch_led, …). The cloud backend learns the id<->code map from the device's
34
+ * thing-shadow and keeps `state` keyed BOTH ways, so a configuration written for
35
+ * either transport resolves over the other. Writes are translated to whatever the
36
+ * live backend needs. The net effect: existing LAN configs gain a cloud fallback,
37
+ * and existing cloud configs gain LAN, with no config change.
38
+ */
39
+
40
+ // When a LAN-primary device's cloud backend connects first but can't offer the
41
+ // numeric data-point map (the device-shadow API isn't available), give the LAN a
42
+ // short head start before letting the cloud drive the one-time characteristic
43
+ // registration — so a numeric-DP config still registers against numeric keys.
44
+ const LAN_REGISTRATION_GRACE_MS = 15000;
45
+
46
+ class TuyaDevice extends EventEmitter {
47
+ constructor(props = {}) {
48
+ super();
49
+ // Several accessories attach their own 'change' listener on top of the one
50
+ // BaseAccessory uses; keep the default-listener guard from ever warning.
51
+ this.setMaxListeners(0);
52
+
53
+ this.log = props.log || console;
54
+
55
+ // A plain config object on `context`, mirroring the transport classes but
56
+ // without the live helper objects we were handed.
57
+ this.context = {...props};
58
+ delete this.context.log;
59
+ delete this.context.cloudApi;
60
+ delete this.context.messaging;
61
+
62
+ this.state = {};
63
+ this._stopped = false;
64
+ this._registered = false; // has the first 'change' (registration) gone out?
65
+ this._connectEmitted = false;
66
+ this._lanGraceElapsed = false;
67
+
68
+ // LAN backend — created later, once an IP is known (see attachLan). A
69
+ // device with no local key can't speak the LAN protocol at all, so it is
70
+ // cloud-only and this stays null.
71
+ this.lan = null;
72
+
73
+ // Cloud backend — present whenever the platform handed us a shared cloud
74
+ // session and this device isn't opted out of it.
75
+ this.cloud = null;
76
+ if (props.cloudApi) {
77
+ this.cloud = new TuyaCloudDevice({
78
+ ...props,
79
+ cloudApi: props.cloudApi,
80
+ messaging: props.messaging,
81
+ log: this.log,
82
+ // Let the cloud backend tell a harmless fallback failure (the device
83
+ // is reachable over the LAN) apart from one that matters (it isn't).
84
+ isLanConnected: () => !!(this.lan && this.lan.connected),
85
+ connect: false
86
+ });
87
+ }
88
+
89
+ if (props.connect !== false) this._connect();
90
+ }
91
+
92
+ // Reachable over either transport.
93
+ get connected() {
94
+ return !!((this.lan && this.lan.connected) || (this.cloud && this.cloud.connected));
95
+ }
96
+
97
+ /* ------------------------------------------------------------------ *
98
+ * Lifecycle
99
+ * ------------------------------------------------------------------ */
100
+
101
+ _connect() {
102
+ if (this.cloud) {
103
+ this._wire(this.cloud, 'cloud');
104
+ this.cloud._connect();
105
+
106
+ // Safety net for the LAN-without-map registration guard above.
107
+ if (this.context.key) {
108
+ setTimeout(() => {
109
+ this._lanGraceElapsed = true;
110
+ if (!this._registered) this._onBackendChange();
111
+ }, LAN_REGISTRATION_GRACE_MS).unref?.();
112
+ }
113
+ }
114
+ // The LAN backend is attached by the platform via attachLan() once the
115
+ // device's IP is known (from discovery, or a configured `ip`), preserving
116
+ // the existing discovery timing.
117
+ }
118
+
119
+ // Bring up (or update) the LAN transport for a device whose IP is now known.
120
+ // `target` carries the {ip, version} learned from discovery; a configured
121
+ // version/forceVersion still take precedence as they always have.
122
+ attachLan(target = {}) {
123
+ if (this._stopped || this.lan) return;
124
+ if (!this.context.key) {
125
+ this.log.debug(`${this.context.name}: no local key; staying on the cloud only.`);
126
+ return;
127
+ }
128
+ if (!target.ip && !this.context.ip) return;
129
+
130
+ let version = this.context.version;
131
+ if (target.version) version = target.version; // the device's broadcast wins…
132
+ if (this.context.forceVersion) version = this.context.forceVersion; // …but forceVersion wins all
133
+
134
+ this.lan = new TuyaAccessory({
135
+ ...this.context,
136
+ ip: target.ip || this.context.ip,
137
+ version,
138
+ log: this.log,
139
+ connect: false
140
+ });
141
+ this._wire(this.lan, 'lan');
142
+ this.lan._connect();
143
+ }
144
+
145
+ _wire(backend, which) {
146
+ backend.on('connect', () => this._onBackendConnect(which));
147
+ backend.on('change', () => this._onBackendChange(which));
148
+ }
149
+
150
+ _onBackendConnect(which) {
151
+ this.log.debug(`${this.context.name}: ${which} backend connected.`);
152
+ if (!this._connectEmitted) {
153
+ this._connectEmitted = true;
154
+ this.emit('connect');
155
+ }
156
+ }
157
+
158
+ /* ------------------------------------------------------------------ *
159
+ * State merge — LAN wins while it's up, cloud fills the rest / takes over
160
+ * ------------------------------------------------------------------ */
161
+
162
+ _merge() {
163
+ const merged = {};
164
+ if (this.cloud && this.cloud.connected) Object.assign(merged, this.cloud.state);
165
+ // LAN overlays the cloud while it's connected: it's the authoritative,
166
+ // freshest view for a device that's actually reachable locally.
167
+ if (this.lan && this.lan.connected) Object.assign(merged, this._lanStateDualKeyed());
168
+ return merged;
169
+ }
170
+
171
+ // LAN state is keyed by numeric dp id; mirror each value under its cloud code
172
+ // too (using the map the cloud backend learned), so a code-style config still
173
+ // resolves while the device is on the LAN.
174
+ _lanStateDualKeyed() {
175
+ const lanState = this.lan.state;
176
+ if (!this.cloud) return lanState;
177
+ const codeByDpId = this.cloud.codeByDpId;
178
+ const out = {...lanState};
179
+ for (const dp in lanState) {
180
+ const code = codeByDpId[dp];
181
+ if (code != null) out[code] = lanState[dp];
182
+ }
183
+ return out;
184
+ }
185
+
186
+ _onBackendChange(which) {
187
+ if (this._stopped) return;
188
+ if (!this._registered && !this._mayRegisterFrom(which)) return;
189
+
190
+ const merged = this._merge();
191
+ const changes = {};
192
+ Object.keys(merged).forEach(key => {
193
+ if (merged[key] !== this.state[key]) changes[key] = merged[key];
194
+ });
195
+
196
+ const first = !this._registered;
197
+ if (first || Object.keys(changes).length) {
198
+ this.state = {...this.state, ...merged};
199
+ this._registered = true;
200
+ // The first emit drives BaseAccessory's one-time characteristic
201
+ // registration; later emits carry only what actually changed.
202
+ this.emit('change', changes, this.state);
203
+ }
204
+ }
205
+
206
+ // Decide whether `which` backend may drive the one-time characteristic
207
+ // registration. LAN is always safe (numeric signature). The cloud is safe when
208
+ // the device is cloud-only (no local key), or once it has the numeric map (state
209
+ // is dual-keyed and so resolves a numeric-DP config), or once the LAN has been
210
+ // given its head start and didn't show up.
211
+ _mayRegisterFrom(which) {
212
+ if (which === 'lan') return true;
213
+ if (!this.context.key) return true;
214
+ if (this.cloud && Object.keys(this.cloud.codeByDpId).length) return true;
215
+ return this._lanGraceElapsed;
216
+ }
217
+
218
+ /* ------------------------------------------------------------------ *
219
+ * Writes — LAN first, cloud as a fallback
220
+ * ------------------------------------------------------------------ */
221
+
222
+ update(dps) {
223
+ // Pure LAN (no cloud configured): byte-for-byte the legacy behaviour — a
224
+ // synchronous boolean, so the sync write helpers keep detecting failures.
225
+ if (!this.cloud) {
226
+ return this.lan ? this.lan.update(this._toLanDps(dps)) : false;
227
+ }
228
+ return this._updateWithFallback(dps);
229
+ }
230
+
231
+ async _updateWithFallback(dps) {
232
+ // Prefer the LAN while it's connected.
233
+ if (this.lan && this.lan.connected) {
234
+ if (this.lan.update(this._toLanDps(dps)) !== false) return true;
235
+ this.log.debug(`${this.context.name}: LAN write didn't go through; trying the cloud.`);
236
+ }
237
+ if (this.cloud && this.cloud.connected) {
238
+ return (await this.cloud.update(dps)) !== false;
239
+ }
240
+ // Cloud is down too — a last LAN attempt (it may have just dropped, and a
241
+ // buffered write is better than a guaranteed failure).
242
+ if (this.lan) return this.lan.update(this._toLanDps(dps)) !== false;
243
+ return false;
244
+ }
245
+
246
+ // Translate a write keyed by codes and/or numeric ids into the numeric ids the
247
+ // LAN protocol needs. Numeric ids pass straight through; a code with a known id
248
+ // is translated; an unmapped code is left as-is (TuyaAccessory.update will then
249
+ // simply ignore it, which is the safe degradation when no map is available).
250
+ _toLanDps(dps) {
251
+ if (!this.cloud || !dps || typeof dps !== 'object') return dps;
252
+ const dpIdByCode = this.cloud.dpIdByCode;
253
+ const out = {};
254
+ for (const key in dps) out[dpIdByCode[key] || key] = dps[key];
255
+ return out;
256
+ }
257
+
258
+ /* ------------------------------------------------------------------ *
259
+ * Teardown (tidy; Homebridge doesn't strictly require it)
260
+ * ------------------------------------------------------------------ */
261
+
262
+ stop() {
263
+ this._stopped = true;
264
+ if (this.cloud && typeof this.cloud.stop === 'function') this.cloud.stop();
265
+ if (this.lan && typeof this.lan.stop === 'function') this.lan.stop();
266
+ }
267
+ }
268
+
269
+ module.exports = TuyaDevice;
@@ -49,13 +49,13 @@ class ValveAccessory extends BaseAccessory {
49
49
  .onSet(value => this.setStateAsync(this.dpPower, value));
50
50
 
51
51
  const characteristicInUse = service.getCharacteristic(Characteristic.InUse)
52
- .onGet(() => characteristicActive.value);
52
+ .onGet(() => { if (!this.device.connected) throw this._commError(); return characteristicActive.value; });
53
53
 
54
54
  if (!this.noTimer) {
55
55
  service.getCharacteristic(Characteristic.SetDuration)
56
- .onGet(() => this.setDuration)
56
+ .onGet(() => { if (!this.device.connected) throw this._commError(); return this.setDuration; })
57
57
  .on('change', (data) => {
58
- this.log.info('Water Valve Time Duration Set to: ' + data.newValue / 60 + ' Minutes');
58
+ this.log.debug('Water Valve Time Duration Set to: ' + data.newValue / 60 + ' Minutes');
59
59
  this.setDuration = data.newValue;
60
60
 
61
61
  if (service.getCharacteristic(Characteristic.InUse).value) {
@@ -65,8 +65,9 @@ class ValveAccessory extends BaseAccessory {
65
65
 
66
66
  clearTimeout(this.timer);
67
67
  this.timer = setTimeout(() => {
68
- this.log.info('Water Valve Timer Expired. Shutting OFF Valve');
69
- service.getCharacteristic(Characteristic.Active).setValue(0);
68
+ this.log.debug('Water Valve Timer Expired. Shutting OFF Valve');
69
+ this.setStateInBackground(this.dpPower, 0);
70
+ service.getCharacteristic(Characteristic.Active).updateValue(0);
70
71
  service.getCharacteristic(Characteristic.InUse).updateValue(0);
71
72
  this.lastActivationTime = null;
72
73
  }, (data.newValue * 1000));
@@ -75,6 +76,7 @@ class ValveAccessory extends BaseAccessory {
75
76
 
76
77
  service.getCharacteristic(Characteristic.RemainingDuration)
77
78
  .onGet(() => {
79
+ if (!this.device.connected) throw this._commError();
78
80
  let remainingTime = this.setDuration - Math.floor(((new Date()).getTime() - this.lastActivationTime) / 1000);
79
81
  return (remainingTime && remainingTime > 0) ? remainingTime : 0;
80
82
  });
@@ -87,17 +89,18 @@ class ValveAccessory extends BaseAccessory {
87
89
  service.getCharacteristic(Characteristic.RemainingDuration).updateValue(0);
88
90
  service.getCharacteristic(Characteristic.Active).updateValue(0);
89
91
  clearTimeout(this.timer);
90
- this.log.info('Water Valve is OFF!');
92
+ this.log.debug('Water Valve is OFF!');
91
93
  break;
92
94
  case 1:
93
95
  this.lastActivationTime = (new Date()).getTime();
94
96
  service.getCharacteristic(Characteristic.RemainingDuration).updateValue(this.setDuration);
95
97
  service.getCharacteristic(Characteristic.Active).updateValue(1);
96
- this.log.info('Water Valve Turning ON with Timer Set to: ' + this.setDuration / 60 + ' Minutes');
98
+ this.log.debug('Water Valve Turning ON with Timer Set to: ' + this.setDuration / 60 + ' Minutes');
97
99
  clearTimeout(this.timer);
98
100
  this.timer = setTimeout(() => {
99
- this.log.info('Water Valve Timer Expired. Shutting OFF Valve');
100
- service.getCharacteristic(Characteristic.Active).setValue(0);
101
+ this.log.debug('Water Valve Timer Expired. Shutting OFF Valve');
102
+ this.setStateInBackground(this.dpPower, 0);
103
+ service.getCharacteristic(Characteristic.Active).updateValue(0);
101
104
  service.getCharacteristic(Characteristic.InUse).updateValue(0);
102
105
  this.lastActivationTime = null;
103
106
  }, (this.setDuration * 1000));
@@ -110,11 +113,12 @@ class ValveAccessory extends BaseAccessory {
110
113
  service.getCharacteristic(Characteristic.RemainingDuration).updateValue(this.setDuration);
111
114
  service.getCharacteristic(Characteristic.Active).updateValue(1);
112
115
  service.getCharacteristic(Characteristic.InUse).updateValue(1);
113
- this.log.info('Water Valve is ON After Restart. Setting Timer to: ' + this.setDuration / 60 + ' Minutes');
116
+ this.log.debug('Water Valve is ON After Restart. Setting Timer to: ' + this.setDuration / 60 + ' Minutes');
114
117
  clearTimeout(this.timer);
115
118
  this.timer = setTimeout(() => {
116
- this.log.info('Water Valve Timer Expired. Shutting OFF Valve');
117
- service.getCharacteristic(Characteristic.Active).setValue(0);
119
+ this.log.debug('Water Valve Timer Expired. Shutting OFF Valve');
120
+ this.setStateInBackground(this.dpPower, 0);
121
+ service.getCharacteristic(Characteristic.Active).updateValue(0);
118
122
  this.lastActivationTime = null;
119
123
  }, (this.setDuration * 1000));
120
124
  }
@@ -38,16 +38,16 @@ class VerticalBlindsWithTilt extends BaseAccessory {
38
38
 
39
39
  const characteristicCurrentPosition = service.getCharacteristic(Characteristic.CurrentPosition)
40
40
  .updateValue(this.currentPosition)
41
- .onGet(() => this.currentPosition);
41
+ .onGet(() => { if (!this.device.connected) throw this._commError(); return this.currentPosition; });
42
42
 
43
43
  const characteristicTargetPosition = service.getCharacteristic(Characteristic.TargetPosition)
44
44
  .updateValue(this.currentPosition)
45
- .onGet(() => this.currentPosition)
45
+ .onGet(() => { if (!this.device.connected) throw this._commError(); return this.currentPosition; })
46
46
  .onSet(value => this.setPosition(value));
47
47
 
48
48
  const characteristicPositionState = service.getCharacteristic(Characteristic.PositionState)
49
49
  .updateValue(Characteristic.PositionState.STOPPED)
50
- .onGet(() => Characteristic.PositionState.STOPPED);
50
+ .onGet(() => { if (!this.device.connected) throw this._commError(); return Characteristic.PositionState.STOPPED; });
51
51
 
52
52
  const characteristicCurrentHorizontalTilt = service.getCharacteristic(Characteristic.CurrentHorizontalTiltAngle)
53
53
  .updateValue(this._getTiltAngle(dps[this.dpTiltState] || dps[this.dpTilt]))
@@ -76,6 +76,7 @@ class VerticalBlindsWithTilt extends BaseAccessory {
76
76
 
77
77
  setPosition(value) {
78
78
  const {Characteristic} = this.hap;
79
+ if (!this.device.connected) throw this._commError();
79
80
 
80
81
  if (value === 0) {
81
82
  if (this.currentPosition === 0) {
@@ -205,6 +206,7 @@ class VerticalBlindsWithTilt extends BaseAccessory {
205
206
  }
206
207
 
207
208
  setTiltAngle(value) {
209
+ if (!this.device.connected) throw this._commError();
208
210
  const tuyaValue = Math.round((value / 1.8) + 50);
209
211
  const clampedValue = Math.max(0, Math.min(100, tuyaValue));
210
212