sc-smart-device 3.3.2__tar.gz → 3.3.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/PKG-INFO +1 -1
  2. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/pyproject.toml +1 -1
  3. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/providers/shelly_provider.py +74 -8
  4. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/providers/tasmota_provider.py +32 -2
  5. sc_smart_device-3.3.3/src/sc_smart_device/providers/temp_bounds.py +66 -0
  6. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/validation/smart_devices_validator.py +2 -0
  7. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device.egg-info/PKG-INFO +1 -1
  8. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device.egg-info/SOURCES.txt +2 -0
  9. sc_smart_device-3.3.3/tests/test_temp_bounds.py +177 -0
  10. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/README.md +0 -0
  11. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/setup.cfg +0 -0
  12. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/__init__.py +0 -0
  13. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/models/__init__.py +0 -0
  14. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/models/capabilities.py +0 -0
  15. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/models/smart_device_status.py +0 -0
  16. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/models/smart_device_view.py +0 -0
  17. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/models/worker_types.py +0 -0
  18. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/providers/__init__.py +0 -0
  19. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/providers/base_provider.py +0 -0
  20. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/shelly_models.json +0 -0
  21. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/smart_device.py +0 -0
  22. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/smart_device_worker.py +0 -0
  23. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/validation/__init__.py +0 -0
  24. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/webhooks/__init__.py +0 -0
  25. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device/webhooks/shelly_webhook_server.py +0 -0
  26. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device.egg-info/dependency_links.txt +0 -0
  27. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device.egg-info/not-zip-safe +0 -0
  28. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device.egg-info/requires.txt +0 -0
  29. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/src/sc_smart_device.egg-info/top_level.txt +0 -0
  30. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/tests/test_basic.py +0 -0
  31. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/tests/test_get_x_value.py +0 -0
  32. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/tests/test_smart_device_view.py +0 -0
  33. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/tests/test_tasmota.py +0 -0
  34. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/tests/test_webhooks.py +0 -0
  35. {sc_smart_device-3.3.2 → sc_smart_device-3.3.3}/tests/test_worker.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sc-smart-device
3
- Version: 3.3.2
3
+ Version: 3.3.3
4
4
  Summary: Provides a simple, consistent access to Shelly and Tasmota smart switches and energy meters.
5
5
  Project-URL: Homepage, https://github.com/Spello-Consulting
6
6
  Project-URL: Repository, https://github.com/Spello-Consulting/sc-smart-device
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sc-smart-device"
7
- version = "3.3.2"
7
+ version = "3.3.3"
8
8
  description = "Provides a simple, consistent access to Shelly and Tasmota smart switches and energy meters."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13"
@@ -16,6 +16,7 @@ from sc_foundation import DateHelper, SCCommon, SCLogger
16
16
  from sc_smart_device.models.capabilities import DeviceCapability
17
17
  from sc_smart_device.models.smart_device_status import SmartDeviceStatus
18
18
  from sc_smart_device.providers.base_provider import BaseProvider
19
+ from sc_smart_device.providers.temp_bounds import is_temp_in_bounds, temp_bounds_error
19
20
  from sc_smart_device.webhooks.shelly_webhook_server import _ShellyWebhookHandler
20
21
 
21
22
  SHELLY_MODEL_FILE = "shelly_models.json"
@@ -591,9 +592,7 @@ class ShellyProvider(BaseProvider):
591
592
  new_comp["OnOutput"] = not device["MetersSeperate"]
592
593
  new_comp["MockRate"] = (component_config[comp_idx].get("MockRate", 0) if component_config else 0)
593
594
  elif component_type == "temp_probe":
594
- new_comp["RequiresOutput"] = (component_config[comp_idx].get("RequiresOutput") if component_config else None)
595
- if new_comp["Name"] == device["Name"]:
596
- new_comp["ProbeID"] = -1
595
+ self._configure_temp_probe(new_comp, device, component_config[comp_idx] if component_config else {})
597
596
 
598
597
  new_comp["customkeylist"] = []
599
598
  if component_config:
@@ -613,6 +612,27 @@ class ShellyProvider(BaseProvider):
613
612
 
614
613
  storage.append(new_comp)
615
614
 
