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
package/index.js CHANGED
@@ -1,269 +1,536 @@
1
- const TuyaAccessory = require('./lib/TuyaAccessory');
2
- const TuyaDiscovery = require('./lib/TuyaDiscovery');
3
-
4
- const OutletAccessory = require('./lib/OutletAccessory');
5
- const SimpleLightAccessory = require('./lib/SimpleLightAccessory');
6
- const MultiOutletAccessory = require('./lib/MultiOutletAccessory');
7
- const CustomMultiOutletAccessory = require('./lib/CustomMultiOutletAccessory');
8
- const RGBTWLightAccessory = require('./lib/RGBTWLightAccessory');
9
- const RGBTWOutletAccessory = require('./lib/RGBTWOutletAccessory');
10
- const TWLightAccessory = require('./lib/TWLightAccessory');
11
- const AirConditionerAccessory = require('./lib/AirConditionerAccessory');
12
- const AirPurifierAccessory = require('./lib/AirPurifierAccessory');
13
- const DehumidifierAccessory = require('./lib/DehumidifierAccessory');
14
- const ConvectorAccessory = require('./lib/ConvectorAccessory');
15
- const GarageDoorAccessory = require('./lib/GarageDoorAccessory');
16
- const SimpleGarageDoorAccessory = require('./lib/SimpleGarageDoorAccessory');
17
- const WledDimmerAccessory = require('./lib/WledDimmerAccessory');
18
- const SimpleDimmer2Accessory = require('./lib/SimpleDimmer2Accessory');
19
- const SimpleBlindsAccessory = require('./lib/SimpleBlindsAccessory');
20
- const SimpleHeaterAccessory = require('./lib/SimpleHeaterAccessory');
21
- const SimpleFanAccessory = require('./lib/SimpleFanAccessory');
22
- const SimpleFanLightAccessory = require('./lib/SimpleFanLightAccessory');
23
- const SwitchAccessory = require('./lib/SwitchAccessory');
24
- const ValveAccessory = require('./lib/ValveAccessory');
25
- const IrrigationSystemAccessory = require('./lib/IrrigationSystemAccessory');
26
- const OilDiffuserAccessory = require('./lib/OilDiffuserAccessory');
27
- const DoorbellAccessory = require('./lib/DoorbellAccessory');
28
- const VerticalBlindsWithTilt = require('./lib/VerticalBlindsWithTilt');
29
- const PercentBlindsAccessory = require('./lib/PercentBlindsAccessory');
30
-
31
- const PLUGIN_NAME = 'homebridge-tuya-plus';
32
- const PLATFORM_NAME = 'TuyaLan';
33
- // Seed used to derive accessory UUIDs. Must remain 'homebridge-tuya' so that
34
- // devices already paired with HomeKit keep their existing identity (names,
35
- // rooms, automations).
36
- const UUID_SEED = 'homebridge-tuya';
37
- const DEFAULT_DISCOVER_TIMEOUT = 60000;
38
-
39
- const CLASS_DEF = {
40
- outlet: OutletAccessory,
41
- simplelight: SimpleLightAccessory,
42
- rgbtwlight: RGBTWLightAccessory,
43
- rgbtwoutlet: RGBTWOutletAccessory,
44
- twlight: TWLightAccessory,
45
- multioutlet: MultiOutletAccessory,
46
- custommultioutlet: CustomMultiOutletAccessory,
47
- airconditioner: AirConditionerAccessory,
48
- airpurifier: AirPurifierAccessory,
49
- dehumidifier: DehumidifierAccessory,
50
- convector: ConvectorAccessory,
51
- garagedoor: GarageDoorAccessory,
52
- simplegaragedoor: SimpleGarageDoorAccessory,
53
- simpledimmer: WledDimmerAccessory,
54
- wleddimmer: WledDimmerAccessory,
55
- simpledimmer2: SimpleDimmer2Accessory,
56
- simpleblinds: SimpleBlindsAccessory,
57
- simpleheater: SimpleHeaterAccessory,
58
- switch: SwitchAccessory,
59
- fan: SimpleFanAccessory,
60
- fanlight: SimpleFanLightAccessory,
61
- watervalve: ValveAccessory,
62
- irrigationsystem: IrrigationSystemAccessory,
63
- oildiffuser: OilDiffuserAccessory,
64
- doorbell: DoorbellAccessory,
65
- verticalblindswithtilt: VerticalBlindsWithTilt,
66
- percentblinds: PercentBlindsAccessory
67
- };
68
-
69
- let Characteristic, Formats, Perms, Categories, PlatformAccessory, Service, AdaptiveLightingController, UUID;
70
-
71
- module.exports = function(homebridge) {
72
- ({
73
- platformAccessory: PlatformAccessory,
74
- hap: {Characteristic, Formats, Perms, Categories, Service, AdaptiveLightingController, uuid: UUID}
75
- } = homebridge);
76
-
77
- homebridge.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, TuyaLan, true);
78
- };
79
-
80
- class TuyaLan {
81
- constructor(...props) {
82
- [this.log, this.config, this.api] = [...props];
83
-
84
- this.cachedAccessories = new Map();
85
- this.api.hap.EnergyCharacteristics = require('./lib/EnergyCharacteristics')(this.api.hap);
86
-
87
- if(!this.config || !this.config.devices) {
88
- this.log("No devices found. Check that you have specified them in your config.json file.");
89
- return false;
90
- }
91
-
92
- this._expectedUUIDs = this.config.devices.map(device => UUID.generate(UUID_SEED +(device.fake ? ':fake:' : ':') + device.id));
93
-
94
- this.api.on('didFinishLaunching', () => {
95
- this.discoverDevices();
96
- });
97
- }
98
-
99
- discoverDevices() {
100
- const devices = {};
101
- const connectedDevices = [];
102
- const fakeDevices = [];
103
- this.config.devices.forEach(device => {
104
- try {
105
- device.id = ('' + device.id).trim();
106
- device.key = ('' + device.key).trim();
107
- device.type = ('' + device.type).trim();
108
-
109
- device.ip = ('' + (device.ip || '')).trim();
110
- } catch(ex) {}
111
-
112
- if (!device.type) return this.log.error('%s (%s) doesn\'t have a type defined.', device.name || 'Unnamed device', device.id);
113
- if (!CLASS_DEF[device.type.toLowerCase()]) return this.log.error('%s (%s) doesn\'t have a valid type defined.', device.name || 'Unnamed device', device.id);
114
-
115
- if (device.fake) fakeDevices.push({name: device.id.slice(8), ...device});
116
- else devices[device.id] = {name: device.id.slice(8), ...device};
117
- });
118
-
119
- const deviceIds = Object.keys(devices);
120
- if (deviceIds.length === 0) return this.log.error('No valid configured devices found.');
121
-
122
- this.log.info('Starting discovery...');
123
-
124
- TuyaDiscovery.start({ids: deviceIds, log: this.log})
125
- .on('discover', config => {
126
- if (!config || !config.id) return;
127
- if (!devices[config.id]) return this.log.warn('Discovered a device that has not been configured yet (%s@%s).', config.id, config.ip);
128
-
129
- connectedDevices.push(config.id);
130
-
131
- this.log.info('Discovered %s (%s) identified as %s (%s)', devices[config.id].name, config.id, devices[config.id].type, config.version);
132
-
133
- // The version broadcast by the device wins over a configured `version`,
134
- // but `forceVersion` overrides everything (e.g. to pin a device that
135
- // reports a newer protocol, like 3.6, to a specific stack).
136
- const device = new TuyaAccessory({
137
- ...devices[config.id], ...config,
138
- ...(devices[config.id].forceVersion ? {version: devices[config.id].forceVersion} : {}),
139
- log: this.log,
140
- UUID: UUID.generate(UUID_SEED + ':' + config.id),
141
- connect: false
142
- });
143
- this.addAccessory(device);
144
- });
145
-
146
- fakeDevices.forEach(config => {
147
- this.log.info('Adding fake device: %s', config.name);
148
- this.addAccessory(new TuyaAccessory({
149
- ...config,
150
- log: this.log,
151
- UUID: UUID.generate(UUID_SEED + ':fake:' + config.id),
152
- connect: false
153
- }));
154
- });
155
-
156
- setTimeout(() => {
157
- deviceIds.forEach(deviceId => {
158
- if (connectedDevices.includes(deviceId)) return;
159
-
160
- if (devices[deviceId].ip) {
161
-
162
- this.log.info('Failed to discover %s (%s) in time but will connect via %s.', devices[deviceId].name, deviceId, devices[deviceId].ip);
163
-
164
- const device = new TuyaAccessory({
165
- ...devices[deviceId],
166
- ...(devices[deviceId].forceVersion ? {version: devices[deviceId].forceVersion} : {}),
167
- log: this.log,
168
- UUID: UUID.generate(UUID_SEED + ':' + deviceId),
169
- connect: false
170
- });
171
- this.addAccessory(device);
172
- } else {
173
- this.log.warn('Failed to discover %s (%s) in time but will keep looking.', devices[deviceId].name, deviceId);
174
- }
175
- });
176
- }, this.config.discoverTimeout ?? DEFAULT_DISCOVER_TIMEOUT);
177
- }
178
-
179
- registerPlatformAccessories(platformAccessories) {
180
- this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, Array.isArray(platformAccessories) ? platformAccessories : [platformAccessories]);
181
- }
182
-
183
- configureAccessory(accessory) {
184
- // also checks null objects or empty config - this._expectedUUIDs
185
- if (accessory instanceof PlatformAccessory && this._expectedUUIDs && this._expectedUUIDs.includes(accessory.UUID)) {
186
- this.cachedAccessories.set(accessory.UUID, accessory);
187
- accessory.services.forEach(service => {
188
- if (service.UUID === Service.AccessoryInformation.UUID) return;
189
- service.characteristics.some(characteristic => {
190
- if (!characteristic.props ||
191
- !Array.isArray(characteristic.props.perms) ||
192
- characteristic.props.perms.length !== 3 ||
193
- !(characteristic.props.perms.includes(Perms.WRITE) && characteristic.props.perms.includes(Perms.NOTIFY))
194
- ) return;
195
-
196
- this.log.info('Marked %s unreachable by faulting Service.%s.%s', accessory.displayName, service.displayName, characteristic.displayName);
197
-
198
- characteristic.updateValue(new Error('Unreachable'));
199
- return true;
200
- });
201
- });
202
- } else {
203
- /*
204
- * Irrespective of this unregistering, Homebridge continues
205
- * to "_prepareAssociatedHAPAccessory" and "addBridgedAccessory".
206
- * This timeout will hopefully remove the accessory after that has happened.
207
- */
208
- setTimeout(() => {
209
- this.removeAccessory(accessory);
210
- }, 1000);
211
- }
212
- }
213
-
214
- addAccessory(device) {
215
- const deviceConfig = device.context;
216
- const type = (deviceConfig.type || '').toLowerCase();
217
-
218
- const Accessory = CLASS_DEF[type];
219
-
220
- let accessory = this.cachedAccessories.get(deviceConfig.UUID),
221
- isCached = true;
222
-
223
- const expectedCategory = Accessory.getCategory(Categories);
224
-
225
- // Only treat a cached accessory as a "different type" when we actually
226
- // have a category to compare against. If getCategory() resolves to
227
- // undefined (e.g. an unknown HAP category constant), HomeKit stores the
228
- // accessory as Categories.OTHER, so an undefined expectation would never
229
- // match and we would needlessly unregister & recreate the accessory on
230
- // every restart — wiping its HomeKit identity (name, room, automations).
231
- if (accessory && expectedCategory !== undefined && accessory.category !== expectedCategory) {
232
- this.log.info("%s has a different type (%s vs %s)", accessory.displayName, accessory.category, expectedCategory);
233
- this.removeAccessory(accessory);
234
- accessory = null;
235
- }
236
-
237
- if (!accessory) {
238
- accessory = new PlatformAccessory(deviceConfig.name, deviceConfig.UUID, expectedCategory);
239
- accessory.getService(Service.AccessoryInformation)
240
- .setCharacteristic(Characteristic.Manufacturer, deviceConfig.manufacturer || "Unknown")
241
- .setCharacteristic(Characteristic.Model, deviceConfig.model || "Unknown")
242
- .setCharacteristic(Characteristic.SerialNumber, deviceConfig.id.slice(8));
243
-
244
- isCached = false;
245
- }
246
-
247
- if (accessory && accessory.displayName !== deviceConfig.name) {
248
- this.log.info(
249
- "Configuration name %s differs from cached displayName %s. Updating cached displayName to %s ",
250
- deviceConfig.name, accessory.displayName, deviceConfig.name);
251
- accessory.displayName = deviceConfig.name;
252
- }
253
-
254
- this.cachedAccessories.set(deviceConfig.UUID, new Accessory(this, accessory, device, !isCached));
255
- }
256
-
257
- removeAccessory(homebridgeAccessory) {
258
- if (!homebridgeAccessory) return;
259
-
260
- this.log.warn('Unregistering', homebridgeAccessory.displayName);
261
-
262
- delete this.cachedAccessories[homebridgeAccessory.UUID];
263
- this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [homebridgeAccessory]);
264
- }
265
-
266
- removeAccessoryByUUID(uuid) {
267
- if (uuid) this.removeAccessory(this.cachedAccessories.get(uuid));
268
- }
269
- }
1
+ const TuyaAccessory = require('./lib/TuyaAccessory');
2
+ const TuyaDevice = require('./lib/TuyaDevice');
3
+ const TuyaDiscovery = require('./lib/TuyaDiscovery');
4
+ const TuyaCloudApi = require('./lib/TuyaCloudApi');
5
+ const TuyaCloudMessaging = require('./lib/TuyaCloudMessaging');
6
+
7
+ const OutletAccessory = require('./lib/OutletAccessory');
8
+ const SimpleLightAccessory = require('./lib/SimpleLightAccessory');
9
+ const MultiOutletAccessory = require('./lib/MultiOutletAccessory');
10
+ const CustomMultiOutletAccessory = require('./lib/CustomMultiOutletAccessory');
11
+ const RGBTWLightAccessory = require('./lib/RGBTWLightAccessory');
12
+ const RGBTWOutletAccessory = require('./lib/RGBTWOutletAccessory');
13
+ const TWLightAccessory = require('./lib/TWLightAccessory');
14
+ const AirConditionerAccessory = require('./lib/AirConditionerAccessory');
15
+ const AirPurifierAccessory = require('./lib/AirPurifierAccessory');
16
+ const DehumidifierAccessory = require('./lib/DehumidifierAccessory');
17
+ const ConvectorAccessory = require('./lib/ConvectorAccessory');
18
+ const GarageDoorAccessory = require('./lib/GarageDoorAccessory');
19
+ const SimpleGarageDoorAccessory = require('./lib/SimpleGarageDoorAccessory');
20
+ const WledDimmerAccessory = require('./lib/WledDimmerAccessory');
21
+ const SimpleDimmerAccessory = require('./lib/SimpleDimmerAccessory');
22
+ const SimpleDimmer2Accessory = require('./lib/SimpleDimmer2Accessory');
23
+ const SimpleBlindsAccessory = require('./lib/SimpleBlindsAccessory');
24
+ const SimpleHeaterAccessory = require('./lib/SimpleHeaterAccessory');
25
+ const SimpleFanAccessory = require('./lib/SimpleFanAccessory');
26
+ const SimpleFanLightAccessory = require('./lib/SimpleFanLightAccessory');
27
+ const SwitchAccessory = require('./lib/SwitchAccessory');
28
+ const ValveAccessory = require('./lib/ValveAccessory');
29
+ const IrrigationSystemAccessory = require('./lib/IrrigationSystemAccessory');
30
+ const OilDiffuserAccessory = require('./lib/OilDiffuserAccessory');
31
+ const DoorbellAccessory = require('./lib/DoorbellAccessory');
32
+ const VerticalBlindsWithTilt = require('./lib/VerticalBlindsWithTilt');
33
+ const PercentBlindsAccessory = require('./lib/PercentBlindsAccessory');
34
+
35
+ const PLUGIN_NAME = 'homebridge-tuya-plus';
36
+ const PLATFORM_NAME = 'TuyaLan';
37
+ // Seed used to derive accessory UUIDs. Must remain 'homebridge-tuya' so that
38
+ // devices already paired with HomeKit keep their existing identity (names,
39
+ // rooms, automations).
40
+ const UUID_SEED = 'homebridge-tuya';
41
+ const DEFAULT_DISCOVER_TIMEOUT = 60000;
42
+
43
+ const CLASS_DEF = {
44
+ outlet: OutletAccessory,
45
+ simplelight: SimpleLightAccessory,
46
+ rgbtwlight: RGBTWLightAccessory,
47
+ rgbtwoutlet: RGBTWOutletAccessory,
48
+ twlight: TWLightAccessory,
49
+ multioutlet: MultiOutletAccessory,
50
+ custommultioutlet: CustomMultiOutletAccessory,
51
+ airconditioner: AirConditionerAccessory,
52
+ airpurifier: AirPurifierAccessory,
53
+ dehumidifier: DehumidifierAccessory,
54
+ convector: ConvectorAccessory,
55
+ garagedoor: GarageDoorAccessory,
56
+ simplegaragedoor: SimpleGarageDoorAccessory,
57
+ simpledimmer: SimpleDimmerAccessory,
58
+ wleddimmer: WledDimmerAccessory,
59
+ simpledimmer2: SimpleDimmer2Accessory,
60
+ simpleblinds: SimpleBlindsAccessory,
61
+ simpleheater: SimpleHeaterAccessory,
62
+ switch: SwitchAccessory,
63
+ fan: SimpleFanAccessory,
64
+ fanlight: SimpleFanLightAccessory,
65
+ watervalve: ValveAccessory,
66
+ irrigationsystem: IrrigationSystemAccessory,
67
+ oildiffuser: OilDiffuserAccessory,
68
+ doorbell: DoorbellAccessory,
69
+ verticalblindswithtilt: VerticalBlindsWithTilt,
70
+ percentblinds: PercentBlindsAccessory,
71
+ };
72
+
73
+ let Characteristic,
74
+ Formats,
75
+ Perms,
76
+ Categories,
77
+ PlatformAccessory,
78
+ Service,
79
+ AdaptiveLightingController,
80
+ UUID;
81
+
82
+ module.exports = function (homebridge) {
83
+ ({
84
+ platformAccessory: PlatformAccessory,
85
+ hap: {
86
+ Characteristic,
87
+ Formats,
88
+ Perms,
89
+ Categories,
90
+ Service,
91
+ AdaptiveLightingController,
92
+ uuid: UUID,
93
+ },
94
+ } = homebridge);
95
+
96
+ homebridge.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, TuyaLan, true);
97
+ };
98
+
99
+ class TuyaLan {
100
+ constructor(...props) {
101
+ [this.log, this.config, this.api] = [...props];
102
+
103
+ this.cachedAccessories = new Map();
104
+ // One TuyaDevice per configured device, keyed by Tuya id, so discovery can
105
+ // hand each its LAN target once it's found on the network.
106
+ this.tuyaDevices = new Map();
107
+ // A SINGLE shared Tuya Cloud session (OpenAPI token + realtime MQTT) for the
108
+ // whole platform — the global fallback every device can lean on. Stays null
109
+ // unless cloud credentials are configured.
110
+ this.cloudApi = null;
111
+ this.cloudMessaging = null;
112
+ this.api.hap.EnergyCharacteristics = require('./lib/EnergyCharacteristics')(
113
+ this.api.hap,
114
+ );
115
+
116
+ if (!this.config || !this.config.devices) {
117
+ this.log(
118
+ 'No devices found. Check that you have specified them in your config.json file.',
119
+ );
120
+ return false;
121
+ }
122
+
123
+ this._expectedUUIDs = this.config.devices.map((device) =>
124
+ UUID.generate(UUID_SEED + (device.fake ? ':fake:' : ':') + device.id),
125
+ );
126
+
127
+ this.api.on('didFinishLaunching', () => {
128
+ this.discoverDevices();
129
+ });
130
+ }
131
+
132
+ discoverDevices() {
133
+ // Bring up the single shared cloud session first, so every device that opts
134
+ // into (or falls back to) the cloud shares one token and one MQTT stream.
135
+ this._setupCloudSession();
136
+
137
+ const lanDeviceIds = []; // ids we still want to find on the LAN
138
+ const connectedDevices = []; // ids discovered on the LAN
139
+ const fakeDevices = [];
140
+ const seenUUIDs = new Set(); // accessory UUIDs already configured this run
141
+
142
+ this.config.devices.forEach((device) => {
143
+ try {
144
+ device.id = ('' + device.id).trim();
145
+ // Cloud-only devices don't need a local key; only trim when present.
146
+ if (device.key != null) device.key = ('' + device.key).trim();
147
+ device.type = ('' + device.type).trim();
148
+
149
+ device.ip = ('' + (device.ip || '')).trim();
150
+ } catch (ex) {}
151
+
152
+ if (!device.type)
153
+ return this.log.error(
154
+ "%s (%s) doesn't have a type defined.",
155
+ device.name || 'Unnamed device',
156
+ device.id,
157
+ );
158
+ if (!CLASS_DEF[device.type.toLowerCase()])
159
+ return this.log.error(
160
+ "%s (%s) doesn't have a valid type defined.",
161
+ device.name || 'Unnamed device',
162
+ device.id,
163
+ );
164
+
165
+ // Two config entries that resolve to the same accessory UUID (the same
166
+ // Tuya id, real or fake) make addAccessory process that UUID twice. The
167
+ // second pass reads back the accessory wrapper the first pass cached
168
+ // instead of a PlatformAccessory and crashes the child bridge while
169
+ // trying to unregister it. Keep the first entry; skip the rest.
170
+ const uuid = UUID.generate(
171
+ UUID_SEED + (device.fake ? ':fake:' : ':') + device.id,
172
+ );
173
+ if (seenUUIDs.has(uuid))
174
+ return this.log.warn(
175
+ '%s (%s) is configured more than once; ignoring the duplicate entry.',
176
+ device.name || 'Unnamed device',
177
+ device.id,
178
+ );
179
+ seenUUIDs.add(uuid);
180
+
181
+ if (device.fake) {
182
+ fakeDevices.push({ name: device.id.slice(8), ...device });
183
+ return;
184
+ }
185
+
186
+ const tuyaDevice = this._createDevice({
187
+ name: device.id.slice(8),
188
+ ...device,
189
+ });
190
+ this.tuyaDevices.set(device.id, tuyaDevice);
191
+ this.addAccessory(tuyaDevice);
192
+
193
+ // A device with a local key can be reached on the LAN, so it wants
194
+ // discovery; the cloud, when configured, is its fallback. A device with
195
+ // no key is cloud-only (e.g. a battery-powered "sleepy" unit) and relies
196
+ // on the cloud session to be reachable at all.
197
+ if (device.key) lanDeviceIds.push(device.id);
198
+ else if (!this.cloudApi)
199
+ this.log.error(
200
+ '%s (%s) has no local key and no Tuya Cloud session is configured, so it can\'t be reached. Add a key for LAN control, or a top-level "cloud" block.',
201
+ tuyaDevice.context.name,
202
+ device.id,
203
+ );
204
+ });
205
+
206
+ fakeDevices.forEach((config) => {
207
+ this.log.info('Adding fake device: %s', config.name);
208
+ this.addAccessory(
209
+ new TuyaAccessory({
210
+ ...config,
211
+ log: this.log,
212
+ UUID: UUID.generate(UUID_SEED + ':fake:' + config.id),
213
+ connect: false,
214
+ }),
215
+ );
216
+ });
217
+
218
+ if (lanDeviceIds.length === 0) {
219
+ if (this.tuyaDevices.size === 0 && fakeDevices.length === 0)
220
+ this.log.error('No valid configured devices found.');
221
+ return; // cloud-only (or empty) configuration: nothing to discover over the LAN
222
+ }
223
+
224
+ this.log.info('Starting discovery...');
225
+
226
+ TuyaDiscovery.start({ ids: lanDeviceIds, log: this.log }).on(
227
+ 'discover',
228
+ (config) => {
229
+ if (!config || !config.id) return;
230
+ const tuyaDevice = this.tuyaDevices.get(config.id);
231
+ if (!tuyaDevice) return this._warnUnconfiguredDevice(config);
232
+ if (connectedDevices.includes(config.id)) return;
233
+
234
+ connectedDevices.push(config.id);
235
+
236
+ this.log.info(
237
+ 'Discovered %s (%s) identified as %s (%s)',
238
+ tuyaDevice.context.name,
239
+ config.id,
240
+ tuyaDevice.context.type,
241
+ config.version,
242
+ );
243
+
244
+ // The version broadcast by the device wins over a configured `version`,
245
+ // but `forceVersion` overrides everything; attachLan applies that order.
246
+ tuyaDevice.attachLan({ ip: config.ip, version: config.version });
247
+ },
248
+ );
249
+
250
+ setTimeout(() => {
251
+ lanDeviceIds.forEach((deviceId) => {
252
+ if (connectedDevices.includes(deviceId)) return;
253
+
254
+ const tuyaDevice = this.tuyaDevices.get(deviceId);
255
+ if (!tuyaDevice) return;
256
+
257
+ if (tuyaDevice.context.ip) {
258
+ this.log.info(
259
+ 'Failed to discover %s (%s) in time but will connect via %s.',
260
+ tuyaDevice.context.name,
261
+ deviceId,
262
+ tuyaDevice.context.ip,
263
+ );
264
+ tuyaDevice.attachLan({ ip: tuyaDevice.context.ip });
265
+ } else if (tuyaDevice.cloud) {
266
+ this.log.info(
267
+ 'Failed to discover %s (%s) on the LAN; it will run over the Tuya Cloud fallback.',
268
+ tuyaDevice.context.name,
269
+ deviceId,
270
+ );
271
+ } else {
272
+ this.log.warn(
273
+ 'Failed to discover %s (%s) in time but will keep looking.',
274
+ tuyaDevice.context.name,
275
+ deviceId,
276
+ );
277
+ }
278
+ });
279
+ }, this.config.discoverTimeout ?? DEFAULT_DISCOVER_TIMEOUT);
280
+ }
281
+
282
+ // A device showed up on the LAN that isn't in the user's config. When the
283
+ // optional cloud session is available we look the device up there first, so
284
+ // the warning can name it (and hint at its product/category) and the user
285
+ // can tell which physical device still needs configuring — far more useful
286
+ // than a bare id@ip. If there's no cloud session, or the lookup fails (the
287
+ // device belongs to another account, the device-management API isn't
288
+ // authorised, the network is down, …), fall back to the plain warning.
289
+ // Never throws: enrichment is best-effort and must not disrupt discovery.
290
+ async _warnUnconfiguredDevice(config) {
291
+ const bareWarning = () =>
292
+ this.log.warn(
293
+ 'Discovered a device that has not been configured yet (%s@%s).',
294
+ config.id,
295
+ config.ip,
296
+ );
297
+
298
+ if (!this.cloudApi) return bareWarning();
299
+
300
+ let info;
301
+ try {
302
+ info = await this.cloudApi.getDeviceInfo(config.id);
303
+ } catch (ex) {
304
+ this.log.debug(
305
+ 'Tuya Cloud lookup for unconfigured device %s failed: %s',
306
+ config.id,
307
+ ex.message,
308
+ );
309
+ }
310
+ if (!info || !info.name) return bareWarning();
311
+
312
+ const details = [];
313
+ if (info.product_name) details.push(info.product_name);
314
+ if (info.category) details.push(`category ${info.category}`);
315
+
316
+ this.log.warn(
317
+ 'Discovered a device that has not been configured yet: %s%s (%s@%s).',
318
+ `"${info.name}"`,
319
+ details.length ? ` — ${details.join(', ')}` : '',
320
+ config.id,
321
+ config.ip,
322
+ );
323
+ }
324
+
325
+ /* ------------------------------------------------------------------ *
326
+ * Tuya Cloud — a single, global fallback session.
327
+ *
328
+ * This plugin stays LAN-first: every device is controlled locally when it
329
+ * can be. When a top-level `cloud` block is configured, the plugin keeps one
330
+ * shared Tuya Cloud session alive in the background, and every device gains a
331
+ * transparent cloud fallback for the moments the LAN can't be reached (a
332
+ * flaky connection, or a battery-powered "sleepy" device that never appears
333
+ * on the LAN at all). It's all opt-in — without `cloud`, nothing here runs.
334
+ * ------------------------------------------------------------------ */
335
+
336
+ _setupCloudSession() {
337
+ const cloudCfg =
338
+ this.config.cloud && typeof this.config.cloud === 'object'
339
+ ? this.config.cloud
340
+ : null;
341
+ if (!cloudCfg) return; // no cloud block: the plugin runs purely on the LAN
342
+
343
+ if (!cloudCfg.accessId || !cloudCfg.accessKey) {
344
+ return this.log.error(
345
+ 'A "cloud" block is present but is missing accessId/accessKey, so the Tuya Cloud fallback is disabled. See the wiki: Tuya Cloud Setup.',
346
+ );
347
+ }
348
+
349
+ this.cloudApi = new TuyaCloudApi({ ...cloudCfg, log: this.log });
350
+ this.cloudMessaging = new TuyaCloudMessaging({
351
+ api: this.cloudApi,
352
+ log: this.log,
353
+ });
354
+
355
+ this.log.info(
356
+ 'Tuya Cloud fallback enabled via %s.',
357
+ this.cloudApi.endpoint,
358
+ );
359
+ }
360
+
361
+ _createDevice(device) {
362
+ // The one shared cloud session, when configured, backs every device as its
363
+ // fallback. There is no per-device cloud configuration.
364
+ const usesCloud = !!this.cloudApi;
365
+ return new TuyaDevice({
366
+ ...device,
367
+ cloudApi: usesCloud ? this.cloudApi : undefined,
368
+ messaging: usesCloud ? this.cloudMessaging : undefined,
369
+ cloudStartDelay: usesCloud ? this._nextCloudStartDelay() : 0,
370
+ log: this.log,
371
+ UUID: UUID.generate(UUID_SEED + ':' + device.id),
372
+ connect: false,
373
+ });
374
+ }
375
+
376
+ // Spread the cloud devices' first reads over a few seconds so a large install
377
+ // doesn't fire dozens of OpenAPI calls at once and trip Tuya's per-second rate
378
+ // limit at startup.
379
+ _nextCloudStartDelay() {
380
+ this._cloudStartCount = (this._cloudStartCount || 0) + 1;
381
+ return Math.min(15000, (this._cloudStartCount - 1) * 300);
382
+ }
383
+
384
+ registerPlatformAccessories(platformAccessories) {
385
+ this.api.registerPlatformAccessories(
386
+ PLUGIN_NAME,
387
+ PLATFORM_NAME,
388
+ Array.isArray(platformAccessories)
389
+ ? platformAccessories
390
+ : [platformAccessories],
391
+ );
392
+ }
393
+
394
+ configureAccessory(accessory) {
395
+ // also checks null objects or empty config - this._expectedUUIDs
396
+ if (
397
+ accessory instanceof PlatformAccessory &&
398
+ this._expectedUUIDs &&
399
+ this._expectedUUIDs.includes(accessory.UUID)
400
+ ) {
401
+ this.cachedAccessories.set(accessory.UUID, accessory);
402
+ accessory.services.forEach((service) => {
403
+ if (service.UUID === Service.AccessoryInformation.UUID) return;
404
+ service.characteristics.some((characteristic) => {
405
+ if (
406
+ !characteristic.props ||
407
+ !Array.isArray(characteristic.props.perms) ||
408
+ characteristic.props.perms.length !== 3 ||
409
+ !(
410
+ characteristic.props.perms.includes(Perms.WRITE) &&
411
+ characteristic.props.perms.includes(Perms.NOTIFY)
412
+ )
413
+ )
414
+ return;
415
+
416
+ this.log.info(
417
+ 'Marked %s unreachable by faulting Service.%s.%s',
418
+ accessory.displayName,
419
+ service.displayName,
420
+ characteristic.displayName,
421
+ );
422
+
423
+ characteristic.updateValue(new Error('Unreachable'));
424
+ return true;
425
+ });
426
+ });
427
+ } else {
428
+ /*
429
+ * Irrespective of this unregistering, Homebridge continues
430
+ * to "_prepareAssociatedHAPAccessory" and "addBridgedAccessory".
431
+ * This timeout will hopefully remove the accessory after that has happened.
432
+ */
433
+ setTimeout(() => {
434
+ this.removeAccessory(accessory);
435
+ }, 1000);
436
+ }
437
+ }
438
+
439
+ addAccessory(device) {
440
+ const deviceConfig = device.context;
441
+ const type = (deviceConfig.type || '').toLowerCase();
442
+
443
+ const Accessory = CLASS_DEF[type];
444
+
445
+ let accessory = this.cachedAccessories.get(deviceConfig.UUID),
446
+ isCached = true;
447
+
448
+ const expectedCategory = Accessory.getCategory(Categories);
449
+
450
+ // Only treat a cached accessory as a "different type" when we actually
451
+ // have a category to compare against. If getCategory() resolves to
452
+ // undefined (e.g. an unknown HAP category constant), HomeKit stores the
453
+ // accessory as Categories.OTHER, so an undefined expectation would never
454
+ // match and we would needlessly unregister & recreate the accessory on
455
+ // every restart — wiping its HomeKit identity (name, room, automations).
456
+ if (
457
+ accessory &&
458
+ expectedCategory !== undefined &&
459
+ accessory.category !== expectedCategory
460
+ ) {
461
+ this.log.info(
462
+ '%s has a different type (%s vs %s)',
463
+ accessory.displayName,
464
+ accessory.category,
465
+ expectedCategory,
466
+ );
467
+ this.removeAccessory(accessory);
468
+ accessory = null;
469
+ }
470
+
471
+ if (!accessory) {
472
+ accessory = new PlatformAccessory(
473
+ deviceConfig.name,
474
+ deviceConfig.UUID,
475
+ expectedCategory,
476
+ );
477
+ accessory
478
+ .getService(Service.AccessoryInformation)
479
+ .setCharacteristic(
480
+ Characteristic.Manufacturer,
481
+ deviceConfig.manufacturer || 'Unknown',
482
+ )
483
+ .setCharacteristic(
484
+ Characteristic.Model,
485
+ deviceConfig.model || 'Unknown',
486
+ )
487
+ .setCharacteristic(
488
+ Characteristic.SerialNumber,
489
+ deviceConfig.id.slice(8),
490
+ );
491
+
492
+ isCached = false;
493
+ }
494
+
495
+ if (accessory && accessory.displayName !== deviceConfig.name) {
496
+ this.log.info(
497
+ 'Configuration name %s differs from cached displayName %s. Updating cached displayName to %s ',
498
+ deviceConfig.name,
499
+ accessory.displayName,
500
+ deviceConfig.name,
501
+ );
502
+ accessory.displayName = deviceConfig.name;
503
+ }
504
+
505
+ this.cachedAccessories.set(
506
+ deviceConfig.UUID,
507
+ new Accessory(this, accessory, device, !isCached),
508
+ );
509
+ }
510
+
511
+ removeAccessory(homebridgeAccessory) {
512
+ if (!homebridgeAccessory) return;
513
+
514
+ // Only real PlatformAccessory instances can be unregistered. cachedAccessories
515
+ // also holds accessory wrappers (set by addAccessory), and Homebridge throws a
516
+ // fatal TypeError when handed anything else, taking down the whole child bridge.
517
+ // Guard against it rather than trust every caller.
518
+ if (!(homebridgeAccessory instanceof PlatformAccessory)) {
519
+ return this.log.warn(
520
+ 'Skipped unregistering %s: not a PlatformAccessory.',
521
+ homebridgeAccessory.displayName,
522
+ );
523
+ }
524
+
525
+ this.log.warn('Unregistering', homebridgeAccessory.displayName);
526
+
527
+ this.cachedAccessories.delete(homebridgeAccessory.UUID);
528
+ this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
529
+ homebridgeAccessory,
530
+ ]);
531
+ }
532
+
533
+ removeAccessoryByUUID(uuid) {
534
+ if (uuid) this.removeAccessory(this.cachedAccessories.get(uuid));
535
+ }
536
+ }