homebridge-tuya-plus 4.3.0-dev.100 → 4.3.0-dev.103

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/Readme.MD CHANGED
@@ -47,6 +47,7 @@ A community-maintained Homebridge plugin for controlling Tuya devices locally ov
47
47
  * Outlets<sup>[14](https://github.com/adrianjagielak/homebridge-tuya-plus/blob/main/wiki/Supported-Device-Types.md#outlets)</sup>
48
48
  * [Presence Sensor (ZY-M100)](wiki/Occupancy-Sensors.md) (occupancy and ambient light)
49
49
  * Switches<sup>[15](https://github.com/adrianjagielak/homebridge-tuya-plus/blob/main/wiki/Supported-Device-Types.md#switch)</sup>
50
+ * [Contact, Smoke, and Leak Sensors](wiki/Cloud-Sensors.md) (including cloud-only devices)
50
51
  * Vertical Blinds<sup>[16](https://github.com/adrianjagielak/homebridge-tuya-plus/blob/main/wiki/Supported-Device-Types.md#vertical-blinds-with-tilt)</sup>
51
52
 
52
53
  ## Cloud fallback
@@ -110,6 +111,7 @@ If you have new accessory logic for a new device, please add a function defined
110
111
  * mxDanger - Plugin branding.
111
112
  * [CodeTheWeb](https://github.com/CodeTheWeb) - developer of [TuyaApi](https://github.com/codetheweb/tuyapi), who gratiously provided this repo's name.
112
113
  * [Oznu](https://github.com/oznu) - developer of Homebridge, added ```config.schema.json``` , fixed dependencies, and helped inspire this readME off his [gsh](https://github.com/oznu/homebridge-gsh) plugin.
114
+ * [0x5e](https://github.com/0x5e) and the [Tuya Homebridge contributors](https://github.com/0x5e/homebridge-tuya-platform) - contact, smoke, leak, and battery mappings, adapted under the MIT license. See [third-party notices](THIRD_PARTY_NOTICES.md).
113
115
 
114
116
  #
115
117
 
@@ -0,0 +1,42 @@
1
+ # Third-party notices
2
+
3
+ ## Sensor mappings from homebridge-tuya-platform
4
+
5
+ The contact, smoke, and leak sensor mappings and shared battery mappings in
6
+ `lib/TuyaSensorAccessory.js`, `lib/ContactSensorAccessory.js`,
7
+ `lib/SmokeSensorAccessory.js`, and `lib/LeakSensorAccessory.js` are adapted from
8
+ [0x5e/homebridge-tuya-platform](https://github.com/0x5e/homebridge-tuya-platform),
9
+ revision `ab74ea4eee3c9df0be2ecc04c0fc56d9c0b02207`:
10
+
11
+ - `src/accessory/ContactSensorAccessory.ts`
12
+ - `src/accessory/SmokeSensorAccessory.ts`
13
+ - `src/accessory/LeakSensorAccessory.ts`
14
+ - `src/accessory/BaseAccessory.ts`
15
+
16
+ Credit goes to 0x5e and the Tuya Homebridge contributors for those implementations.
17
+ Eliran Sapir ([sapireli](https://github.com/sapireli)) adapted them for Tuya Plus's
18
+ accessory lifecycle, cloud updates, configuration UI, and regression tests.
19
+
20
+ The source project's MIT license notice follows:
21
+
22
+ The MIT License (MIT)
23
+
24
+ Copyright (c) 2014-2021 Tuya Inc.
25
+
26
+ Permission is hereby granted, free of charge, to any person obtaining a copy
27
+ of this software and associated documentation files (the "Software"), to deal
28
+ in the Software without restriction, including without limitation the rights
29
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30
+ copies of the Software, and to permit persons to whom the Software is
31
+ furnished to do so, subject to the following conditions:
32
+
33
+ The above copyright notice and this permission notice shall be included in
34
+ all copies or substantial portions of the Software.
35
+
36
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
39
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
41
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
42
+ DEALINGS IN THE SOFTWARE.
@@ -135,6 +135,18 @@
135
135
  "title": "Simple Heater",
136
136
  "enum": ["SimpleHeater"]
137
137
  },
138
+ {
139
+ "title": "Contact Sensor",
140
+ "enum": ["ContactSensor"]
141
+ },
142
+ {
143
+ "title": "Smoke Sensor",
144
+ "enum": ["SmokeSensor"]
145
+ },
146
+ {
147
+ "title": "Leak Sensor",
148
+ "enum": ["LeakSensor"]
149
+ },
138
150
  {
139
151
  "title": "Garage Door",
140
152
  "enum": ["GarageDoor"]
@@ -997,7 +1009,7 @@
997
1009
  "title": "No battery service",
998
1010
  "description": "Disable the battery service (use if your controller is mains-powered or doesn't report 'battery_percentage').",
999
1011
  "condition": {
1000
- "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem'].includes(model.devices[arrayIndices].type);"
1012
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem', 'ContactSensor', 'SmokeSensor', 'LeakSensor'].includes(model.devices[arrayIndices].type);"
1001
1013
  }
1002
1014
  },
1003
1015
  "dpBattery": {
@@ -1005,7 +1017,7 @@
1005
1017
  "placeholder": "46 or battery_percentage",
1006
1018
  "title": "Battery data-point (numeric id, or cloud code)",
1007
1019
  "condition": {
1008
- "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem'].includes(model.devices[arrayIndices].type) && !model.devices[arrayIndices].noBattery;"
1020
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem', 'ContactSensor', 'SmokeSensor', 'LeakSensor'].includes(model.devices[arrayIndices].type) && !model.devices[arrayIndices].noBattery;"
1009
1021
  }
1010
1022
  },
1011
1023
  "lowBatteryThreshold": {
@@ -1014,7 +1026,7 @@
1014
1026
  "title": "Low-battery threshold (%)",
1015
1027
  "description": "At or below this level HomeKit shows a low-battery warning.",
1016
1028
  "condition": {
1017
- "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem'].includes(model.devices[arrayIndices].type) && !model.devices[arrayIndices].noBattery;"
1029
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem', 'ContactSensor', 'SmokeSensor', 'LeakSensor'].includes(model.devices[arrayIndices].type) && !model.devices[arrayIndices].noBattery;"
1018
1030
  }
1019
1031
  },
1020
1032
  "dpCharging": {
@@ -1023,9 +1035,50 @@
1023
1035
  "title": "Charging-status data-point (numeric id, or cloud code)",
1024
1036
  "description": "Boolean data-point reporting whether the battery is charging (e.g. solar / USB-C units). HomeKit shows Charging / Not Charging; if your controller doesn't report this, it shows Not Chargeable.",
1025
1037
  "condition": {
1026
- "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem'].includes(model.devices[arrayIndices].type) && !model.devices[arrayIndices].noBattery;"
1038
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['IrrigationSystem', 'ContactSensor', 'SmokeSensor', 'LeakSensor'].includes(model.devices[arrayIndices].type) && !model.devices[arrayIndices].noBattery;"
1027
1039
  }
1028
1040
  },
1041
+ "dpContact": {
1042
+ "type": ["integer", "string"],
1043
+ "title": "Contact data point",
1044
+ "placeholder": "doorcontact_state",
1045
+ "condition": {
1046
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['ContactSensor'].includes(model.devices[arrayIndices].type);"
1047
+ }
1048
+ },
1049
+ "dpSmoke": {
1050
+ "type": ["integer", "string"],
1051
+ "title": "Smoke data point",
1052
+ "placeholder": "smoke_sensor_status",
1053
+ "condition": {
1054
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['SmokeSensor'].includes(model.devices[arrayIndices].type);"
1055
+ }
1056
+ },
1057
+ "dpLeak": {
1058
+ "type": ["integer", "string"],
1059
+ "title": "Leak data point",
1060
+ "placeholder": "watersensor_state",
1061
+ "condition": {
1062
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['LeakSensor'].includes(model.devices[arrayIndices].type);"
1063
+ }
1064
+ },
1065
+ "dpBatteryState": {
1066
+ "type": ["integer", "string"],
1067
+ "title": "Battery-state data point",
1068
+ "placeholder": "battery_state",
1069
+ "condition": {
1070
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['ContactSensor', 'SmokeSensor', 'LeakSensor'].includes(model.devices[arrayIndices].type);"
1071
+ }
1072
+ },
1073
+ "batteryDivisor": {
1074
+ "type": "number",
1075
+ "title": "Battery percentage divisor",
1076
+ "placeholder": "1",
1077
+ "condition": {
1078
+ "functionBody": "return model.devices && model.devices[arrayIndices] && ['ContactSensor', 'SmokeSensor', 'LeakSensor'].includes(model.devices[arrayIndices].type);"
1079
+ },
1080
+ "minimum": 0.000001
1081
+ },
1029
1082
  "dpRainState": {
1030
1083
  "type": ["integer", "string"],
1031
1084
  "placeholder": "49 or rain_sensor_state",
package/index.js CHANGED
@@ -32,6 +32,9 @@ const OilDiffuserAccessory = require('./lib/OilDiffuserAccessory');
32
32
  const DoorbellAccessory = require('./lib/DoorbellAccessory');
33
33
  const VerticalBlindsWithTilt = require('./lib/VerticalBlindsWithTilt');
34
34
  const PercentBlindsAccessory = require('./lib/PercentBlindsAccessory');
35
+ const ContactSensorAccessory = require('./lib/ContactSensorAccessory');
36
+ const SmokeSensorAccessory = require('./lib/SmokeSensorAccessory');
37
+ const LeakSensorAccessory = require('./lib/LeakSensorAccessory');
35
38
 
36
39
  const PLUGIN_NAME = 'homebridge-tuya-plus';
37
40
  const PLATFORM_NAME = 'TuyaLan';
@@ -70,6 +73,9 @@ const CLASS_DEF = {
70
73
  doorbell: DoorbellAccessory,
71
74
  verticalblindswithtilt: VerticalBlindsWithTilt,
72
75
  percentblinds: PercentBlindsAccessory,
76
+ contactsensor: ContactSensorAccessory,
77
+ smokesensor: SmokeSensorAccessory,
78
+ leaksensor: LeakSensorAccessory,
73
79
  };
74
80
 
75
81
  let Characteristic,
@@ -0,0 +1,13 @@
1
+ const TuyaSensorAccessory = require('./TuyaSensorAccessory');
2
+
3
+ class ContactSensorAccessory extends TuyaSensorAccessory {
4
+ static sensor = {
5
+ service: 'ContactSensor',
6
+ characteristic: 'ContactSensorState',
7
+ option: 'dpContact',
8
+ codes: ['doorcontact_state', 'switch'],
9
+ decode: TuyaSensorAccessory.booleanValue,
10
+ };
11
+ }
12
+
13
+ module.exports = ContactSensorAccessory;
@@ -0,0 +1,14 @@
1
+ const TuyaSensorAccessory = require('./TuyaSensorAccessory');
2
+
3
+ class LeakSensorAccessory extends TuyaSensorAccessory {
4
+ static sensor = {
5
+ service: 'LeakSensor',
6
+ characteristic: 'LeakDetected',
7
+ option: 'dpLeak',
8
+ codes: ['gas_sensor_status', 'gas_sensor_state', 'ch4_sensor_state', 'watersensor_state'],
9
+ decode: TuyaSensorAccessory.alarmValue,
10
+ anyAlarm: true,
11
+ };
12
+ }
13
+
14
+ module.exports = LeakSensorAccessory;
@@ -0,0 +1,13 @@
1
+ const TuyaSensorAccessory = require('./TuyaSensorAccessory');
2
+
3
+ class SmokeSensorAccessory extends TuyaSensorAccessory {
4
+ static sensor = {
5
+ service: 'SmokeSensor',
6
+ characteristic: 'SmokeDetected',
7
+ option: 'dpSmoke',
8
+ codes: ['smoke_sensor_status', 'smoke_sensor_state'],
9
+ decode: TuyaSensorAccessory.alarmValue,
10
+ };
11
+ }
12
+
13
+ module.exports = SmokeSensorAccessory;
@@ -0,0 +1,134 @@
1
+ // Sensor codes and battery mappings adapted from 0x5e/homebridge-tuya-platform.
2
+ // See THIRD_PARTY_NOTICES.md for attribution and the MIT license notice.
3
+ const BaseAccessory = require('./BaseAccessory');
4
+
5
+ const BATTERY_CODES = ['battery_percentage', 'residual_electricity', 'wireless_electricity', 'va_battery', 'battery'];
6
+
7
+ class TuyaSensorAccessory extends BaseAccessory {
8
+ static getCategory(Categories) {
9
+ return Categories.SENSOR;
10
+ }
11
+
12
+ _registerPlatformAccessory() {
13
+ const service = this.hap.Service[this.constructor.sensor.service];
14
+ this.accessory.addService(service, this.device.context.name);
15
+ super._registerPlatformAccessory();
16
+ }
17
+
18
+ _registerCharacteristics(dps) {
19
+ const {Service, Characteristic} = this.hap;
20
+ const definition = this.constructor.sensor;
21
+ const service = this.accessory.getService(Service[definition.service]);
22
+ this._checkServiceName(service, this.device.context.name);
23
+ this._sensorState = {...dps};
24
+ this._sensorBindings = [];
25
+ this._bindSensorCharacteristic(service, Characteristic[definition.characteristic], state => this._sensorValue(state));
26
+ this._registerSensorBattery();
27
+ this._syncSensorCharacteristics();
28
+ this.device.on('change', (changes, state) => {
29
+ this._sensorState = state ? {...state} : {...this._sensorState, ...changes};
30
+ this._registerSensorBattery();
31
+ this._syncSensorCharacteristics();
32
+ });
33
+ }
34
+
35
+ _sensorCodes(option, defaults) {
36
+ const override = this.device.context[option];
37
+ if (override !== undefined && override !== null && String(override).trim() !== '') return [String(override).trim()];
38
+ return defaults;
39
+ }
40
+
41
+ _sensorValues(option, defaults, state = this._sensorState) {
42
+ return this._sensorCodes(option, defaults)
43
+ .filter(code => Object.prototype.hasOwnProperty.call(state, code))
44
+ .map(code => state[code]);
45
+ }
46
+
47
+ _sensorValue(state = this._sensorState) {
48
+ const definition = this.constructor.sensor;
49
+ const values = this._sensorValues(definition.option, definition.codes, state);
50
+ if (!values.length) throw this._commError();
51
+ const decoded = values.map(value => definition.decode(value));
52
+ // Leak detectors may report several gases/water at once. Any alarm wins,
53
+ // including when another reported data point is missing or malformed.
54
+ if (definition.anyAlarm && decoded.includes(1)) return 1;
55
+ const selected = definition.anyAlarm ? decoded : decoded.slice(0, 1);
56
+ if (selected.some(value => value === undefined)) throw this._commError();
57
+ return selected[0];
58
+ }
59
+
60
+ _bindSensorCharacteristic(service, type, read) {
61
+ const getter = async () => read(await this.getStateAsync(Object.keys(this._sensorState)));
62
+ const characteristic = service.getCharacteristic(type).onGet(getter);
63
+ this._sensorBindings.push({characteristic, read});
64
+ }
65
+
66
+ _syncSensorCharacteristics() {
67
+ for (const {characteristic, read} of this._sensorBindings) {
68
+ try {
69
+ if (!this.device.connected) throw this._commError();
70
+ const value = read(this._sensorState);
71
+ if (characteristic.value !== value) characteristic.updateValue(value);
72
+ } catch (error) {
73
+ characteristic.updateValue(error);
74
+ }
75
+ }
76
+ }
77
+
78
+ _registerSensorBattery() {
79
+ if (this._batteryRegistered) return;
80
+ if (this._coerceBoolean(this.device.context.noBattery)) {
81
+ const battery = this.accessory.getService(this.hap.Service.Battery);
82
+ if (battery) this.accessory.removeService(battery);
83
+ return;
84
+ }
85
+ const hasLevel = this._sensorValues('dpBattery', BATTERY_CODES).length > 0;
86
+ if (!hasLevel) return;
87
+
88
+ this._batteryRegistered = true;
89
+ const {Service, Characteristic} = this.hap;
90
+ const service = this.accessory.getService(Service.Battery)
91
+ || this.accessory.addService(Service.Battery, this.device.context.name + ' Battery');
92
+ this._bindSensorCharacteristic(service, Characteristic.BatteryLevel, state => this._sensorBatteryLevel(state));
93
+ this._bindSensorCharacteristic(service, Characteristic.StatusLowBattery, state => {
94
+ const states = this._sensorValues('dpBatteryState', ['battery_state'], state);
95
+ if (states.length) {
96
+ if (states[0] === 'low') return Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
97
+ if (['middle', 'medium', 'high', 'normal', 'full'].includes(states[0])) return Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
98
+ throw this._commError();
99
+ }
100
+ const threshold = Math.min(100, Math.max(0, this._coerceNumber(this.device.context.lowBatteryThreshold, 20)));
101
+ return this._sensorBatteryLevel(state) <= threshold
102
+ ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
103
+ });
104
+ this._bindSensorCharacteristic(service, Characteristic.ChargingState, state => {
105
+ const values = this._sensorValues('dpCharging', ['charge_state'], state);
106
+ if (!values.length) return Characteristic.ChargingState.NOT_CHARGEABLE;
107
+ const charging = TuyaSensorAccessory.booleanValue(values[0]);
108
+ if (charging === undefined) throw this._commError();
109
+ return charging ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING;
110
+ });
111
+ }
112
+
113
+ _sensorBatteryLevel(state = this._sensorState) {
114
+ const value = this._sensorValues('dpBattery', BATTERY_CODES, state)[0];
115
+ const divisor = Number(this.device.context.batteryDivisor ?? 1);
116
+ if ((typeof value !== 'number' && (typeof value !== 'string' || value.trim() === ''))
117
+ || !Number.isFinite(Number(value)) || !Number.isFinite(divisor) || divisor <= 0) throw this._commError();
118
+ return Math.min(100, Math.max(0, Number(value) / divisor));
119
+ }
120
+
121
+ static booleanValue(value) {
122
+ if ([true, 1, '1', 'true'].includes(value)) return 1;
123
+ if ([false, 0, '0', 'false'].includes(value)) return 0;
124
+ return undefined;
125
+ }
126
+
127
+ static alarmValue(value) {
128
+ if (value === 'alarm') return 1;
129
+ if (value === 'normal') return 0;
130
+ return TuyaSensorAccessory.booleanValue(value);
131
+ }
132
+ }
133
+
134
+ module.exports = TuyaSensorAccessory;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "homebridge-tuya-plus",
3
- "version": "4.3.0-dev.100",
3
+ "version": "4.3.0-dev.103",
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": {
@@ -0,0 +1,197 @@
1
+ 'use strict';
2
+
3
+ const EventEmitter = require('events');
4
+ const ContactSensorAccessory = require('../lib/ContactSensorAccessory');
5
+ const SmokeSensorAccessory = require('../lib/SmokeSensorAccessory');
6
+ const LeakSensorAccessory = require('../lib/LeakSensorAccessory');
7
+ const TuyaCloudDevice = require('../lib/TuyaCloudDevice');
8
+ const {HAP, makeInstance, makeMockService, makeMockCharacteristic} = require('./support/mocks');
9
+
10
+ const TYPES = [ContactSensorAccessory, SmokeSensorAccessory, LeakSensorAccessory];
11
+
12
+ function sensorFixture(Type, state, context = {}) {
13
+ const fixture = makeInstance(Type, state, context);
14
+ const services = new Map();
15
+ function service(type, name) {
16
+ const result = makeMockService(type.UUID);
17
+ result.displayName = name;
18
+ result.chars = new Map();
19
+ result.getCharacteristic.mockImplementation(characteristic => {
20
+ if (!result.chars.has(characteristic.UUID)) result.chars.set(characteristic.UUID, makeMockCharacteristic());
21
+ return result.chars.get(characteristic.UUID);
22
+ });
23
+ services.set(type.UUID, result);
24
+ return result;
25
+ }
26
+ service(HAP.Service[Type.sensor.service], fixture.device.context.name);
27
+ fixture.accessory.getService.mockImplementation(type => services.get(type.UUID));
28
+ fixture.accessory.addService.mockImplementation(service);
29
+ fixture.instance._registerCharacteristics(state);
30
+ const callback = fixture.device.on.mock.calls.find(([event]) => event === 'change')[1];
31
+ const change = updates => {
32
+ Object.assign(fixture.device.state, updates);
33
+ callback(updates, {...fixture.device.state});
34
+ };
35
+ const characteristic = (serviceName, characteristicName) =>
36
+ services.get(HAP.Service[serviceName].UUID).chars.get(HAP.Characteristic[characteristicName].UUID);
37
+ const main = characteristic(Type.sensor.service, Type.sensor.characteristic);
38
+ const read = char => char.onGet.mock.calls[0][0]();
39
+ return {...fixture, services, change, characteristic, main, read};
40
+ }
41
+
42
+ describe.each(TYPES)('%s read-only sensor', Type => {
43
+ const code = Type.sensor.codes[0];
44
+ const initial = Type === ContactSensorAccessory ? false : 'normal';
45
+
46
+ test('creates its service and registers one accessory', () => {
47
+ const {instance, accessory, platform} = makeInstance(Type);
48
+ instance._registerPlatformAccessory();
49
+ expect(accessory.addService).toHaveBeenCalledWith(HAP.Service[Type.sensor.service], 'Test Device');
50
+ expect(platform.registerPlatformAccessories).toHaveBeenCalledTimes(1);
51
+ });
52
+
53
+ test('has no battery service until battery telemetry is reported', () => {
54
+ const {services} = sensorFixture(Type, {[code]: initial});
55
+ expect(services.has(HAP.Service.Battery.UUID)).toBe(false);
56
+ });
57
+
58
+ test('keeps state through unrelated partial updates and never writes commands', async () => {
59
+ const {main, read, change, device} = sensorFixture(Type, {[code]: initial});
60
+ change({unrelated: 50});
61
+ await expect(read(main)).resolves.toBe(0);
62
+ expect(main.onSet).not.toHaveBeenCalled();
63
+ expect(device.update).not.toHaveBeenCalled();
64
+ });
65
+
66
+ test('does not turn an unknown or missing reading into a safe state', async () => {
67
+ const fixture = sensorFixture(Type, {});
68
+ await expect(fixture.read(fixture.main)).rejects.toMatchObject({hapStatus: -70402});
69
+ fixture.change({[code]: 'unsupported-state'});
70
+ await expect(fixture.read(fixture.main)).rejects.toMatchObject({hapStatus: -70402});
71
+ expect(fixture.main.updateValue).toHaveBeenLastCalledWith(expect.objectContaining({hapStatus: -70402}));
72
+ });
73
+
74
+ test('reports No Response after disconnecting', async () => {
75
+ const fixture = sensorFixture(Type, {[code]: initial});
76
+ fixture.device.connected = false;
77
+ await expect(fixture.read(fixture.main)).rejects.toMatchObject({hapStatus: -70402});
78
+ });
79
+
80
+ test('accepts a numeric LAN DP override', async () => {
81
+ const fixture = sensorFixture(Type, {'7': initial}, {[Type.sensor.option]: 7});
82
+ await expect(fixture.read(fixture.main)).resolves.toBe(0);
83
+ fixture.change({'7': Type === ContactSensorAccessory ? true : 'alarm'});
84
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
85
+ });
86
+
87
+ test('accepts a custom cloud code without requiring a numeric shadow mapping', async () => {
88
+ const fixture = sensorFixture(Type, {custom_code: initial}, {[Type.sensor.option]: 'custom_code'});
89
+ await expect(fixture.read(fixture.main)).resolves.toBe(0);
90
+ });
91
+ });
92
+
93
+ describe('contact mapping from 0x5e', () => {
94
+ test.each([true, 1, '1', 'true'])('%s means contact not detected (open)', async value => {
95
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: value});
96
+ await expect(fixture.read(fixture.main)).resolves.toBe(HAP.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED);
97
+ });
98
+ test.each([false, 0, '0', 'false'])('%s means contact detected (closed)', async value => {
99
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: value});
100
+ await expect(fixture.read(fixture.main)).resolves.toBe(HAP.Characteristic.ContactSensorState.CONTACT_DETECTED);
101
+ });
102
+ test('falls back to switch and prefers doorcontact_state when both exist', async () => {
103
+ const fixture = sensorFixture(ContactSensorAccessory, {switch: true});
104
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
105
+ fixture.change({doorcontact_state: false});
106
+ await expect(fixture.read(fixture.main)).resolves.toBe(0);
107
+ });
108
+ });
109
+
110
+ describe.each([SmokeSensorAccessory, LeakSensorAccessory])('%s alarm mappings', Type => {
111
+ test.each(Type.sensor.codes)('supports %s', async code => {
112
+ const fixture = sensorFixture(Type, {[code]: 'alarm'});
113
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
114
+ fixture.change({[code]: 'normal'});
115
+ await expect(fixture.read(fixture.main)).resolves.toBe(0);
116
+ });
117
+ test.each(['1', 1, true])('accepts alarm value %s', async value => {
118
+ const fixture = sensorFixture(Type, {[Type.sensor.codes[0]]: value});
119
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
120
+ });
121
+ });
122
+
123
+ test('a leak alarm wins over normal or malformed readings from other channels', async () => {
124
+ const fixture = sensorFixture(LeakSensorAccessory, {gas_sensor_status: 'normal', watersensor_state: 'alarm'});
125
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
126
+ fixture.change({gas_sensor_status: 'unsupported'});
127
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
128
+ fixture.change({watersensor_state: 'normal'});
129
+ await expect(fixture.read(fixture.main)).rejects.toMatchObject({hapStatus: -70402});
130
+ });
131
+
132
+ describe('sensor battery telemetry', () => {
133
+ test.each(['battery_percentage', 'residual_electricity', 'wireless_electricity', 'va_battery', 'battery'])('supports %s', async code => {
134
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: false, [code]: 65});
135
+ await expect(fixture.read(fixture.characteristic('Battery', 'BatteryLevel'))).resolves.toBe(65);
136
+ });
137
+ test('adds battery telemetry when it arrives after initial registration', async () => {
138
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: false});
139
+ fixture.change({battery_percentage: 20});
140
+ await expect(fixture.read(fixture.characteristic('Battery', 'StatusLowBattery'))).resolves.toBe(1);
141
+ fixture.change({battery_percentage: 21});
142
+ await expect(fixture.read(fixture.characteristic('Battery', 'StatusLowBattery'))).resolves.toBe(0);
143
+ });
144
+ test('battery_state takes precedence over the percentage threshold', async () => {
145
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: false, battery_percentage: 80, battery_state: 'low'});
146
+ const status = fixture.characteristic('Battery', 'StatusLowBattery');
147
+ await expect(fixture.read(status)).resolves.toBe(1);
148
+ fixture.change({battery_percentage: 5, battery_state: 'high'});
149
+ await expect(fixture.read(status)).resolves.toBe(0);
150
+ });
151
+ test('supports scaled percentages, threshold overrides, and charging', async () => {
152
+ const fixture = sensorFixture(ContactSensorAccessory, {'1': true, '2': 250, '3': true},
153
+ {dpContact: 1, dpBattery: 2, dpCharging: 3, batteryDivisor: 10, lowBatteryThreshold: 30});
154
+ await expect(fixture.read(fixture.characteristic('Battery', 'BatteryLevel'))).resolves.toBe(25);
155
+ await expect(fixture.read(fixture.characteristic('Battery', 'StatusLowBattery'))).resolves.toBe(1);
156
+ await expect(fixture.read(fixture.characteristic('Battery', 'ChargingState'))).resolves.toBe(1);
157
+ });
158
+ test('non-rechargeable sensors do not claim to be charging', async () => {
159
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: false, battery_percentage: 60});
160
+ await expect(fixture.read(fixture.characteristic('Battery', 'ChargingState'))).resolves.toBe(2);
161
+ });
162
+ test('invalid telemetry reports No Response instead of a normal battery', async () => {
163
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: false, battery_percentage: 'invalid'});
164
+ await expect(fixture.read(fixture.characteristic('Battery', 'BatteryLevel'))).rejects.toMatchObject({hapStatus: -70402});
165
+ await expect(fixture.read(fixture.characteristic('Battery', 'StatusLowBattery'))).rejects.toMatchObject({hapStatus: -70402});
166
+ });
167
+ test('noBattery disables the service', () => {
168
+ const fixture = sensorFixture(ContactSensorAccessory, {doorcontact_state: false, battery_percentage: 60}, {noBattery: true});
169
+ expect(fixture.services.has(HAP.Service.Battery.UUID)).toBe(false);
170
+ });
171
+ });
172
+
173
+ describe.each(TYPES)('%s cloud-only updates', Type => {
174
+ test('maps initial cloud status and MQTT updates without sending commands', async () => {
175
+ const code = Type.sensor.codes[0];
176
+ const api = {
177
+ isConfigured: () => true,
178
+ getStatus: jest.fn().mockResolvedValue([{code, value: Type === ContactSensorAccessory ? false : 'normal'}]),
179
+ getDeviceInfo: jest.fn().mockResolvedValue({online: true}),
180
+ sendCommands: jest.fn(),
181
+ };
182
+ const messaging = new EventEmitter();
183
+ messaging.subscribeDevice = jest.fn();
184
+ const log = {debug() {}, info() {}, warn() {}, error() {}};
185
+ const backend = new TuyaCloudDevice({id: 'fixture-sensor', name: 'Fixture', cloudApi: api, messaging, log, connect: false});
186
+ await backend._connect();
187
+ const fixture = sensorFixture(Type, backend.state);
188
+ backend.on('change', fixture.change);
189
+ await expect(fixture.read(fixture.main)).resolves.toBe(0);
190
+ const realtime = messaging.subscribeDevice.mock.calls[0][1];
191
+ realtime([{code, value: Type === ContactSensorAccessory ? true : 'alarm'}]);
192
+ await expect(fixture.read(fixture.main)).resolves.toBe(1);
193
+ expect(api.sendCommands).not.toHaveBeenCalled();
194
+ expect(fixture.device.update).not.toHaveBeenCalled();
195
+ backend.stop();
196
+ });
197
+ });
@@ -37,6 +37,9 @@ const CLASS_DEF = {
37
37
  doorbell: require('../lib/DoorbellAccessory'),
38
38
  verticalblindswithtilt: require('../lib/VerticalBlindsWithTilt'),
39
39
  percentblinds: require('../lib/PercentBlindsAccessory'),
40
+ contactsensor: require('../lib/ContactSensorAccessory'),
41
+ smokesensor: require('../lib/SmokeSensorAccessory'),
42
+ leaksensor: require('../lib/LeakSensorAccessory'),
40
43
  };