615
+ def _configure_temp_probe(self, new_comp: dict, device: dict, cfg: dict) -> None:
616
+ """Apply temp-probe-specific config (RequiresOutput, bounds) to a component.
617
+
618
+ Rejects the config (via ``_raise_runtime_error``) when both ``MinTemp``
619
+ and ``MaxTemp`` are set and ``MinTemp`` is not strictly less than
620
+ ``MaxTemp``.
621
+
622
+ Args:
623
+ new_comp: The component dict under construction.
624
+ device: The owning device dict.
625
+ cfg: The probe's config dict (empty if none supplied).
626
+ """
627
+ new_comp["RequiresOutput"] = cfg.get("RequiresOutput")
628
+ new_comp["MinTemp"] = cfg.get("MinTemp")
629
+ new_comp["MaxTemp"] = cfg.get("MaxTemp")
630
+ bounds_error = temp_bounds_error(new_comp["MinTemp"], new_comp["MaxTemp"], new_comp["Name"])
631
+ if bounds_error:
632
+ self._raise_runtime_error(bounds_error)
633
+ if new_comp["Name"] == device["Name"]:
634
+ new_comp["ProbeID"] = -1
635
+
616
636
  def _new_device_component(self, device_index: int, component_type: str) -> dict:
617
637
  device = self._devices[device_index]
618
638
  comp: dict = {
@@ -644,6 +664,8 @@ class ShellyProvider(BaseProvider):
644
664
  comp["Temperature"] = None
645
665
  comp["LastReadingTime"] = None
646
666
  comp["RequiresOutput"] = None
667
+ comp["MinTemp"] = None
668
+ comp["MaxTemp"] = None
647
669
  return comp
648
670
 
649
671
  # ── Internal — device status ─────────────────────────────────────────────────
@@ -739,10 +761,12 @@ class ShellyProvider(BaseProvider):
739
761
  if read_tp:
740
762
  probe_id = tp["ProbeID"]
741
763
  if probe_id == -1:
742
- tp["Temperature"] = device["Temperature"]
764
+ self._store_probe_reading(tp, device["Temperature"])
743
765
  elif probe_id is not None:
744
- tp["Temperature"] = result_data.get(f"temperature:{probe_id}", {}).get("tC")
745
- tp["LastReadingTime"] = DateHelper.now()
766
+ raw = result_data.get(f"temperature:{probe_id}", {}).get("tC")
767
+ self._store_probe_reading(tp, raw)
768
+ else:
769
+ tp["LastReadingTime"] = DateHelper.now()
746
770
 
747
771
  else: # REST (gen 1)
748
772
  device["MacAddress"] = result_data.get("mac")
@@ -1134,6 +1158,48 @@ class ShellyProvider(BaseProvider):
1134
1158
 
1135
1159
  # ── Internal — calculations / helpers ────────────────────────────────────────
1136
1160
 
1161
+ def _bounded_probe_reading(self, temp_probe: dict, raw: float | None) -> float | None:
1162
+ """Return the raw reading if within the probe's bounds, else None.
1163
+
1164
+ A reading outside the probe's configured ``MinTemp`` / ``MaxTemp`` range
1165
+ is rejected (logged at debug) and ``None`` is returned, so the probe is
1166
+ treated as unavailable for that read.
1167
+
1168
+ Args:
1169
+ temp_probe: The internal temp-probe component dict.
1170
+ raw: The raw temperature reading, or None if unavailable.
1171
+
1172
+ Returns:
1173
+ The reading when in bounds (or when it cannot be constrained),
1174
+ otherwise None.
1175
+ """
1176
+ if is_temp_in_bounds(raw, temp_probe.get("MinTemp"), temp_probe.get("MaxTemp")):
1177
+ return raw
1178
+ self._log_debug(
1179
+ f"TempProbe {temp_probe['Name']!r}: reading {raw} outside configured bounds "
1180
+ f"(MinTemp={temp_probe.get('MinTemp')}, MaxTemp={temp_probe.get('MaxTemp')}); "
1181
+ f"treating probe as unavailable."
1182
+ )
1183
+ return None
1184
+
1185
+ def _store_probe_reading(self, temp_probe: dict, raw: float | None) -> None:
1186
+ """Apply bounds to a raw reading and store it on the probe.
1187
+
1188
+ When the reading is accepted (in bounds, including a genuine ``None``),
1189
+ ``Temperature`` and ``LastReadingTime`` are updated. When a reading is
1190
+ rejected as out-of-bounds, ``Temperature`` is set to ``None`` and
1191
+ ``LastReadingTime`` is left unchanged, so downstream averagers treat it
1192
+ as an unavailable sample rather than a fresh reading.
1193
+
1194
+ Args:
1195
+ temp_probe: The internal temp-probe component dict.
1196
+ raw: The raw temperature reading, or None if unavailable.
1197
+ """
1198
+ bounded = self._bounded_probe_reading(temp_probe, raw)
1199
+ temp_probe["Temperature"] = bounded
1200
+ if not (raw is not None and bounded is None):
1201
+ temp_probe["LastReadingTime"] = DateHelper.now()
1202
+
1137
1203
  def _calculate_device_energy_totals(self, device: dict) -> None:
1138
1204
  if device["Meters"] > 0:
1139
1205
  total_p = sum(m["Power"] or 0 for m in self._meters if m["DeviceIndex"] == device["Index"])
@@ -1244,8 +1310,8 @@ class ShellyProvider(BaseProvider):
1244
1310
  temp_probe["DeviceIndex"] == device_index
1245
1311
  and temp_probe["ComponentIndex"] == imported_probe.get("ComponentIndex")
1246
1312
  ):
