homebridge-tuya-plus 4.1.0-pr.100.74 → 4.2.0-dev.81

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/AGENTS.md CHANGED
@@ -149,6 +149,11 @@ optional, off-by-default flags read through `_debugConfig()` and coerced with
149
149
  (token, signature, password, access key/id, uid) redacted. Verbose and
150
150
  per-request — keep it off in normal operation, and remember Homebridge
151
151
  debug logging must be on to see it.
152
+ - `debug.logDebugAsInfo` — promote every `this.log.debug` line to `info` by
153
+ wrapping the platform logger (threaded down to every device/accessory/cloud
154
+ component). Lets a user capture the plugin's verbose protocol/state logging
155
+ without enabling Homebridge's global debug mode. Chatty by design — a
156
+ troubleshooting switch, not for normal operation.
152
157
 
153
158
  ## Git & PR workflow
154
159
 
package/index.js CHANGED
@@ -93,6 +93,23 @@ function coerceBoolean(value, defaultValue) {
93
93
  : df;
94
94
  }
95
95
 
96
+ // Return a drop-in replacement for the Homebridge logger whose .debug() emits
97
+ // at info level instead, leaving every other method (and the callable form)
98
+ // untouched. Wrapping the platform's logger once and threading it down to every
99
+ // device/accessory/cloud component promotes the plugin's whole debug stream to
100
+ // info, so users can capture its verbose protocol/state logging without turning
101
+ // on Homebridge's global debug mode (debug.logDebugAsInfo).
102
+ function promoteDebugToInfo(log) {
103
+ const wrapped = (...args) => log(...args);
104
+ for (const key of ['info', 'warn', 'error', 'log']) {
105
+ if (typeof log[key] === 'function')
106
+ wrapped[key] = (...args) => log[key](...args);
107
+ }
108
+ wrapped.debug = (...args) => log.info(...args);
109
+ if ('prefix' in log) wrapped.prefix = log.prefix;
110
+ return wrapped;
111
+ }
112
+
96
113
  module.exports = function (homebridge) {
97
114
  ({
98
115
  platformAccessory: PlatformAccessory,
@@ -114,6 +131,14 @@ class TuyaLan {
114
131
  constructor(...props) {
115
132
  [this.log, this.config, this.api] = [...props];
116
133
 
134
+ // Apply before anything logs so the very first lines already honour it.
135
+ if (this.config && coerceBoolean(this._debugConfig().logDebugAsInfo)) {
136
+ this.log = promoteDebugToInfo(this.log);
137
+ this.log.info(
138
+ 'debug.logDebugAsInfo is set: routing all debug logging to info.',
139
+ );
140
+ }
141
+
117
142
  this.cachedAccessories = new Map();
118
143
  // One TuyaDevice per configured device, keyed by Tuya id, so discovery can
119
144
  // hand each its LAN target once it's found on the network.
@@ -65,6 +65,14 @@ class BaseAccessory {
65
65
  return typeof b === 'boolean' ? b : (typeof b === 'string' ? b.toLowerCase().trim() === 'true' : (typeof b === 'number' ? b !== 0 : df));
66
66
  }
67
67
 
68
+ // Numbers reach us as numbers from the Homebridge UI but as strings from a
69
+ // hand-edited config.json, and as anything at all from a device that reports
70
+ // an unexpected data point. Anything non-numeric falls back to the default.
71
+ _coerceNumber(n, defaultValue) {
72
+ const parsed = parseInt(n);
73
+ return isNaN(parsed) ? defaultValue : parsed;
74
+ }
75
+
68
76
  // A HapStatusError to throw from a get/set handler when the value can't be
69
77
  // served (device unreachable, or an unusable reading). HomeKit shows the
70
78
  // accessory as "No Response". Preferred over a plain `throw new Error(...)`,
@@ -240,20 +248,34 @@ class BaseAccessory {
240
248
  return Math.round(value * scale)
241
249
  }
242
250
 
251
+ // The mired window HomeKit sees and the raw scale the device speaks. A zero
252
+ // is meaningless for all three, so it keeps falling back to the default.
253
+ _getWhiteColorRange() {
254
+ return {
255
+ min: parseInt(this.device.context.minWhiteColor) || 140,
256
+ max: parseInt(this.device.context.maxWhiteColor) || 400,
257
+ scale: parseInt(this.device.context.scaleWhiteColor) || 255
258
+ };
259
+ }
260
+
243
261
  convertColorTemperatureFromHomeKitToTuya(value) {
244
- const min = this.device.context.minWhiteColor || 140;
245
- const max = this.device.context.maxWhiteColor || 400;
246
- const scale = this.device.context.scaleWhiteColor || 255;
247
- const result = Math.round(Math.max(Math.min(scale-(scale-1)/(max-min)*(value-min),scale),1));
248
- return result;
262
+ const {min, max, scale} = this._getWhiteColorRange();
263
+ const mireds = this._coerceNumber(value, min);
264
+ return Math.round(Math.max(Math.min(scale-(scale-1)/(max-min)*(mireds-min),scale),1));
249
265
  }
250
266
 
251
267
  convertColorTemperatureFromTuyaToHomeKit(value) {
252
- const min = this.device.context.minWhiteColor || 140;
253
- const max = this.device.context.maxWhiteColor || 400;
254
- const scale = this.device.context.scaleWhiteColor || 255;
255
- const result = Math.round(Math.max(Math.min((scale-value)/((scale-1)/(max-min))+min,max),min));
256
- return Math.min(600, Math.max(71, result));
268
+ const {min, max, scale} = this._getWhiteColorRange();
269
+ // A device that hasn't reported its colour-temperature data point yet —
270
+ // or reports a non-numeric one — used to convert to NaN, which HomeKit
271
+ // rejects with a characteristic warning on every read (see issue #34).
272
+ // Fall back to the coolest mired, what the lights already report while
273
+ // they're not in white mode.
274
+ const tuya = this._coerceNumber(value, scale);
275
+ const mireds = (scale-tuya)/((scale-1)/(max-min))+min;
276
+ // Clamped to the configured window last: that window is what the lights
277
+ // publish through setProps(), and a read outside it warns just as loudly.
278
+ return Math.round(Math.max(Math.min(mireds,max),min));
257
279
  }
258
280
 
259
281
  convertColorFromHomeKitToTuya(value, dpValue) {
@@ -61,6 +61,9 @@ class OilDiffuserAccessory extends BaseAccessory {
61
61
  this.dpLight = this._getCustomDP(this.device.context.dpLight) || '5';
62
62
  this.dpMode = this._getCustomDP(this.device.context.dpMode) || '6';
63
63
  this.dpColor = this._getCustomDP(this.device.context.dpColor) || '8';
64
+ // No default: these diffusers have no colour-temperature data point, and
65
+ // setColorTemperature emulates one by writing the equivalent RGB colour.
66
+ this.dpColorTemperature = this._getCustomDP(this.device.context.dpColorTemperature);
64
67
  this.dpActive = this._getCustomDP(this.device.context.dpActive) || '1';
65
68
  this.dpRotationSpeed = this._getCustomDP(this.device.context.dpRotationSpeed) || '2';
66
69
  this.dpWaterLevel = this._getCustomDP(this.device.context.dpWaterLevel) || '9';
@@ -111,7 +114,7 @@ class OilDiffuserAccessory extends BaseAccessory {
111
114
 
112
115
  const characteristicColorTemperature = lightService.getCharacteristic(Characteristic.ColorTemperature)
113
116
  .setProps({ minValue: 0, maxValue: 600 })
114
- .updateValue(dps[this.dpMode] === this.cmdWhite ? this.convertColorTemperatureFromTuyaToHomeKit(dps[this.dpColorTemperature]) : 0)
117
+ .updateValue(this.dpColorTemperature && dps[this.dpMode] === this.cmdWhite ? this.convertColorTemperatureFromTuyaToHomeKit(dps[this.dpColorTemperature]) : 0)
115
118
  .onGet(() => this.getColorTemperature())
116
119
  .onSet(value => this.setColorTemperature(value));
117
120
 
@@ -218,7 +221,11 @@ class OilDiffuserAccessory extends BaseAccessory {
218
221
  }
219
222
 
220
223
  getColorTemperature() {
221
- if (this.getStateAsync(this.dpMode) !== this.cmdWhite) return 0;
224
+ const mode = this.getStateAsync(this.dpMode);
225
+ // Without a colour-temperature data point there is nothing to read back:
226
+ // reading the undefined one returned NaN, which HomeKit rejects with a
227
+ // characteristic warning on every read while the light is white.
228
+ if (!this.dpColorTemperature || mode !== this.cmdWhite) return 0;
222
229
  return this.convertColorTemperatureFromTuyaToHomeKit(this.getStateAsync(this.dpColorTemperature));
223
230
  }
224
231
 
@@ -31,8 +31,8 @@ class RGBTWLightAccessory extends BaseAccessory {
31
31
  this.dpColorTemperature = this._getCustomDP(this.device.context.dpColorTemperature) || '4';
32
32
  this.dpColor = this._getCustomDP(this.device.context.dpColor) || '5';
33
33
 
34
- this.minWhiteColor = this.device.context.minWhiteColor ?? DEFAULT_MIN_WHITE_COLOR;
35
- this.maxWhiteColor = this.device.context.maxWhiteColor ?? DEFAULT_MAX_WHITE_COLOR;
34
+ this.minWhiteColor = this._coerceNumber(this.device.context.minWhiteColor, DEFAULT_MIN_WHITE_COLOR);
35
+ this.maxWhiteColor = this._coerceNumber(this.device.context.maxWhiteColor, DEFAULT_MAX_WHITE_COLOR);
36
36
 
37
37
  this._detectColorFunction(dps[this.dpColor]);
38
38
 
@@ -41,8 +41,8 @@ class TWLightAccessory extends BaseAccessory {
41
41
 
42
42
  const characteristicColorTemperature = service.getCharacteristic(Characteristic.ColorTemperature)
43
43
  .setProps({
44
- minValue: this.device.context.minWhiteColor ?? DEFAULT_MIN_WHITE_COLOR,
45
- maxValue: this.device.context.maxWhiteColor ?? DEFAULT_MAX_WHITE_COLOR
44
+ minValue: this._coerceNumber(this.device.context.minWhiteColor, DEFAULT_MIN_WHITE_COLOR),
45
+ maxValue: this._coerceNumber(this.device.context.maxWhiteColor, DEFAULT_MAX_WHITE_COLOR)
46
46
  })
47
47
  .updateValue(this.convertColorTemperatureFromTuyaToHomeKit(dps[this.dpColorTemperature]))
48
48
  .onGet(() => this.getColorTemperature())
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "homebridge-tuya-plus",
3
- "version": "4.1.0-pr.100.74",
3
+ "version": "4.2.0-dev.81",
4
4
  "description": "A community-maintained Homebridge plugin for controlling Tuya devices locally over LAN, with an optional Tuya Cloud fallback for whatever the LAN can't reach. Includes new features, fixes, and updated device support. PRs welcome: if it runs, it ships (almost).",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "keywords": [
37
37
  "homebridge-plugin",
38
+ "supports-hap",
38
39
  "homebridge",
39
40
  "homebridge-tuya",
40
41
  "tuya"
@@ -26,9 +26,8 @@
26
26
  */
27
27
 
28
28
  const { execFileSync } = require('child_process');
29
- const path = require('path');
30
29
 
31
- const pkgJson = require(path.join(__dirname, '..', 'package.json'));
30
+ const pkgJson = require('../package.json');
32
31
  const PKG = pkgJson.name;
33
32
  const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
34
33
 
@@ -66,10 +66,13 @@ describe('convertColorTemperatureFromTuyaToHomeKit', () => {
66
66
  expect(instance.convertColorTemperatureFromTuyaToHomeKit(0)).toBe(400);
67
67
  });
68
68
 
69
- test('clamps result to [71, 600]', () => {
70
- const { instance } = make();
71
- expect(instance.convertColorTemperatureFromTuyaToHomeKit(255)).toBeGreaterThanOrEqual(71);
72
- expect(instance.convertColorTemperatureFromTuyaToHomeKit(0)).toBeLessThanOrEqual(600);
69
+ test('clamps result to the configured mired window', () => {
70
+ const { instance } = make({}, { minWhiteColor: 154, maxWhiteColor: 370 });
71
+ for (const tuya of [-500, 0, 128, 255, 5000]) {
72
+ const hk = instance.convertColorTemperatureFromTuyaToHomeKit(tuya);
73
+ expect(hk).toBeGreaterThanOrEqual(154);
74
+ expect(hk).toBeLessThanOrEqual(370);
75
+ }
73
76
  });
74
77
 
75
78
  test('round-trips with convertColorTemperatureFromHomeKitToTuya at boundaries', () => {
@@ -79,6 +82,38 @@ describe('convertColorTemperatureFromTuyaToHomeKit', () => {
79
82
  expect(instance.convertColorTemperatureFromTuyaToHomeKit(tuya)).toBe(hk);
80
83
  }
81
84
  });
85
+
86
+ // A missing/unusable data point used to convert to NaN, which HomeKit
87
+ // rejects with a characteristic warning on every read (issue #34).
88
+ test('falls back to the coolest mired for an unreported data point', () => {
89
+ const { instance } = make();
90
+ for (const unusable of [undefined, null, '', 'abc', true, {}]) {
91
+ expect(instance.convertColorTemperatureFromTuyaToHomeKit(unusable)).toBe(140);
92
+ }
93
+ });
94
+
95
+ test('reads a data point reported as a string', () => {
96
+ const { instance } = make();
97
+ expect(instance.convertColorTemperatureFromTuyaToHomeKit('255')).toBe(140);
98
+ expect(instance.convertColorTemperatureFromTuyaToHomeKit('0')).toBe(400);
99
+ });
100
+
101
+ test('accepts a mired window configured as strings', () => {
102
+ const { instance } = make({}, { minWhiteColor: '154', maxWhiteColor: '370' });
103
+ expect(instance.convertColorTemperatureFromTuyaToHomeKit(255)).toBe(154);
104
+ expect(instance.convertColorTemperatureFromTuyaToHomeKit(0)).toBe(370);
105
+ });
106
+ });
107
+
108
+ describe('convertColorTemperatureFromHomeKitToTuya', () => {
109
+ test('never returns NaN for an unusable value', () => {
110
+ const { instance } = make();
111
+ for (const unusable of [undefined, null, '', 'abc', NaN]) {
112
+ const tuya = instance.convertColorTemperatureFromHomeKitToTuya(unusable);
113
+ expect(Number.isFinite(tuya)).toBe(true);
114
+ expect(tuya).toBe(instance.convertColorTemperatureFromHomeKitToTuya(140));
115
+ }
116
+ });
82
117
  });
83
118
 
84
119
  // ---------------------------------------------------------------------------
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const OilDiffuserAccessory = require('../lib/OilDiffuserAccessory');
4
+ const { makeInstance, HAP } = require('./support/mocks');
5
+
6
+ // The dp/command fields are normally established by _registerCharacteristics,
7
+ // which only runs once the device reports its first state.
8
+ function makeDiffuser(state = {}, context = {}) {
9
+ const result = makeInstance(OilDiffuserAccessory, state, { colorFunction: 'HEXHSB', ...context });
10
+ const { instance, device } = result;
11
+
12
+ instance.dpLight = '5';
13
+ instance.dpMode = '6';
14
+ instance.dpColor = '8';
15
+ instance.dpColorTemperature = instance._getCustomDP(device.context.dpColorTemperature);
16
+ instance.cmdWhite = 'white';
17
+ instance.cmdColor = 'colour';
18
+ instance.colorFunction = 'HEXHSB';
19
+
20
+ return result;
21
+ }
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // getColorTemperature
25
+ // ---------------------------------------------------------------------------
26
+ describe('OilDiffuserAccessory.getColorTemperature', () => {
27
+ // These diffusers have no colour-temperature dp; reading the undefined one
28
+ // returned NaN, which HomeKit rejects with a characteristic warning.
29
+ test('returns the neutral value in white mode when no dp is configured', () => {
30
+ const { instance } = makeDiffuser({ '6': 'white' });
31
+ expect(instance.getColorTemperature()).toBe(0);
32
+ });
33
+
34
+ test('returns the neutral value in color mode', () => {
35
+ const { instance } = makeDiffuser({ '6': 'colour' });
36
+ expect(instance.getColorTemperature()).toBe(0);
37
+ });
38
+
39
+ test('reads the configured dp in white mode', () => {
40
+ const { instance } = makeDiffuser({ '6': 'white', '4': 255 }, { dpColorTemperature: 4 });
41
+ // convertColorTemperatureFromTuyaToHomeKit(255) == 140
42
+ expect(instance.getColorTemperature()).toBe(140);
43
+ });
44
+
45
+ test('rejects (No Response) when the device is not connected', () => {
46
+ const { instance, device } = makeDiffuser({ '6': 'white' });
47
+ device.connected = false;
48
+ expect(() => instance.getColorTemperature()).toThrow(HAP.HapStatusError);
49
+ });
50
+ });
@@ -82,6 +82,16 @@ describe('RGBTWLightAccessory.getColorTemperature', () => {
82
82
  expect(typeof result).toBe('number');
83
83
  expect(Number.isFinite(result)).toBe(true);
84
84
  });
85
+
86
+ // HomeKit warns about every non-finite read, so a white-mode light whose
87
+ // colour-temperature dp hasn't been reported yet must still answer in range.
88
+ test('returns an in-range value when the color temperature dp is missing', () => {
89
+ const { instance } = makeLight({ '2': 'white' });
90
+ const result = instance.getColorTemperature();
91
+ expect(Number.isFinite(result)).toBe(true);
92
+ expect(result).toBeGreaterThanOrEqual(instance.minWhiteColor);
93
+ expect(result).toBeLessThanOrEqual(instance.maxWhiteColor);
94
+ });
85
95
  });
86
96
 
87
97
  // ---------------------------------------------------------------------------
@@ -166,6 +166,49 @@ describe('TuyaLan — debug.forceCloudFallback', () => {
166
166
  });
167
167
  });
168
168
 
169
+ describe('TuyaLan — debug.logDebugAsInfo', () => {
170
+ // The platform wraps its logger and threads it down to every
171
+ // device/accessory/cloud component, so promoting it once routes the
172
+ // plugin's whole debug stream to info. Build the platform directly here to
173
+ // keep a handle on the underlying logger mock the wrapper delegates to.
174
+ function platformWith(config) {
175
+ const Platform = getPlatformClass();
176
+ const rawLog = makeLog();
177
+ return [new Platform(rawLog, config, makeApi()), rawLog];
178
+ }
179
+
180
+ test('routes a debug line to info', () => {
181
+ const [platform, rawLog] = platformWith({debug: {logDebugAsInfo: true}, devices: [SW()]});
182
+ platform.log.debug('hello', 1);
183
+ expect(rawLog.info).toHaveBeenCalledWith('hello', 1);
184
+ expect(rawLog.debug).not.toHaveBeenCalledWith('hello', 1);
185
+ });
186
+
187
+ test('the wrapped logger passes the callable form and info/warn/error straight through', () => {
188
+ const [platform, rawLog] = platformWith({debug: {logDebugAsInfo: true}, devices: [SW()]});
189
+ platform.log('plain');
190
+ platform.log.warn('careful');
191
+ platform.log.error('broke');
192
+ expect(rawLog).toHaveBeenCalledWith('plain');
193
+ expect(rawLog.warn).toHaveBeenCalledWith('careful');
194
+ expect(rawLog.error).toHaveBeenCalledWith('broke');
195
+ });
196
+
197
+ test('off (or absent) leaves the logger untouched and debug going to debug', () => {
198
+ const [platform, rawLog] = platformWith({devices: [SW()]});
199
+ expect(platform.log).toBe(rawLog);
200
+ platform.log.debug('quiet');
201
+ expect(rawLog.debug).toHaveBeenCalledWith('quiet');
202
+ expect(rawLog.info).not.toHaveBeenCalledWith('quiet');
203
+ });
204
+
205
+ test('lenient boolean spellings are accepted', () => {
206
+ const [platform, rawLog] = platformWith({debug: {logDebugAsInfo: 'true'}, devices: [SW()]});
207
+ platform.log.debug('promote me');
208
+ expect(rawLog.info).toHaveBeenCalledWith('promote me');
209
+ });
210
+ });
211
+
169
212
  describe('TuyaLan — unconfigured device discovery', () => {
170
213
  const UNKNOWN = {id: 'bf99999999999999', ip: '10.0.0.9'};
171
214
  const BARE = 'Discovered a device that has not been configured yet (%s@%s).';
@@ -1214,6 +1214,11 @@ Aroma diffusers and humidifiers with mist on/off, mist intensity (speed) and an
1214
1214
  /* Data-point for light colour / brightness value. Default: "8" */
1215
1215
  "dpColor": 8,
1216
1216
 
1217
+ /* Data-point for a colour-temperature value, if your diffuser reports one.
1218
+ Unset by default: these diffusers have no such data-point, and HomeKit's
1219
+ temperature slider is served by writing the matching colour instead. */
1220
+ "dpColorTemperature": 4,
1221
+
1217
1222
  /* Data-point for the water-level status. Default: "9" */
1218
1223
  "dpWaterLevel": 9,
1219
1224