41
44
 
42
45
  const validCategoryValues = new Set(Object.values(Categories));
@@ -43,6 +43,7 @@ const HAP = {
43
43
  OccupancyDetected: { UUID: '71', OCCUPANCY_NOT_DETECTED: 0, OCCUPANCY_DETECTED: 1 },
44
44
  CurrentAmbientLightLevel: { UUID: '6B' },
45
45
  LeakDetected: { UUID: '70', LEAK_NOT_DETECTED: 0, LEAK_DETECTED: 1 },
46
+ SmokeDetected: { UUID: '76', SMOKE_NOT_DETECTED: 0, SMOKE_DETECTED: 1 },
46
47
  HeatingThresholdTemperature: { UUID: '12' },
47
48
  CoolingThresholdTemperature: { UUID: '0D' },
48
49
  CurrentTemperature: { UUID: '11' },
@@ -74,6 +75,7 @@ const HAP = {
74
75
  OccupancySensor: { UUID: '86' },
75
76
  LightSensor: { UUID: '84' },
76
77
  LeakSensor: { UUID: '83' },
78
+ SmokeSensor: { UUID: '87' },
77
79
  Doorbell: { UUID: '41' },
78
80
  AccessoryInformation: { UUID: '3E' },
79
81
  },
@@ -0,0 +1,58 @@
1
+ # Contact, smoke, and leak sensors
2
+
3
+ Use `ContactSensor`, `SmokeSensor`, or `LeakSensor` in the `TuyaLan` platform's
4
+ `devices` list. These read-only accessories work through the existing cloud
5
+ transport, including devices behind a gateway that cannot be reached over the LAN.
6
+ Configure the platform's [cloud credentials](Tuya-Cloud-Setup.md), and omit the
7
+ device's local `key` to keep it cloud-only:
8
+
9
+ ```json
10
+ {
11
+ "type": "ContactSensor",
12
+ "name": "Front Door",
13
+ "id": "YOUR_DEVICE_ID"
14
+ }
15
+ ```
16
+
17
+ | Type | Default cloud codes | Detected state | Override |
18
+ | --- | --- | --- | --- |
19
+ | `ContactSensor` | `doorcontact_state`, then `switch` | `true` means open | `dpContact` |
20
+ | `SmokeSensor` | `smoke_sensor_status`, then `smoke_sensor_state` | `alarm` or `1` | `dpSmoke` |
21
+ | `LeakSensor` | `gas_sensor_status`, `gas_sensor_state`, `ch4_sensor_state`, `watersensor_state` | Any reported alarm | `dpLeak` |
22
+
23
+ The contact handler accepts booleans and their `0`/`1` or `false`/`true` string
24
+ equivalents. Smoke and leak handlers also accept `alarm`/`normal`. Missing or
25
+ unrecognized readings report No Response instead of being interpreted as safe.
26
+ An alarm on one leak data point takes precedence over other readings.
27
+
28
+ Custom data-point settings accept cloud codes or numeric LAN IDs. For a LAN
29
+ device, supply its local key and the matching numeric override. No device commands
30
+ are sent by these sensor handlers. Cloud updates use the existing MQTT stream;
31
+ the handlers add no polling.
32
+
33
+ ## Battery
34
+
35
+ A battery service is added when a percentage data point is reported:
36
+ `battery_percentage`, `residual_electricity`, `wireless_electricity`, `va_battery`,
37
+ or `battery`. It can also appear when that reading arrives after the sensor's
38
+ initial update.
39
+
40
+ - `dpBattery`: override the percentage data point.
41
+ - `batteryDivisor`: divide the raw percentage by this value; default `1`.
42
+ - `dpBatteryState`: override `battery_state`. Its `low` state takes precedence
43
+ over the percentage threshold; `middle`, `medium`, `high`, `normal`, and `full`
44
+ are normal battery states.
45
+ - `lowBatteryThreshold`: percentage at or below which to report low battery when
46
+ no battery-state code is present; default `20`.
47
+ - `dpCharging`: override `charge_state`. Devices without that reading report
48
+ Not Chargeable.
49
+ - `noBattery`: disable the battery service.
50
+
51
+ ## Attribution and migration
52
+
53
+ The cloud codes and battery mappings come from 0x5e's Tuya platform plugin;
54
+ Eliran Sapir adapted them for Tuya Plus. See [third-party notices](../THIRD_PARTY_NOTICES.md).
55
+
56
+ This adds device support, not an automatic migration from another plugin. Existing
57
+ accessory UUIDs, child-bridge pairing, and service IDs need separate migration work
58
+ to preserve HomeKit rooms and automations.