1247
- temp_probe["Temperature"] = imported_probe.get("Temperature", temp_probe.get("Temperature"))
1248
- temp_probe["LastReadingTime"] = DateHelper.now()
1313
+ raw = imported_probe.get("Temperature", temp_probe.get("Temperature"))
1314
+ self._store_probe_reading(temp_probe, raw)
1249
1315
 
1250
1316
  def _export_device_information_to_json(self, device: dict) -> bool:
1251
1317
  if not device.get("Simulate"):
@@ -17,6 +17,7 @@ from sc_foundation import SCCommon, SCLogger
17
17
  from sc_smart_device.models.capabilities import DeviceCapability
18
18
  from sc_smart_device.models.smart_device_status import SmartDeviceStatus
19
19
  from sc_smart_device.providers.base_provider import BaseProvider
20
+ from sc_smart_device.providers.temp_bounds import is_temp_in_bounds, temp_bounds_error
20
21
 
21
22
  if TYPE_CHECKING:
22
23
  from pathlib import Path
@@ -401,6 +402,11 @@ class TasmotaProvider(BaseProvider):
401
402
  elif component_type == "temp_probe":
402
403
  new_comp["Temperature"] = None
403
404
  new_comp["LastReadingTime"] = None
405
+ new_comp["MinTemp"] = cfg.get("MinTemp")
406
+ new_comp["MaxTemp"] = cfg.get("MaxTemp")
407
+ bounds_error = temp_bounds_error(new_comp["MinTemp"], new_comp["MaxTemp"], new_comp["Name"])
408
+ if bounds_error:
409
+ self._raise_runtime_error(bounds_error)
404
410
 
405
411
  for existing in storage:
406
412
  if existing["Name"] == new_comp["Name"]:
@@ -476,7 +482,7 @@ class TasmotaProvider(BaseProvider):
476
482
  continue
477
483
  for sensor_data in status_sns.values():
478
484
  if isinstance(sensor_data, dict) and "Temperature" in sensor_data:
479
- tp["Temperature"] = sensor_data["Temperature"]
485
+ tp["Temperature"] = self._bounded_probe_reading(tp, sensor_data["Temperature"])
480
486
  break
481
487
 
482
488
  self._calculate_device_energy_totals(device)
@@ -636,7 +642,7 @@ class TasmotaProvider(BaseProvider):
636
642
  tp["DeviceIndex"] == device_index
637
643
  and tp["ComponentIndex"] == imported_tp.get("ComponentIndex")
638
644
  ):
639
- tp["Temperature"] = imported_tp.get("Temperature")
645
+ tp["Temperature"] = self._bounded_probe_reading(tp, imported_tp.get("Temperature"))
640
646
  self._calculate_device_energy_totals(device)
641
647
  except (OSError, json.JSONDecodeError, KeyError) as e:
642
648
  msg = f"Error importing Tasmota simulation file for {device['Label']}: {e}"
@@ -724,6 +730,30 @@ class TasmotaProvider(BaseProvider):
724
730
 
725
731
  # ── Helpers ───────────────────────────────────────────────────────────────────
726
732
 
