homebridge-tuya-plus 3.14.0-dev.19 → 3.14.0-dev.21

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/index.js CHANGED
@@ -1,359 +1,349 @@
1
- const TuyaAccessory = require('./lib/TuyaAccessory');
2
- const TuyaDiscovery = require('./lib/TuyaDiscovery');
3
- const TuyaCloudApi = require('./lib/TuyaCloudApi');
4
- const TuyaCloudDevice = require('./lib/TuyaCloudDevice');
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
- // Lenient boolean coercion (matches BaseAccessory._coerceBoolean) so config
44
- // values like true / "true" / 1 all read as true.
45
- const coerceBoolean = (b, df = false) =>
46
- typeof b === 'boolean' ? b :
47
- typeof b === 'string' ? b.toLowerCase().trim() === 'true' :
48
- typeof b === 'number' ? b !== 0 : df;
49
-
50
- const CLASS_DEF = {
51
- outlet: OutletAccessory,
52
- simplelight: SimpleLightAccessory,
53
- rgbtwlight: RGBTWLightAccessory,
54
- rgbtwoutlet: RGBTWOutletAccessory,
55
- twlight: TWLightAccessory,
56
- multioutlet: MultiOutletAccessory,
57
- custommultioutlet: CustomMultiOutletAccessory,
58
- airconditioner: AirConditionerAccessory,
59
- airpurifier: AirPurifierAccessory,
60
- dehumidifier: DehumidifierAccessory,
61
- convector: ConvectorAccessory,
62
- garagedoor: GarageDoorAccessory,
63
- simplegaragedoor: SimpleGarageDoorAccessory,
64
- simpledimmer: SimpleDimmerAccessory,
65
- wleddimmer: WledDimmerAccessory,
66
- simpledimmer2: SimpleDimmer2Accessory,
67
- simpleblinds: SimpleBlindsAccessory,
68
- simpleheater: SimpleHeaterAccessory,
69
- switch: SwitchAccessory,
70
- fan: SimpleFanAccessory,
71
- fanlight: SimpleFanLightAccessory,
72
- watervalve: ValveAccessory,
73
- irrigationsystem: IrrigationSystemAccessory,
74
- oildiffuser: OilDiffuserAccessory,
75
- doorbell: DoorbellAccessory,
76
- verticalblindswithtilt: VerticalBlindsWithTilt,
77
- percentblinds: PercentBlindsAccessory
78
- };
79
-
80
- let Characteristic, Formats, Perms, Categories, PlatformAccessory, Service, AdaptiveLightingController, UUID;
81
-
82
- module.exports = function(homebridge) {
83
- ({
84
- platformAccessory: PlatformAccessory,
85
- hap: {Characteristic, Formats, Perms, Categories, Service, AdaptiveLightingController, uuid: UUID}
86
- } = homebridge);
87
-
88
- homebridge.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, TuyaLan, true);
89
- };
90
-
91
- class TuyaLan {
92
- constructor(...props) {
93
- [this.log, this.config, this.api] = [...props];
94
-
95
- this.cachedAccessories = new Map();
96
- // Shared Tuya Cloud clients, keyed by credential set, so several
97
- // cloud devices on the same project share one token + one realtime
98
- // (MQTT) connection. Empty unless cloud devices are configured.
99
- this.cloudApis = new Map();
100
- this.cloudMessagers = new Map();
101
- this.api.hap.EnergyCharacteristics = require('./lib/EnergyCharacteristics')(this.api.hap);
102
-
103
- if(!this.config || !this.config.devices) {
104
- this.log("No devices found. Check that you have specified them in your config.json file.");
105
- return false;
106
- }
107
-
108
- this._expectedUUIDs = this.config.devices.map(device => UUID.generate(UUID_SEED +(device.fake ? ':fake:' : ':') + device.id));
109
-
110
- this.api.on('didFinishLaunching', () => {
111
- this.discoverDevices();
112
- });
113
- }
114
-
115
- discoverDevices() {
116
- const devices = {};
117
- const connectedDevices = [];
118
- const fakeDevices = [];
119
- const cloudDevices = [];
120
- this.config.devices.forEach(device => {
121
- try {
122
- device.id = ('' + device.id).trim();
123
- // Cloud devices don't need a local key; only trim when present.
124
- if (device.key != null) device.key = ('' + device.key).trim();
125
- device.type = ('' + device.type).trim();
126
-
127
- device.ip = ('' + (device.ip || '')).trim();
128
- } catch(ex) {}
129
-
130
- if (!device.type) return this.log.error('%s (%s) doesn\'t have a type defined.', device.name || 'Unnamed device', device.id);
131
- 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);
132
-
133
- if (this._isCloudDevice(device)) cloudDevices.push({name: device.id.slice(8), ...device});
134
- else if (device.fake) fakeDevices.push({name: device.id.slice(8), ...device});
135
- else devices[device.id] = {name: device.id.slice(8), ...device};
136
- });
137
-
138
- // Cloud devices are reached over the internet, not the LAN, so they need
139
- // no discovery — wire them up right away.
140
- cloudDevices.forEach(config => this._addCloudAccessory(config));
141
-
142
- const deviceIds = Object.keys(devices);
143
- if (deviceIds.length === 0) {
144
- if (cloudDevices.length === 0) this.log.error('No valid configured devices found.');
145
- return; // cloud-only (or empty) configuration: nothing to discover over LAN
146
- }
147
-
148
- this.log.info('Starting discovery...');
149
-
150
- TuyaDiscovery.start({ids: deviceIds, log: this.log})
151
- .on('discover', config => {
152
- if (!config || !config.id) return;
153
- if (!devices[config.id]) return this.log.warn('Discovered a device that has not been configured yet (%s@%s).', config.id, config.ip);
154
-
155
- connectedDevices.push(config.id);
156
-
157
- this.log.info('Discovered %s (%s) identified as %s (%s)', devices[config.id].name, config.id, devices[config.id].type, config.version);
158
-
159
- // The version broadcast by the device wins over a configured `version`,
160
- // but `forceVersion` overrides everything (e.g. to pin a device that
161
- // reports a newer protocol, like 3.6, to a specific stack).
162
- const device = new TuyaAccessory({
163
- ...devices[config.id], ...config,
164
- ...(devices[config.id].forceVersion ? {version: devices[config.id].forceVersion} : {}),
165
- log: this.log,
166
- UUID: UUID.generate(UUID_SEED + ':' + config.id),
167
- connect: false
168
- });
169
- this.addAccessory(device);
170
- });
171
-
172
- fakeDevices.forEach(config => {
173
- this.log.info('Adding fake device: %s', config.name);
174
- this.addAccessory(new TuyaAccessory({
175
- ...config,
176
- log: this.log,
177
- UUID: UUID.generate(UUID_SEED + ':fake:' + config.id),
178
- connect: false
179
- }));
180
- });
181
-
182
- setTimeout(() => {
183
- deviceIds.forEach(deviceId => {
184
- if (connectedDevices.includes(deviceId)) return;
185
-
186
- if (devices[deviceId].ip) {
187
-
188
- this.log.info('Failed to discover %s (%s) in time but will connect via %s.', devices[deviceId].name, deviceId, devices[deviceId].ip);
189
-
190
- const device = new TuyaAccessory({
191
- ...devices[deviceId],
192
- ...(devices[deviceId].forceVersion ? {version: devices[deviceId].forceVersion} : {}),
193
- log: this.log,
194
- UUID: UUID.generate(UUID_SEED + ':' + deviceId),
195
- connect: false
196
- });
197
- this.addAccessory(device);
198
- } else {
199
- this.log.warn('Failed to discover %s (%s) in time but will keep looking.', devices[deviceId].name, deviceId);
200
- }
201
- });
202
- }, this.config.discoverTimeout ?? DEFAULT_DISCOVER_TIMEOUT);
203
- }
204
-
205
- /* ------------------------------------------------------------------ *
206
- * Tuya Cloud helpers (for devices that can't be reached over the LAN,
207
- * e.g. battery-powered "sleepy" irrigation timers). This plugin stays
208
- * LAN-first; these paths are only exercised by devices opting in with
209
- * `cloud: true` (or a per-device `cloud` credentials object).
210
- * ------------------------------------------------------------------ */
211
-
212
- _isCloudDevice(device) {
213
- return !!(device && (device.cloud === true || (typeof device.cloud === 'object' && device.cloud)));
214
- }
215
-
216
- // Effective cloud credentials/options for a device: the platform-level
217
- // `cloud` block, overlaid with any per-device `cloud` object.
218
- _resolveCloudConfig(device) {
219
- const platform = (this.config.cloud && typeof this.config.cloud === 'object') ? this.config.cloud : {};
220
- const perDevice = (typeof device.cloud === 'object' && device.cloud) ? device.cloud : {};
221
- return {...platform, ...perDevice};
222
- }
223
-
224
- // One TuyaCloudApi per credential set, so multiple cloud devices on the
225
- // same Tuya project share a single token.
226
- _getCloudApi(cloudCfg) {
227
- const key = TuyaCloudApi.keyFor(cloudCfg);
228
- if (!this.cloudApis.has(key)) {
229
- this.cloudApis.set(key, new TuyaCloudApi({...cloudCfg, log: this.log}));
230
- }
231
- return this.cloudApis.get(key);
232
- }
233
-
234
- // One shared realtime (MQTT) stream per credential set, unless realtime is
235
- // disabled. Returns null when realtime is off — the device then shows its
236
- // initial state and stays controllable, but won't receive live updates.
237
- _getCloudMessaging(api, cloudCfg) {
238
- const realtime = cloudCfg.realtime === undefined ? true : coerceBoolean(cloudCfg.realtime, true);
239
- if (!realtime) return null;
240
- const key = TuyaCloudApi.keyFor(cloudCfg);
241
- if (!this.cloudMessagers.has(key)) {
242
- this.cloudMessagers.set(key, new TuyaCloudMessaging({api, log: this.log}));
243
- }
244
- return this.cloudMessagers.get(key);
245
- }
246
-
247
- _addCloudAccessory(config) {
248
- const cloudCfg = this._resolveCloudConfig(config);
249
- if (!cloudCfg.accessId || !cloudCfg.accessKey) {
250
- return this.log.error('%s (%s) is configured for the Tuya Cloud, but no credentials were found. Add a top-level "cloud" block (accessId, accessKey, region) or a per-device "cloud" object.', config.name, config.id);
251
- }
252
-
253
- const api = this._getCloudApi(cloudCfg);
254
- const messaging = this._getCloudMessaging(api, cloudCfg);
255
-
256
- this.log.info('Adding cloud device: %s (%s) via %s', config.name, config.id, api.endpoint);
257
-
258
- this.addAccessory(new TuyaCloudDevice({
259
- ...config,
260
- cloud: true, // normalise so accessories can detect cloud mode
261
- cloudApi: api,
262
- messaging,
263
- log: this.log,
264
- UUID: UUID.generate(UUID_SEED + ':' + config.id),
265
- connect: false
266
- }));
267
- }
268
-
269
- registerPlatformAccessories(platformAccessories) {
270
- this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, Array.isArray(platformAccessories) ? platformAccessories : [platformAccessories]);
271
- }
272
-
273
- configureAccessory(accessory) {
274
- // also checks null objects or empty config - this._expectedUUIDs
275
- if (accessory instanceof PlatformAccessory && this._expectedUUIDs && this._expectedUUIDs.includes(accessory.UUID)) {
276
- this.cachedAccessories.set(accessory.UUID, accessory);
277
- accessory.services.forEach(service => {
278
- if (service.UUID === Service.AccessoryInformation.UUID) return;
279
- service.characteristics.some(characteristic => {
280
- if (!characteristic.props ||
281
- !Array.isArray(characteristic.props.perms) ||
282
- characteristic.props.perms.length !== 3 ||
283
- !(characteristic.props.perms.includes(Perms.WRITE) && characteristic.props.perms.includes(Perms.NOTIFY))
284
- ) return;
285
-
286
- this.log.info('Marked %s unreachable by faulting Service.%s.%s', accessory.displayName, service.displayName, characteristic.displayName);
287
-
288
- characteristic.updateValue(new Error('Unreachable'));
289
- return true;
290
- });
291
- });
292
- } else {
293
- /*
294
- * Irrespective of this unregistering, Homebridge continues
295
- * to "_prepareAssociatedHAPAccessory" and "addBridgedAccessory".
296
- * This timeout will hopefully remove the accessory after that has happened.
297
- */
298
- setTimeout(() => {
299
- this.removeAccessory(accessory);
300
- }, 1000);
301
- }
302
- }
303
-
304
- addAccessory(device) {
305
- const deviceConfig = device.context;
306
- const type = (deviceConfig.type || '').toLowerCase();
307
-
308
- const Accessory = CLASS_DEF[type];
309
-
310
- let accessory = this.cachedAccessories.get(deviceConfig.UUID),
311
- isCached = true;
312
-
313
- const expectedCategory = Accessory.getCategory(Categories);
314
-
315
- // Only treat a cached accessory as a "different type" when we actually
316
- // have a category to compare against. If getCategory() resolves to
317
- // undefined (e.g. an unknown HAP category constant), HomeKit stores the
318
- // accessory as Categories.OTHER, so an undefined expectation would never
319
- // match and we would needlessly unregister & recreate the accessory on
320
- // every restart — wiping its HomeKit identity (name, room, automations).
321
- if (accessory && expectedCategory !== undefined && accessory.category !== expectedCategory) {
322
- this.log.info("%s has a different type (%s vs %s)", accessory.displayName, accessory.category, expectedCategory);
323
- this.removeAccessory(accessory);
324
- accessory = null;
325
- }
326
-
327
- if (!accessory) {
328
- accessory = new PlatformAccessory(deviceConfig.name, deviceConfig.UUID, expectedCategory);
329
- accessory.getService(Service.AccessoryInformation)
330
- .setCharacteristic(Characteristic.Manufacturer, deviceConfig.manufacturer || "Unknown")
331
- .setCharacteristic(Characteristic.Model, deviceConfig.model || "Unknown")
332
- .setCharacteristic(Characteristic.SerialNumber, deviceConfig.id.slice(8));
333
-
334
- isCached = false;
335
- }
336
-
337
- if (accessory && accessory.displayName !== deviceConfig.name) {
338
- this.log.info(
339
- "Configuration name %s differs from cached displayName %s. Updating cached displayName to %s ",
340
- deviceConfig.name, accessory.displayName, deviceConfig.name);
341
- accessory.displayName = deviceConfig.name;
342
- }
343
-
344
- this.cachedAccessories.set(deviceConfig.UUID, new Accessory(this, accessory, device, !isCached));
345
- }
346
-
347
- removeAccessory(homebridgeAccessory) {
348
- if (!homebridgeAccessory) return;
349
-
350
- this.log.warn('Unregistering', homebridgeAccessory.displayName);
351
-
352
- delete this.cachedAccessories[homebridgeAccessory.UUID];
353
- this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [homebridgeAccessory]);
354
- }
355
-
356
- removeAccessoryByUUID(uuid) {
357
- if (uuid) this.removeAccessory(this.cachedAccessories.get(uuid));
358
- }
359
- }
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
+ // Lenient boolean coercion (matches BaseAccessory._coerceBoolean) so config
44
+ // values like true / "true" / 1 all read as true.
45
+ const coerceBoolean = (b, df = false) =>
46
+ typeof b === 'boolean' ? b :
47
+ typeof b === 'string' ? b.toLowerCase().trim() === 'true' :
48
+ typeof b === 'number' ? b !== 0 : df;
49
+
50
+ const CLASS_DEF = {
51
+ outlet: OutletAccessory,
52
+ simplelight: SimpleLightAccessory,
53
+ rgbtwlight: RGBTWLightAccessory,
54
+ rgbtwoutlet: RGBTWOutletAccessory,
55
+ twlight: TWLightAccessory,
56
+ multioutlet: MultiOutletAccessory,
57
+ custommultioutlet: CustomMultiOutletAccessory,
58
+ airconditioner: AirConditionerAccessory,
59
+ airpurifier: AirPurifierAccessory,
60
+ dehumidifier: DehumidifierAccessory,
61
+ convector: ConvectorAccessory,
62
+ garagedoor: GarageDoorAccessory,
63
+ simplegaragedoor: SimpleGarageDoorAccessory,
64
+ simpledimmer: SimpleDimmerAccessory,
65
+ wleddimmer: WledDimmerAccessory,
66
+ simpledimmer2: SimpleDimmer2Accessory,
67
+ simpleblinds: SimpleBlindsAccessory,
68
+ simpleheater: SimpleHeaterAccessory,
69
+ switch: SwitchAccessory,
70
+ fan: SimpleFanAccessory,
71
+ fanlight: SimpleFanLightAccessory,
72
+ watervalve: ValveAccessory,
73
+ irrigationsystem: IrrigationSystemAccessory,
74
+ oildiffuser: OilDiffuserAccessory,
75
+ doorbell: DoorbellAccessory,
76
+ verticalblindswithtilt: VerticalBlindsWithTilt,
77
+ percentblinds: PercentBlindsAccessory
78
+ };
79
+
80
+ let Characteristic, Formats, Perms, Categories, PlatformAccessory, Service, AdaptiveLightingController, UUID;
81
+
82
+ module.exports = function(homebridge) {
83
+ ({
84
+ platformAccessory: PlatformAccessory,
85
+ hap: {Characteristic, Formats, Perms, Categories, Service, AdaptiveLightingController, uuid: UUID}
86
+ } = homebridge);
87
+
88
+ homebridge.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, TuyaLan, true);
89
+ };
90
+
91
+ class TuyaLan {
92
+ constructor(...props) {
93
+ [this.log, this.config, this.api] = [...props];
94
+
95
+ this.cachedAccessories = new Map();
96
+ // One TuyaDevice per configured device, keyed by Tuya id, so discovery can
97
+ // hand each its LAN target once it's found on the network.
98
+ this.tuyaDevices = new Map();
99
+ // A SINGLE shared Tuya Cloud session (OpenAPI token + realtime MQTT) for the
100
+ // whole platform — the global fallback every device can lean on. Stays null
101
+ // unless cloud credentials are configured.
102
+ this.cloudApi = null;
103
+ this.cloudMessaging = null;
104
+ this.api.hap.EnergyCharacteristics = require('./lib/EnergyCharacteristics')(this.api.hap);
105
+
106
+ if(!this.config || !this.config.devices) {
107
+ this.log("No devices found. Check that you have specified them in your config.json file.");
108
+ return false;
109
+ }
110
+
111
+ this._expectedUUIDs = this.config.devices.map(device => UUID.generate(UUID_SEED +(device.fake ? ':fake:' : ':') + device.id));
112
+
113
+ this.api.on('didFinishLaunching', () => {
114
+ this.discoverDevices();
115
+ });
116
+ }
117
+
118
+ discoverDevices() {
119
+ // Bring up the single shared cloud session first, so every device that opts
120
+ // into (or falls back to) the cloud shares one token and one MQTT stream.
121
+ this._setupCloudSession();
122
+
123
+ const lanDeviceIds = []; // ids we still want to find on the LAN
124
+ const connectedDevices = []; // ids discovered on the LAN
125
+ const fakeDevices = [];
126
+
127
+ this.config.devices.forEach(device => {
128
+ try {
129
+ device.id = ('' + device.id).trim();
130
+ // Cloud-only devices don't need a local key; only trim when present.
131
+ if (device.key != null) device.key = ('' + device.key).trim();
132
+ device.type = ('' + device.type).trim();
133
+
134
+ device.ip = ('' + (device.ip || '')).trim();
135
+ } catch(ex) {}
136
+
137
+ if (!device.type) return this.log.error('%s (%s) doesn\'t have a type defined.', device.name || 'Unnamed device', device.id);
138
+ 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);
139
+
140
+ if (device.fake) {
141
+ fakeDevices.push({name: device.id.slice(8), ...device});
142
+ return;
143
+ }
144
+
145
+ const tuyaDevice = this._createDevice({name: device.id.slice(8), ...device});
146
+ this.tuyaDevices.set(device.id, tuyaDevice);
147
+ this.addAccessory(tuyaDevice);
148
+
149
+ // A device with a local key can be reached on the LAN, so it wants
150
+ // discovery; the cloud, when configured, is its fallback. A device with
151
+ // no key is cloud-only (e.g. a battery-powered "sleepy" unit) and relies
152
+ // on the cloud session to be reachable at all.
153
+ if (device.key) lanDeviceIds.push(device.id);
154
+ else if (!this.cloudApi) this.log.error('%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.', tuyaDevice.context.name, device.id);
155
+ });
156
+
157
+ fakeDevices.forEach(config => {
158
+ this.log.info('Adding fake device: %s', config.name);
159
+ this.addAccessory(new TuyaAccessory({
160
+ ...config,
161
+ log: this.log,
162
+ UUID: UUID.generate(UUID_SEED + ':fake:' + config.id),
163
+ connect: false
164
+ }));
165
+ });
166
+
167
+ if (lanDeviceIds.length === 0) {
168
+ if (this.tuyaDevices.size === 0 && fakeDevices.length === 0) this.log.error('No valid configured devices found.');
169
+ return; // cloud-only (or empty) configuration: nothing to discover over the LAN
170
+ }
171
+
172
+ this.log.info('Starting discovery...');
173
+
174
+ TuyaDiscovery.start({ids: lanDeviceIds, log: this.log})
175
+ .on('discover', config => {
176
+ if (!config || !config.id) return;
177
+ const tuyaDevice = this.tuyaDevices.get(config.id);
178
+ if (!tuyaDevice) return this.log.warn('Discovered a device that has not been configured yet (%s@%s).', config.id, config.ip);
179
+ if (connectedDevices.includes(config.id)) return;
180
+
181
+ connectedDevices.push(config.id);
182
+
183
+ this.log.info('Discovered %s (%s) identified as %s (%s)', tuyaDevice.context.name, config.id, tuyaDevice.context.type, config.version);
184
+
185
+ // The version broadcast by the device wins over a configured `version`,
186
+ // but `forceVersion` overrides everything; attachLan applies that order.
187
+ tuyaDevice.attachLan({ip: config.ip, version: config.version});
188
+ });
189
+
190
+ setTimeout(() => {
191
+ lanDeviceIds.forEach(deviceId => {
192
+ if (connectedDevices.includes(deviceId)) return;
193
+
194
+ const tuyaDevice = this.tuyaDevices.get(deviceId);
195
+ if (!tuyaDevice) return;
196
+
197
+ if (tuyaDevice.context.ip) {
198
+ this.log.info('Failed to discover %s (%s) in time but will connect via %s.', tuyaDevice.context.name, deviceId, tuyaDevice.context.ip);
199
+ tuyaDevice.attachLan({ip: tuyaDevice.context.ip});
200
+ } else if (tuyaDevice.cloud) {
201
+ this.log.info('Failed to discover %s (%s) on the LAN; it will run over the Tuya Cloud fallback.', tuyaDevice.context.name, deviceId);
202
+ } else {
203
+ this.log.warn('Failed to discover %s (%s) in time but will keep looking.', tuyaDevice.context.name, deviceId);
204
+ }
205
+ });
206
+ }, this.config.discoverTimeout ?? DEFAULT_DISCOVER_TIMEOUT);
207
+ }
208
+
209
+ /* ------------------------------------------------------------------ *
210
+ * Tuya Cloud — a single, global fallback session.
211
+ *
212
+ * This plugin stays LAN-first: every device is controlled locally when it
213
+ * can be. When a top-level `cloud` block is configured, the plugin keeps one
214
+ * shared Tuya Cloud session alive in the background, and every device gains a
215
+ * transparent cloud fallback for the moments the LAN can't be reached (a
216
+ * flaky connection, or a battery-powered "sleepy" device that never appears
217
+ * on the LAN at all). It's all opt-in — without `cloud`, nothing here runs.
218
+ * ------------------------------------------------------------------ */
219
+
220
+ _setupCloudSession() {
221
+ const cloudCfg = (this.config.cloud && typeof this.config.cloud === 'object') ? this.config.cloud : null;
222
+ if (!cloudCfg) return; // no cloud block: the plugin runs purely on the LAN
223
+
224
+ if (!cloudCfg.accessId || !cloudCfg.accessKey) {
225
+ return this.log.error('A "cloud" block is present but is missing accessId/accessKey, so the Tuya Cloud fallback is disabled. See the wiki: Tuya Cloud Setup.');
226
+ }
227
+
228
+ this.cloudApi = new TuyaCloudApi({...cloudCfg, log: this.log});
229
+
230
+ const realtime = cloudCfg.realtime === undefined ? true : coerceBoolean(cloudCfg.realtime, true);
231
+ this.cloudMessaging = realtime ? new TuyaCloudMessaging({api: this.cloudApi, log: this.log}) : null;
232
+
233
+ this.log.info('Tuya Cloud fallback enabled via %s%s.', this.cloudApi.endpoint, this.cloudMessaging ? ' (with realtime updates)' : ' (realtime updates disabled)');
234
+ }
235
+
236
+ _createDevice(device) {
237
+ // The one shared cloud session, when configured, backs every device as its
238
+ // fallback. There is no per-device cloud configuration.
239
+ const usesCloud = !!this.cloudApi;
240
+ return new TuyaDevice({
241
+ ...device,
242
+ cloudApi: usesCloud ? this.cloudApi : undefined,
243
+ messaging: usesCloud ? this.cloudMessaging : undefined,
244
+ cloudStartDelay: usesCloud ? this._nextCloudStartDelay() : 0,
245
+ log: this.log,
246
+ UUID: UUID.generate(UUID_SEED + ':' + device.id),
247
+ connect: false
248
+ });
249
+ }
250
+
251
+ // Spread the cloud devices' first reads over a few seconds so a large install
252
+ // doesn't fire dozens of OpenAPI calls at once and trip Tuya's per-second rate
253
+ // limit at startup.
254
+ _nextCloudStartDelay() {
255
+ this._cloudStartCount = (this._cloudStartCount || 0) + 1;
256
+ return Math.min(15000, (this._cloudStartCount - 1) * 300);
257
+ }
258
+
259
+ registerPlatformAccessories(platformAccessories) {
260
+ this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, Array.isArray(platformAccessories) ? platformAccessories : [platformAccessories]);
261
+ }
262
+
263
+ configureAccessory(accessory) {
264
+ // also checks null objects or empty config - this._expectedUUIDs
265
+ if (accessory instanceof PlatformAccessory && this._expectedUUIDs && this._expectedUUIDs.includes(accessory.UUID)) {
266
+ this.cachedAccessories.set(accessory.UUID, accessory);
267
+ accessory.services.forEach(service => {
268
+ if (service.UUID === Service.AccessoryInformation.UUID) return;
269
+ service.characteristics.some(characteristic => {
270
+ if (!characteristic.props ||
271
+ !Array.isArray(characteristic.props.perms) ||
272
+ characteristic.props.perms.length !== 3 ||
273
+ !(characteristic.props.perms.includes(Perms.WRITE) && characteristic.props.perms.includes(Perms.NOTIFY))
274
+ ) return;
275
+
276
+ this.log.info('Marked %s unreachable by faulting Service.%s.%s', accessory.displayName, service.displayName, characteristic.displayName);
277
+
278
+ characteristic.updateValue(new Error('Unreachable'));
279
+ return true;
280
+ });
281
+ });
282
+ } else {
283
+ /*
284
+ * Irrespective of this unregistering, Homebridge continues
285
+ * to "_prepareAssociatedHAPAccessory" and "addBridgedAccessory".
286
+ * This timeout will hopefully remove the accessory after that has happened.
287
+ */
288
+ setTimeout(() => {
289
+ this.removeAccessory(accessory);
290
+ }, 1000);
291
+ }
292
+ }
293
+
294
+ addAccessory(device) {
295
+ const deviceConfig = device.context;
296
+ const type = (deviceConfig.type || '').toLowerCase();
297
+
298
+ const Accessory = CLASS_DEF[type];
299
+
300
+ let accessory = this.cachedAccessories.get(deviceConfig.UUID),
301
+ isCached = true;
302
+
303
+ const expectedCategory = Accessory.getCategory(Categories);
304
+
305
+ // Only treat a cached accessory as a "different type" when we actually
306
+ // have a category to compare against. If getCategory() resolves to
307
+ // undefined (e.g. an unknown HAP category constant), HomeKit stores the
308
+ // accessory as Categories.OTHER, so an undefined expectation would never
309
+ // match and we would needlessly unregister & recreate the accessory on
310
+ // every restart — wiping its HomeKit identity (name, room, automations).
311
+ if (accessory && expectedCategory !== undefined && accessory.category !== expectedCategory) {
312
+ this.log.info("%s has a different type (%s vs %s)", accessory.displayName, accessory.category, expectedCategory);
313
+ this.removeAccessory(accessory);
314
+ accessory = null;
315
+ }
316
+
317
+ if (!accessory) {
318
+ accessory = new PlatformAccessory(deviceConfig.name, deviceConfig.UUID, expectedCategory);
319
+ accessory.getService(Service.AccessoryInformation)
320
+ .setCharacteristic(Characteristic.Manufacturer, deviceConfig.manufacturer || "Unknown")
321
+ .setCharacteristic(Characteristic.Model, deviceConfig.model || "Unknown")
322
+ .setCharacteristic(Characteristic.SerialNumber, deviceConfig.id.slice(8));
323
+
324
+ isCached = false;
325
+ }
326
+
327
+ if (accessory && accessory.displayName !== deviceConfig.name) {
328
+ this.log.info(
329
+ "Configuration name %s differs from cached displayName %s. Updating cached displayName to %s ",
330
+ deviceConfig.name, accessory.displayName, deviceConfig.name);
331
+ accessory.displayName = deviceConfig.name;
332
+ }
333
+
334
+ this.cachedAccessories.set(deviceConfig.UUID, new Accessory(this, accessory, device, !isCached));
335
+ }
336
+
337
+ removeAccessory(homebridgeAccessory) {
338
+ if (!homebridgeAccessory) return;
339
+
340
+ this.log.warn('Unregistering', homebridgeAccessory.displayName);
341
+
342
+ delete this.cachedAccessories[homebridgeAccessory.UUID];
343
+ this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [homebridgeAccessory]);
344
+ }
345
+
346
+ removeAccessoryByUUID(uuid) {
347
+ if (uuid) this.removeAccessory(this.cachedAccessories.get(uuid));
348
+ }
349
+ }