diff --git a/README.md b/README.md index a636b31..aed13a4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Show the readings Indigo leaves out when it does not fully know a Z-Wave sensor, as Indigo devices of their own.** -**Version:** 5.15 | **Author:** CliveS & Claude | **Needs:** Indigo 2022.1 or later, with a Z-Wave interface +**Version:** 5.16 | **Author:** CliveS & Claude | **Needs:** Indigo 2022.1 or later, with a Z-Wave interface **[Read the full guide](https://highsteads.github.io/UniversalZWaveSensor/)** — setting up, what everything means, and what to do when something goes wrong. @@ -53,6 +53,8 @@ The [full guide](https://highsteads.github.io/UniversalZWaveSensor/) goes throug ## What's new +**v5.16** — Some sensor readings were filed under the wrong name. A water sensor using the older binary report showed as **Tamper** rather than **Water Leak**, a tamper showed as **Motion**, and readings such as current, voltage and CO2 landed in the wrong state, so a plug's current in amps appeared as its power in watts. The plugin's lookup tables now follow the Z-Wave standard. A reading the plugin has no state for is now reported as unknown rather than stored somewhere wrong. + **v5.15** — A sensor's **Online** state now says online from the moment the plugin starts it, and whenever it reports, so **Show Status** no longer calls a working sensor offline. A lock's **Latch Closed** state no longer shows the opposite of the truth. One of the sample messages in **Simulate Z-Wave Report** was labelled the wrong way round, and the old manual inside the plugin has gone, as the guide replaces it. **v5.14** — The settings window was wider than the screen allowed, so the help text beside each setting was cut off. The help now wraps to fit. No setting or behaviour changed. diff --git a/UniversalZWaveSensor.indigoPlugin/Contents/Info.plist b/UniversalZWaveSensor.indigoPlugin/Contents/Info.plist index 6b021e5..dd34b99 100644 --- a/UniversalZWaveSensor.indigoPlugin/Contents/Info.plist +++ b/UniversalZWaveSensor.indigoPlugin/Contents/Info.plist @@ -27,7 +27,7 @@ IwsApiVersion 1.0.0 PluginVersion - 5.15 + 5.16 ServerApiVersion 3.0 diff --git a/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/plugin.py b/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/plugin.py index bdb130c..9d31651 100644 --- a/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/plugin.py +++ b/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/plugin.py @@ -6,8 +6,26 @@ # (temperature, humidity, contact, etc.) that Indigo does not expose # natively. Uses subscribeToIncoming() to receive ALL Z-Wave bytes. # Author: CliveS & Claude Opus 4.8, Claude Opus 5.5 -# Date: 27-09-2026 -# Version: 5.15 +# Date: 01-11-2026 +# Version: 5.16 +# +# v5.16 (01-11-2026): the two Z-Wave code tables now follow the Z-Wave standard +# (checked against the zwave-js project's definitions). +# * SENSOR_BINARY types: 0x06 is Water (was read as tamper), 0x08 is Tamper (was +# motion), 0x04 is CO2 (was a water leak), and 0x09 Aux / 0x0B Tilt are no +# longer read as motion. Types the plugin has no state for (CO2, heat, freeze, +# aux, tilt, glass break) set only the primary on/off state, as an unknown +# type always has. +# * SENSOR_MULTILEVEL types: right up to 0x09 before, but from 0x0B nearly every +# entry named the wrong reading, e.g. Current (0x10) was written to watts and +# CO2 (0x11) to UV index. Corrected, with velocity (0x06), loudness (0x1E), +# target temperature (0x22), PM2.5 (0x23) and VOC (0x27) at their real codes. +# Codes with no matching state (dew point, weight, tank capacity, angle, +# seismic intensity, resistivity) are now reported as unknown instead of +# being written to an unrelated state. +# * Each reading's unit follows the scale the sensor sends: millivolts and +# milliamps are converted to V and A so the voltage and current states stay +# in one unit, and a target temperature is converted like a temperature. # # v5.15 (27-09-2026): Online state set True when a device starts or reports, # False only on the stale path; simulateReport example for "motion cleared" @@ -174,41 +192,62 @@ # key -> (state_id, default_unit) # ============================================================================== SENSOR_TYPES = { + # Codes per the Z-Wave Sensor Multilevel command class (zwave-js + # Sensors.ts, checked 01-11-2026). Before v5.16 the entries from 0x0B up + # named the wrong reading. A code not listed here is logged as unknown. 0x01: ("temperature", "degC"), 0x03: ("luminance", "lux"), - 0x04: ("watts", "W"), # general power (alt to type 0x10) + 0x04: ("watts", "W"), # power 0x05: ("humidity", "%"), - 0x08: ("pressure", "kPa"), - 0x09: ("atmosphericPressure", "kPa"), # scale=1 -> inHg - 0x0B: ("velocity", "m/s"), - 0x0E: ("targetTemperature", "degC"), # thermostat-style target temp via multilevel - 0x0F: ("co2Level", "ppm"), - 0x10: ("watts", "W"), # power (reuses energy meter state) - 0x11: ("uvIndex", ""), - 0x12: ("voltage", "V"), # reuses meter voltage state - 0x13: ("current", "A"), # reuses meter current state - 0x15: ("airFlow", "m3/h"), - 0x19: ("voc", "ppm"), - 0x1B: ("noise", "dB"), - 0x1C: ("soilMoisture", "%"), - 0x1F: ("pm25", "ug/m3"), + 0x06: ("velocity", "m/s"), + 0x08: ("pressure", "kPa"), # atmospheric pressure + 0x09: ("atmosphericPressure", "kPa"), # barometric pressure; scale=1 -> inHg + 0x0F: ("voltage", "V"), + 0x10: ("current", "A"), + 0x11: ("co2Level", "ppm"), + 0x12: ("airFlow", "m3/h"), + 0x1B: ("uvIndex", ""), + 0x1E: ("noise", "dB"), # loudness + 0x1F: ("soilMoisture", "%"), # moisture + 0x22: ("targetTemperature", "degC"), + 0x23: ("pm25", "ug/m3"), + 0x27: ("voc", "ppm"), +} + +# Scales other than 0 for the codes above, as (unit, multiplier). The value is +# multiplied so a state keeps one unit whatever the sensor sends: millivolts and +# milliamps become V and A. A scale missing here keeps the default unit. +# (Temperature, target temperature and luminance are handled in the parser.) +SENSOR_SCALES = { + 0x06: {1: ("mph", 1.0)}, + 0x0F: {1: ("V", 0.001)}, # millivolts + 0x10: {1: ("A", 0.001)}, # milliamps + 0x12: {1: ("cfm", 1.0)}, + 0x1E: {1: ("dBA", 1.0)}, + 0x1F: {1: ("m3/m3", 1.0), 2: ("kOhm", 1.0), 3: ("aw", 1.0)}, + 0x23: {0: ("mol/m3", 1.0), 1: ("ug/m3", 1.0)}, + 0x27: {0: ("mol/m3", 1.0), 1: ("ppm", 1.0)}, } +TEMPERATURE_TYPES = (0x01, 0x22) # converted to the user's degC / degF # ============================================================================== # SENSOR_BINARY (0x30) sensor type lookup # key -> state_id # ============================================================================== +# Codes per the Z-Wave Sensor Binary command class (zwave-js BinarySensorType, +# checked 01-11-2026): 0x01 general purpose, 0x02 smoke, 0x03 CO, 0x04 CO2, +# 0x05 heat, 0x06 water, 0x07 freeze, 0x08 tamper, 0x09 aux, 0x0A door/window, +# 0x0B tilt, 0x0C motion, 0x0D glass break. Before v5.16 several were wrong (a +# water report set "tamper", a tamper report set "motion"). Codes with no state +# of their own here fall back to onOffState in _handle_binary_sensor. BINARY_SENSOR_TYPES = { 0x01: "onOffState", # general purpose 0x02: "smoke", - 0x03: "coAlarm", - 0x04: "waterLeak", - 0x06: "tamper", - 0x08: "motion", - 0x09: "motion", # PIR alternative + 0x03: "coAlarm", # CO (carbon monoxide) + 0x06: "waterLeak", # water + 0x08: "tamper", 0x0A: "contact", # door / window - 0x0B: "motion", # movement alternative - 0x0C: "motion", # motion sensor (Z-Wave SENSOR_BINARY v2 type 0x0C) + 0x0C: "motion", } # ============================================================================== @@ -966,7 +1005,7 @@ def _handle_multilevel(self, device, raw) -> bool: state_key, default_unit = SENSOR_TYPES[sensor_type] # Resolve unit; apply temperature unit preference with conversion if needed - if sensor_type == 0x01: # temperature + if sensor_type in TEMPERATURE_TYPES: # temperature, target temperature reported_unit = "degC" if scale == 0 else "degF" if reported_unit != self.temp_unit: if self.temp_unit == "degF": @@ -977,6 +1016,11 @@ def _handle_multilevel(self, device, raw) -> bool: unit = self.temp_unit elif sensor_type == 0x03: # luminance unit = "%" if scale == 0 else "lux" + elif scale in SENSOR_SCALES.get(sensor_type, {}): + unit, factor = SENSOR_SCALES[sensor_type][scale] + if factor != 1.0: + value = value * factor + precision += 3 # mV -> V keeps its resolution else: unit = default_unit @@ -2253,7 +2297,7 @@ def updateStateImageOnServer(self, sel): ("Meter power 1500W", "32 02 01 12 05 DC", "watts"), ("Barrier open", "66 03 FF", "contact"), ("Central scene 2x", "5B 03 02 03 02", "lastSceneAction"), - ("Supervision+motion", "6C 01 2A 04 30 03 FF 08", "motion"), + ("Supervision+motion", "6C 01 2A 04 30 03 FF 0C", "motion"), ] w = 78 diff --git a/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/test_plugin.py b/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/test_plugin.py index 554e772..bc20058 100644 --- a/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/test_plugin.py +++ b/UniversalZWaveSensor.indigoPlugin/Contents/Server Plugin/test_plugin.py @@ -803,9 +803,9 @@ def test_humidity_icon_from_raw_path(self): self.assertNotIn("SensorOn", dev.image_writes) def test_co2_850_ppm(self): - """850 ppm CO2: sensor=0x0F, precision=0, scale=0, size=2""" + """850 ppm CO2: sensor=0x11 (CO2 in the Z-Wave standard), precision=0, scale=0, size=2""" pss = self._prec_scale_size(0, 0, 2) - raw = [0x31, 0x05, 0x0F, pss] + list(struct.pack(">H", 850)) + raw = [0x31, 0x05, 0x11, pss] + list(struct.pack(">H", 850)) dev = self._dev("generic") self.assertTrue(self.p._handle_multilevel(dev, raw)) self.assertAlmostEqual(dev.state_writes["co2Level"]["value"], 850.0) @@ -842,16 +842,16 @@ def _dev(self, sensor_type="generic"): plugin_props={"sensorType": sensor_type}) def test_motion_detected(self): - """0xFF + type=0x08 (PIR) -> motion=True, displayStatus=detected.""" + """0xFF + type=0x0C (Motion) -> motion=True, displayStatus=detected.""" dev = self._dev("motion") - self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x08])) + self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x0C])) self.assertTrue(dev.state_writes["motion"]["value"]) self.assertEqual(dev.state_writes["displayStatus"]["value"], "detected") def test_motion_clear(self): - """0x00 + type=0x08 -> motion=False, displayStatus=clear.""" + """0x00 + type=0x0C -> motion=False, displayStatus=clear.""" dev = self._dev("motion") - self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0x00, 0x08])) + self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0x00, 0x0C])) self.assertFalse(dev.state_writes["motion"]["value"]) self.assertEqual(dev.state_writes["displayStatus"]["value"], "clear") @@ -870,9 +870,9 @@ def test_contact_closed(self): self.assertEqual(dev.state_writes["displayStatus"]["value"], "closed") def test_water_leak(self): - """0xFF + type=0x04 -> waterLeak=True, displayStatus=leak.""" + """0xFF + type=0x06 (Water) -> waterLeak=True, displayStatus=leak.""" dev = self._dev("generic") - self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x04])) + self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x06])) self.assertTrue(dev.state_writes["waterLeak"]["value"]) self.assertEqual(dev.state_writes["waterLeak"]["uiValue"], "leak") @@ -883,9 +883,9 @@ def test_smoke_alarm(self): self.assertTrue(dev.state_writes["smoke"]["value"]) def test_tamper(self): - """0xFF + type=0x06 -> tamper=True.""" + """0xFF + type=0x08 (Tamper) -> tamper=True.""" dev = self._dev("generic") - self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x06])) + self.assertTrue(self.p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x08])) self.assertTrue(dev.state_writes["tamper"]["value"]) def test_v1_no_type_byte_fallback(self): @@ -2002,7 +2002,7 @@ def setUp(self): self.p = make_plugin() def test_crc16_multichannel_supervision_nest(self): - inner = [0x30, 0x03, 0xFF, 0x08] # SENSOR_BINARY motion active + inner = [0x30, 0x03, 0xFF, 0x0C] # SENSOR_BINARY motion (type 0x0C) active sup = [0x6C, 0x01, 0x2A, len(inner)] + inner mc = [0x60, 0x0D, 0x01, 0x00] + sup # src_ep=1 crc = [0x56, 0x01] + mc + [0xAB, 0xCD] diff --git a/docs/changelog.md b/docs/changelog.md index 959b774..a44198f 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -7,6 +7,15 @@ nav_order: 10 The newest version is at the top. +## 5.16 — 1 November 2026 + +- **Sensor readings are filed under the right name.** A sensor says what kind of reading it is sending with a code number, and two of the plugin's lookup tables had several codes wrong: + - From a sensor using the older on/off (binary) report, a **water leak** set **Tamper** instead of **Water Leak**, and a **tamper** (the cover being removed) set **Motion**. A CO2 alarm set **Water Leak**, and aux and tilt reports set **Motion**. + - Among measured readings, temperature, light, power, humidity and pressure were right, but most of the rest were not: **current** was stored as power in watts, **voltage** as CO2, **CO2** as UV index, and so on. + - Both tables now follow the Z-Wave standard. Check any trigger you built on one of the affected states, because it will now see the reading it was meant to. +- A reading the plugin has no state for, such as dew point or weight, is now reported in the Event Log as unknown rather than being stored in an unrelated state. A binary report the plugin has no state for (CO2, heat, freeze, aux, tilt, glass break) changes only the device's on/off state. +- Voltage and current sent in millivolts or milliamps are stored in volts and amps, so the states keep one unit. A thermostat's target temperature sent in Fahrenheit is converted like any other temperature. + ## 5.15 — 27 September 2026 - A sensor's **Online** state now shows online as soon as the plugin starts the device, and again every time the sensor reports. Before, it only changed when a sensor went quiet or came back, so a sensor that had never gone quiet could be listed as offline in **Show Status**. A sensor still shows offline when it has sent nothing for longer than the **Stale threshold**. diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..2e86f7c --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,23 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +# Filename: conftest.py +# Description: Shared seam for the tests in tests/. Puts the bundle's +# "Server Plugin" folder on sys.path and imports the bundle's own +# test_plugin.py, which installs the ONE indigo stand-in this +# suite uses (a MagicMock with real kStateImageSel names), so +# plugin.py can be imported here with no Indigo server. Does not +# define a second stub. +# Author: CliveS & Claude Opus 5.5 +# Date: 01-11-2026 +# Version: 1.0 + +import os +import sys + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SERVER_PLUGIN = os.path.join(REPO_ROOT, "UniversalZWaveSensor.indigoPlugin", + "Contents", "Server Plugin") +if SERVER_PLUGIN not in sys.path: + sys.path.insert(0, SERVER_PLUGIN) + +import test_plugin # noqa: E402,F401 (installs sys.modules["indigo"]) diff --git a/tests/test_xml_callbacks_and_changelog.py b/tests/test_xml_callbacks_and_changelog.py new file mode 100644 index 0000000..c7e3a07 --- /dev/null +++ b/tests/test_xml_callbacks_and_changelog.py @@ -0,0 +1,71 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +# Filename: test_xml_callbacks_and_changelog.py +# Description: Generic checks this repo did not have yet: +# - every and every named in +# the XML exists on Plugin (a missing one only fails when the +# user opens that dialog or menu) +# - every state plugin.py writes by name is declared on at +# least one device type in Devices.xml +# - docs/changelog.md's newest entry is the version Info.plist +# ships +# Author: CliveS & Claude Opus 5.5 +# Date: 01-11-2026 +# Version: 1.0 + +import ast +import glob +import os +import plistlib +import re +import xml.etree.ElementTree as ET + +import plugin as plugin_module +from conftest import REPO_ROOT, SERVER_PLUGIN + +NATIVE_STATES = {"onOffState"} # supplied by Indigo for relay / sensor types + + +def _xml_root(name): + return ET.parse(os.path.join(SERVER_PLUGIN, name)).getroot() + + +def test_every_xml_callback_exists_on_the_plugin(): + named = [] + for path in sorted(glob.glob(os.path.join(SERVER_PLUGIN, "*.xml"))): + root = ET.parse(path).getroot() + for el in root.iter("CallbackMethod"): + named.append((os.path.basename(path), (el.text or "").strip())) + for el in root.iter("List"): + if el.get("method"): + named.append((os.path.basename(path), el.get("method"))) + assert len(named) >= 6, "expected the menu callbacks and the device pickers" + missing = [f"{f}: {m}" for f, m in named + if not callable(getattr(plugin_module.Plugin, m, None))] + assert not missing, f"XML names methods plugin.py does not define: {missing}" + + +def test_every_state_written_by_name_is_declared_somewhere(): + with open(os.path.join(SERVER_PLUGIN, "plugin.py"), encoding="utf-8") as fh: + tree = ast.parse(fh.read()) + written = set() + for node in ast.walk(tree): + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in ("updateStateOnServer", "_safe_update")): + args = node.args[1:] if node.func.attr == "_safe_update" else node.args + if args and isinstance(args[0], ast.Constant) and isinstance(args[0].value, str): + written.add(args[0].value) + declared = {s.get("id") for s in _xml_root("Devices.xml").iter("State")} + assert {"lastUpdate", "deviceOnline", "displayStatus"} <= written + undeclared = written - declared - NATIVE_STATES + assert not undeclared, f"written but declared on no device type: {sorted(undeclared)}" + + +def test_docs_changelog_newest_entry_is_this_version(): + plist = glob.glob(os.path.join(REPO_ROOT, "*.indigoPlugin", "Contents", "Info.plist"))[0] + with open(plist, "rb") as fh: + version = plistlib.load(fh)["PluginVersion"] + with open(os.path.join(REPO_ROOT, "docs", "changelog.md"), encoding="utf-8") as fh: + entries = re.findall(r"^##\s+v?(\d+(?:\.\d+)+)\b", fh.read(), re.M) + assert entries, "docs/changelog.md has no '## ' entries" + assert entries[0] == version, f"newest changelog entry {entries[0]}, Info.plist {version}" diff --git a/tests/test_zwave_code_tables.py b/tests/test_zwave_code_tables.py new file mode 100644 index 0000000..6e63e10 --- /dev/null +++ b/tests/test_zwave_code_tables.py @@ -0,0 +1,238 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +# Filename: test_zwave_code_tables.py +# Description: The plugin's Z-Wave code tables against the Z-Wave standard, and +# what the decoders do with real-shaped reports. +# +# Reference for the expected values: the zwave-js project's +# definitions, fetched 01-11-2026 — +# packages/cc/src/lib/_Types.ts (enum BinarySensorType) +# packages/core/src/registries/Sensors.ts (multilevel sensor types) +# packages/core/src/registries/Notifications.ts +# The two code tables were corrected in v5.16; BINARY_BUG and +# MULTILEVEL_BUG now record what the tests below guard against. +# The idle-event fault is still open and stays xfail(strict=True). +# Author: CliveS & Claude Opus 5.5 +# Date: 01-11-2026 +# Version: 1.1 + +import pytest + +import plugin as P +from test_plugin import MockDevice, make_plugin + +# ------------------------------------------------------------ the standard + +# Sensor Binary CC sensor types (zwave-js BinarySensorType). +BINARY_STANDARD = {0x01: "General purpose", 0x02: "Smoke", 0x03: "CO", 0x04: "CO2", + 0x05: "Heat", 0x06: "Water", 0x07: "Freeze", 0x08: "Tamper", + 0x09: "Aux", 0x0A: "Door/Window", 0x0B: "Tilt", 0x0C: "Motion", + 0x0D: "Glass break"} + +# Sensor Multilevel CC sensor types (zwave-js Sensors.ts). +MULTILEVEL_STANDARD = {0x01: "Air temperature", 0x03: "Illuminance", 0x04: "Power", + 0x05: "Humidity", 0x06: "Velocity", 0x08: "Atmospheric pressure", + 0x09: "Barometric pressure", 0x0B: "Dew point", 0x0E: "Weight", + 0x0F: "Voltage", 0x10: "Current", 0x11: "CO2 level", + 0x12: "Air flow", 0x13: "Tank capacity", 0x15: "Angle position", + 0x19: "Seismic intensity", 0x1B: "Ultraviolet", + 0x1C: "Electrical resistivity", 0x1F: "Moisture"} + +BINARY_BUG = ("Fixed in v5.16. BINARY_SENSOR_TYPES did not follow the Z-Wave Sensor Binary " + "types: 0x04 is CO2 (plugin: waterLeak), 0x06 is Water (plugin: " + "tamper), 0x08 is Tamper (plugin: motion), 0x09 Aux and 0x0B Tilt " + "(plugin: motion). A leak reported this way sets 'tamper', not " + "'waterLeak'; a cover-removed tamper sets 'motion'.") + +MULTILEVEL_BUG = ("Fixed in v5.16. SENSOR_TYPES was right up to 0x09 but wrong from 0x0B: 0x0F is " + "Voltage (plugin: co2Level), 0x10 Current (plugin: watts), 0x11 CO2 " + "(plugin: uvIndex), 0x12 Air flow (plugin: voltage), 0x13 Tank " + "capacity (plugin: current), 0x1B Ultraviolet (plugin: noise), " + "0x1F Moisture (plugin: pm25), and others.") + + +# ------------------------------------------------------------ what is right + +@pytest.mark.parametrize("code, key", [(0x02, "smoke"), (0x03, "coAlarm"), + (0x0A, "contact"), (0x0C, "motion")]) +def test_binary_types_the_plugin_has_right(code, key): + assert P.BINARY_SENSOR_TYPES[code] == key + + +@pytest.mark.parametrize("code, key", [(0x01, "temperature"), (0x03, "luminance"), + (0x04, "watts"), (0x05, "humidity")]) +def test_multilevel_types_the_plugin_has_right(code, key): + assert P.SENSOR_TYPES[code][0] == key + + +@pytest.mark.parametrize("name, code", [ + ("NOTIF_SMOKE", 0x01), ("NOTIF_CO", 0x02), ("NOTIF_WATER", 0x05), + ("NOTIF_ACCESS_CONTROL", 0x06), ("NOTIF_HOME_SECURITY", 0x07), + ("HS_INTRUSION", 0x01), ("HS_INTRUSION_NL", 0x02), ("HS_TAMPER", 0x03), + ("HS_GLASS_BREAK", 0x05), ("HS_GLASS_BREAK_NL", 0x06), + ("HS_MOTION_DETECTED", 0x07), ("HS_MOTION_DETECTED_NL", 0x08), + ("HS_TAMPER_ALT", 0x09), ("AC_DOOR_OPEN", 0x16), ("AC_DOOR_CLOSED", 0x17), +]) +def test_notification_codes_match_the_standard(name, code): + assert getattr(P, name) == code + + +# ------------------------------------------------------------ the binary table + +def test_binary_table_follows_the_standard(): + wrong = {code: P.BINARY_SENSOR_TYPES[code] for code in (0x04, 0x06, 0x08, 0x09, 0x0B) + if code in P.BINARY_SENSOR_TYPES} + expect = {0x06: "waterLeak", 0x08: "tamper"} + assert {k: v for k, v in wrong.items() if k in expect} == expect + assert P.BINARY_SENSOR_TYPES.get(0x04) != "waterLeak" + assert P.BINARY_SENSOR_TYPES.get(0x09) != "motion" + assert P.BINARY_SENSOR_TYPES.get(0x0B) != "motion" + + +def test_a_binary_water_report_sets_water_leak(): + p = make_plugin() + dev = MockDevice(1, "Kitchen Leak", plugin_props={"sensorType": "generic"}) + p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x06]) # type 0x06 = Water + assert dev.states.get("waterLeak") is True + + +def test_a_binary_tamper_report_is_not_motion(): + p = make_plugin() + dev = MockDevice(1, "Hall PIR", plugin_props={"sensorType": "generic"}) + p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, 0x08]) # type 0x08 = Tamper + assert dev.states.get("motion") is not True + assert dev.states.get("tamper") is True + + +# ------------------------------------------------------------ the multilevel table + +def test_multilevel_table_follows_the_standard(): + expect = {0x0F: "voltage", 0x10: "current", 0x11: "co2Level"} + assert {k: P.SENSOR_TYPES[k][0] for k in expect} == expect + + +def test_a_current_report_does_not_land_in_watts(): + p = make_plugin() + dev = MockDevice(1, "Kettle Plug", plugin_props={"sensorType": "energy"}) + # 0x10 Current, precision 1, scale 0 (A), size 2: 0x0005 -> 0.5 A + p._handle_multilevel(dev, [0x31, 0x05, 0x10, 0x22, 0x00, 0x05]) + assert "watts" not in dev.state_writes, "0.5 A was written as 0.5 W" + + +# ------------------------------------------------------------ idle events + +IDLE_BUG = ("BUG: a Home Security 'idle' notification (event 0x00) names the event " + "that ended in its first event parameter, but _handle_notification clears " + "motion AND tamper on every idle, and writes onOffState=False whatever the " + "device type. Motion ending clears a tamper that is still active.") + + +@pytest.mark.xfail(strict=True, reason=IDLE_BUG) +def test_motion_ending_does_not_clear_an_active_tamper(): + p = make_plugin() + dev = MockDevice(1, "Hall PIR", plugin_props={"sensorType": "motion"}) + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x07, 0x03, 0x00]) # cover off + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x07, 0x08, 0x00]) # motion + # idle, event parameter 0x08: motion has ended + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x07, 0x00, 0x01, 0x08]) + assert dev.states.get("motion") is False + assert dev.states.get("tamper") is True, "the cover is still off" + + +@pytest.mark.xfail(strict=True, reason=IDLE_BUG) +def test_a_tamper_clearing_does_not_close_a_door_contact(): + p = make_plugin() + dev = MockDevice(1, "Back Door", plugin_props={"sensorType": "contact"}) + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x06, 0x16, 0x00]) # door open + # Home Security idle, event parameter 0x03: the cover went back on + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x07, 0x00, 0x01, 0x03]) + assert dev.states.get("contact") is True + assert dev.states.get("onOffState") is True, "the door's primary state went to closed" + + +def test_a_plain_idle_still_clears_motion(): + """An idle with no event parameter (older devices) must keep clearing motion.""" + p = make_plugin() + dev = MockDevice(1, "Hall PIR", plugin_props={"sensorType": "motion"}) + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x07, 0x08, 0x00]) + p._handle_notification(dev, [0x71, 0x05, 0, 0, 0, 0xFF, 0x07, 0x00, 0x00]) + assert dev.states.get("motion") is False + + +# ------------------------------------------------------------ v5.16 additions + +def test_no_binary_code_maps_to_a_state_that_means_something_else(): + """Every code the table maps must name the same thing as the standard.""" + meaning = {"onOffState": "General purpose", "smoke": "Smoke", "coAlarm": "CO", + "waterLeak": "Water", "tamper": "Tamper", "contact": "Door/Window", + "motion": "Motion"} + for code, key in P.BINARY_SENSOR_TYPES.items(): + assert BINARY_STANDARD[code] == meaning[key], f"0x{code:02X} -> {key}" + + +def test_every_multilevel_code_names_the_reading_the_standard_gives_it(): + standard = {0x01: "temperature", 0x03: "luminance", 0x04: "watts", 0x05: "humidity", + 0x06: "velocity", 0x08: "pressure", 0x09: "atmosphericPressure", + 0x0F: "voltage", 0x10: "current", 0x11: "co2Level", 0x12: "airFlow", + 0x1B: "uvIndex", 0x1E: "noise", 0x1F: "soilMoisture", + 0x22: "targetTemperature", 0x23: "pm25", 0x27: "voc"} + assert {k: v[0] for k, v in P.SENSOR_TYPES.items()} == standard + + +@pytest.mark.parametrize("code", [0x0B, 0x0E, 0x13, 0x15, 0x19, 0x1C]) +def test_a_code_with_no_matching_state_is_reported_as_unknown(code): + p = make_plugin() + dev = MockDevice(1, "Odd Sensor", plugin_props={"sensorType": "generic"}) + assert p._handle_multilevel(dev, [0x31, 0x05, code, 0x01, 0x05]) is False + assert len(dev.state_writes) == 0 + + +def test_a_current_report_lands_in_current(): + p = make_plugin() + dev = MockDevice(1, "Kettle Plug", plugin_props={"sensorType": "energy"}) + p._handle_multilevel(dev, [0x31, 0x05, 0x10, 0x22, 0x00, 0x05]) # 0.5 A + assert dev.state_writes["current"]["value"] == 0.5 + assert dev.state_writes["current"]["uiValue"] == "0.5 A" + + +def test_millivolts_are_stored_as_volts(): + p = make_plugin() + dev = MockDevice(1, "Sensor", plugin_props={"sensorType": "generic"}) + # 0x0F Voltage, precision 0, scale 1 (mV), size 2: 3300 mV + p._handle_multilevel(dev, [0x31, 0x05, 0x0F, 0x0A, 0x0C, 0xE4]) + assert dev.state_writes["voltage"]["value"] == pytest.approx(3.3) + assert dev.state_writes["voltage"]["uiValue"] == "3.300 V" + + +def test_milliamps_are_stored_as_amps(): + p = make_plugin() + dev = MockDevice(1, "Sensor", plugin_props={"sensorType": "generic"}) + # 0x10 Current, precision 0, scale 1 (mA), size 2: 250 mA + p._handle_multilevel(dev, [0x31, 0x05, 0x10, 0x0A, 0x00, 0xFA]) + assert dev.state_writes["current"]["value"] == pytest.approx(0.25) + + +def test_pm25_takes_its_unit_from_the_scale(): + p = make_plugin() + dev = MockDevice(1, "Air", plugin_props={"sensorType": "generic"}) + # 0x23 PM2.5, precision 0, scale 1 (ug/m3), size 1: 12 + p._handle_multilevel(dev, [0x31, 0x05, 0x23, 0x09, 0x0C]) + assert dev.state_writes["pm25"]["uiValue"] == "12 ug/m3" + + +def test_a_target_temperature_in_fahrenheit_is_converted_like_a_temperature(): + p = make_plugin(temp_unit="degC") + dev = MockDevice(1, "Thermostat", plugin_props={"sensorType": "generic"}) + # 0x22 Target temperature, precision 0, scale 1 (degF), size 1: 68 F + p._handle_multilevel(dev, [0x31, 0x05, 0x22, 0x09, 0x44]) + assert dev.state_writes["targetTemperature"]["value"] == pytest.approx(20.0) + + +@pytest.mark.parametrize("code", [0x04, 0x05, 0x07, 0x09, 0x0B, 0x0D]) +def test_a_binary_type_with_no_state_of_its_own_only_sets_the_primary_state(code): + p = make_plugin() + dev = MockDevice(1, "Sensor", plugin_props={"sensorType": "generic"}) + p._handle_binary_sensor(dev, [0x30, 0x03, 0xFF, code]) + assert dev.state_writes["onOffState"]["value"] is True + for key in ("motion", "tamper", "waterLeak", "contact"): + assert key not in dev.state_writes, f"0x{code:02X} wrote {key}"