733
+ def _bounded_probe_reading(self, temp_probe: dict, raw: float | None) -> float | None:
734
+ """Return the raw reading if within the probe's bounds, else None.
735
+
736
+ A reading outside the probe's configured ``MinTemp`` / ``MaxTemp`` range
737
+ is rejected (logged at debug) and ``None`` is returned, so the probe is
738
+ treated as unavailable for that read.
739
+
740
+ Args:
741
+ temp_probe: The internal temp-probe component dict.
742
+ raw: The raw temperature reading, or None if unavailable.
743
+
744
+ Returns:
745
+ The reading when in bounds (or when it cannot be constrained),
746
+ otherwise None.
747
+ """
748
+ if is_temp_in_bounds(raw, temp_probe.get("MinTemp"), temp_probe.get("MaxTemp")):
749
+ return raw
750
+ self._log_debug(
751
+ f"TempProbe {temp_probe['Name']!r}: reading {raw} outside configured bounds "
752
+ f"(MinTemp={temp_probe.get('MinTemp')}, MaxTemp={temp_probe.get('MaxTemp')}); "
753
+ f"treating probe as unavailable."
754
+ )
755
+ return None
756
+
727
757
  def _log_debug(self, message: str) -> None:
728
758
  if self.allow_debug_logging:
729
759
  self.logger.log_message(message, "debug")
@@ -0,0 +1,66 @@
1
+ """Per-probe temperature boundary helpers shared by all providers.
2
+
3
+ Temperature probes may declare optional ``MinTemp`` / ``MaxTemp`` boundaries in
4
+ config. A raw reading that falls strictly outside the configured range is
5
+ treated as invalid and discarded (the probe's temperature becomes ``None``),
6
+ filtering physically-impossible values at source — for example a DS18B20
7
+ power-on default of 85°C or a disconnected reading of -127°C — before they reach
8
+ downstream consumers that switch physical outputs.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+
14
+ def temp_bounds_error(
15
+ min_temp: float | None,
16
+ max_temp: float | None,
17
+ probe_name: str | None,
18
+ ) -> str | None:
19
+ """Validate a probe's ``MinTemp`` / ``MaxTemp`` configuration.
20
+
21
+ Both boundaries are optional and independent. Only when both are set is the
22
+ cross-field constraint checked: ``MinTemp`` must be strictly less than
23
+ ``MaxTemp``.
24
+
25
+ Args:
26
+ min_temp: Configured lower boundary, or ``None`` if unset.
27
+ max_temp: Configured upper boundary, or ``None`` if unset.
28
+ probe_name: Probe name, used in the returned error message.
29
+
30
+ Returns:
31
+ An error message describing the invalid configuration, or ``None`` if
32
+ the configuration is valid.
33
+ """
34
+ if min_temp is not None and max_temp is not None and min_temp >= max_temp:
35
+ return (
36
+ f"TempProbe {probe_name!r}: MinTemp ({min_temp}) must be less than "
37
+ f"MaxTemp ({max_temp})."
38
+ )
39
+ return None
40
+
41
+
42
+ def is_temp_in_bounds(
43
+ raw: float | None,
44
+ min_temp: float | None,
45
+ max_temp: float | None,
46
+ ) -> bool:
47
+ """Return whether a raw reading lies within the configured boundaries.
48
+
49
+ A reading strictly greater than ``max_temp`` or strictly less than
50
+ ``min_temp`` is out of bounds. A ``None`` reading, or an unset boundary,
51
+ imposes no constraint.
52
+
53
+ Args:
54
+ raw: The raw temperature reading, or ``None`` if unavailable.
55
+ min_temp: Configured lower boundary, or ``None`` if unset.
56
+ max_temp: Configured upper boundary, or ``None`` if unset.
57
+
58
+ Returns:
59
+ ``True`` if the reading is within bounds (or cannot be constrained),
60
+ ``False`` if it is strictly outside a configured boundary.
61
+ """
62
+ if raw is None:
63
+ return True
64
+ if max_temp is not None and raw > max_temp:
65
+ return False
66
+ return not (min_temp is not None and raw < min_temp)
@@ -142,6 +142,8 @@ smart_devices_validator: dict = {
142
142
  "schema": {
143
143
  **_component_id_name,
144
144
  "RequiresOutput": {"type": "string", "required": False, "nullable": True},
145
+ "MinTemp": {"type": "number", "required": False, "nullable": True},
146
+ "MaxTemp": {"type": "number", "required": False, "nullable": True},
145
147
  },
146
148
  },
147
149
  },
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sc-smart-device
3
- Version: 3.3.2
3
+ Version: 3.3.3
4
4
  Summary: Provides a simple, consistent access to Shelly and Tasmota smart switches and energy meters.
5
5
  Project-URL: Homepage, https://github.com/Spello-Consulting
6
6
  Project-URL: Repository, https://github.com/Spello-Consulting/sc-smart-device
@@ -19,6 +19,7 @@ src/sc_smart_device/providers/__init__.py
19
19
  src/sc_smart_device/providers/base_provider.py
20
20
  src/sc_smart_device/providers/shelly_provider.py
21
21
  src/sc_smart_device/providers/tasmota_provider.py
22
+ src/sc_smart_device/providers/temp_bounds.py
22
23
  src/sc_smart_device/validation/__init__.py
23
24
  src/sc_smart_device/validation/smart_devices_validator.py
24
25
  src/sc_smart_device/webhooks/__init__.py
@@ -27,5 +28,6 @@ tests/test_basic.py
27
28
  tests/test_get_x_value.py
28
29
  tests/test_smart_device_view.py
29
30
  tests/test_tasmota.py
31
+ tests/test_temp_bounds.py
30
32
  tests/test_webhooks.py
31
33
  tests/test_worker.py
@@ -0,0 +1,177 @@
1
+ """Tests for per-probe MinTemp/MaxTemp boundary filtering (issue #7).
2
+
3
+ Covers the pure boundary helpers, the provider-level filtering behaviour on
4
+ both the Shelly and Tasmota providers (including LastReadingTime handling for
5
+ rejected readings), and the ``MinTemp < MaxTemp`` config validation error.
6
+ """
7
+ # ruff: noqa: SLF001 # tests intentionally exercise provider-internal helpers
8
+
9
+ import pytest
10
+ from sc_fixtures import logger
11
+
12
+ from sc_smart_device.providers.shelly_provider import ShellyProvider
13
+ from sc_smart_device.providers.tasmota_provider import TasmotaProvider
14
+ from sc_smart_device.providers.temp_bounds import is_temp_in_bounds, temp_bounds_error
15
+
16
+ # ── Pure boundary check: is_temp_in_bounds ────────────────────────────────────
17
+
18
+
19
+ @pytest.mark.parametrize(
20
+ ("raw", "min_temp", "max_temp", "expected"),
21
+ [
22
+ # Above max → rejected
23
+ (90.0, 0.0, 70.0, False),
24
+ # Below min → rejected
25
+ (-10.0, 0.0, 70.0, False),
26
+ # Within range → accepted
27
+ (25.0, 0.0, 70.0, True),
28
+ # Only max set — above, at, and below the boundary
29
+ (90.0, None, 70.0, False),
30
+ (70.0, None, 70.0, True), # equal to max is in bounds (strict >)
31
+ (25.0, None, 70.0, True),
32
+ # Only min set — below, at, and above the boundary
33
+ (-5.0, 0.0, None, False),
34
+ (0.0, 0.0, None, True), # equal to min is in bounds (strict <)
35
+ (25.0, 0.0, None, True),
36
+ # Neither set → always accepted
37
+ (1000.0, None, None, True),
38
+ (-1000.0, None, None, True),
39
+ # None reading is never constrained
40
+ (None, 0.0, 70.0, True),
41
+ (None, None, None, True),
42
+ ],
43
+ )
44
+ def test_is_temp_in_bounds(raw, min_temp, max_temp, expected):
45
+ """is_temp_in_bounds applies strict, independent, optional boundaries."""
46
+ assert is_temp_in_bounds(raw, min_temp, max_temp) is expected
47
+
48
+
49
+ # ── Config validation: temp_bounds_error ──────────────────────────────────────
50
+
51
+
52
+ @pytest.mark.parametrize(
53
+ ("min_temp", "max_temp"),
54
+ [
55
+ (None, None), # neither set
56
+ (0.0, None), # only min
57
+ (None, 70.0), # only max
58
+ (0.0, 70.0), # min < max
59
+ (-20.0, 0.0), # min < max (negatives)
60
+ ],
61
+ )
62
+ def test_temp_bounds_error_valid(min_temp, max_temp):
63
+ """Valid or absent boundaries produce no error."""
64
+ assert temp_bounds_error(min_temp, max_temp, "Roof") is None
65
+
66
+
67
+ @pytest.mark.parametrize(
68
+ ("min_temp", "max_temp"),
69
+ [
70
+ (70.0, 10.0), # min > max
71
+ (70.0, 70.0), # min == max (must be strictly less)
72
+ ],
73
+ )
74
+ def test_temp_bounds_error_invalid(min_temp, max_temp):
75
+ """MinTemp must be strictly less than MaxTemp when both are set."""
76
+ message = temp_bounds_error(min_temp, max_temp, "Roof")
77
+ assert message is not None
78
+ assert "Roof" in message
79
+ assert "must be less than" in message
80
+
81
+
82
+ # ── Provider helpers ──────────────────────────────────────────────────────────
83
+
84
+
85
+ def _make_probe(min_temp=None, max_temp=None, last_reading=None):
86
+ return {
87
+ "Name": "Roof",
88
+ "MinTemp": min_temp,
89
+ "MaxTemp": max_temp,
90
+ "Temperature": None,
91
+ "LastReadingTime": last_reading,
92
+ }
93
+
94
+
95
+ def test_shelly_store_reading_within_bounds():
96
+ """An in-range reading sets Temperature and refreshes LastReadingTime."""
97
+ provider = ShellyProvider(logger)
98
+ probe = _make_probe(min_temp=0.0, max_temp=70.0)
99
+ provider._store_probe_reading(probe, 25.0)
100
+ assert probe["Temperature"] == 25.0
101
+ assert probe["LastReadingTime"] is not None
102
+
103
+
104
+ def test_shelly_store_reading_above_max_rejected():
105
+ """An above-max reading yields None and leaves LastReadingTime untouched."""
106
+ provider = ShellyProvider(logger)
107
+ probe = _make_probe(min_temp=0.0, max_temp=70.0, last_reading="PRIOR")
108
+ provider._store_probe_reading(probe, 90.0)
109
+ assert probe["Temperature"] is None
110
+ assert probe["LastReadingTime"] == "PRIOR"
111
+
112
+
113
+ def test_shelly_store_reading_below_min_rejected():
114
+ """A below-min reading yields None and leaves LastReadingTime untouched."""
115
+ provider = ShellyProvider(logger)
116
+ probe = _make_probe(min_temp=0.0, max_temp=70.0, last_reading="PRIOR")
117
+ provider._store_probe_reading(probe, -127.0)
118
+ assert probe["Temperature"] is None
119
+ assert probe["LastReadingTime"] == "PRIOR"
120
+
121
+
122
+ def test_shelly_store_reading_none_is_fresh_sample():
123
+ """A genuine None reading (unavailable probe) still refreshes LastReadingTime."""
124
+ provider = ShellyProvider(logger)
125
+ probe = _make_probe(min_temp=0.0, max_temp=70.0)
126
+ provider._store_probe_reading(probe, None)
127
+ assert probe["Temperature"] is None
128
+ assert probe["LastReadingTime"] is not None
129
+
130
+
131
+ def test_shelly_store_reading_no_bounds():
132
+ """With no bounds configured, any reading is accepted."""
133
+ provider = ShellyProvider(logger)
134
+ probe = _make_probe()
135
+ provider._store_probe_reading(probe, 123.0)
136
+ assert probe["Temperature"] == 123.0
137
+ assert probe["LastReadingTime"] is not None
138
+
139
+
140
+ def test_tasmota_bounded_reading():
141
+ """Tasmota filters out-of-range readings and passes in-range ones through."""
142
+ provider = TasmotaProvider(logger)
143
+ probe = _make_probe(min_temp=0.0, max_temp=70.0)
144
+ assert provider._bounded_probe_reading(probe, 25.0) == 25.0
145
+ assert provider._bounded_probe_reading(probe, 85.0) is None
146
+ assert provider._bounded_probe_reading(probe, -127.0) is None
147
+
148
+
149
+ # ── Provider config validation ────────────────────────────────────────────────
150
+
151
+
152
+ def _bad_bounds_settings(model):
153
+ return {
154
+ "PingAllowed": False,
155
+ "Devices": [
156
+ {
157
+ "Name": "Bounds Device",
158
+ "Model": model,
159
+ "Hostname": "192.168.1.99",
160
+ "TempProbes": [{"Name": "Roof", "MinTemp": 70.0, "MaxTemp": 10.0}],
161
+ }
162
+ ],
163
+ }
164
+
165
+
166
+ def test_shelly_rejects_invalid_bounds():
167
+ """Loading a Shelly probe with MinTemp >= MaxTemp raises RuntimeError."""
168
+ provider = ShellyProvider(logger)
169
+ with pytest.raises(RuntimeError, match="must be less than"):
170
+ provider._add_devices_from_config(_bad_bounds_settings("Shelly2PMG3"))
171
+
172
+
173
+ def test_tasmota_rejects_invalid_bounds():
174
+ """Loading a Tasmota probe with MinTemp >= MaxTemp raises RuntimeError."""
175
+ provider = TasmotaProvider(logger)
176
+ with pytest.raises(RuntimeError, match="must be less than"):
177
+ provider._add_devices_from_config(_bad_bounds_settings("Tasmota"))