python-izone 2.0.1__tar.gz → 2.1.1__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 (68) hide show
  1. {python_izone-2.0.1 → python_izone-2.1.1}/PKG-INFO +1 -1
  2. python_izone-2.1.1/docs/release-notes/v2.1.0.md +11 -0
  3. python_izone-2.1.1/docs/release-notes/v2.1.1.md +13 -0
  4. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/__init__.py +2 -0
  5. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/controller.py +190 -46
  6. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/exceptions.py +35 -0
  7. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/v2.py +10 -11
  8. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/version.py +2 -2
  9. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/zone.py +26 -15
  10. {python_izone-2.0.1 → python_izone-2.1.1}/tests/conftest.py +3 -0
  11. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_controller.py +30 -0
  12. python_izone-2.1.1/tests/test_reconfiguration.py +259 -0
  13. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_zone.py +97 -0
  14. {python_izone-2.0.1 → python_izone-2.1.1}/.gitattributes +0 -0
  15. {python_izone-2.0.1 → python_izone-2.1.1}/.github/workflows/main.yml +0 -0
  16. {python_izone-2.0.1 → python_izone-2.1.1}/.gitignore +0 -0
  17. {python_izone-2.0.1 → python_izone-2.1.1}/.pre-commit-config.yaml +0 -0
  18. {python_izone-2.0.1 → python_izone-2.1.1}/.python-version +0 -0
  19. {python_izone-2.0.1 → python_izone-2.1.1}/.vscode/.ropeproject/config.py +0 -0
  20. {python_izone-2.0.1 → python_izone-2.1.1}/.vscode/extensions.json +0 -0
  21. {python_izone-2.0.1 → python_izone-2.1.1}/.vscode/launch.json +0 -0
  22. {python_izone-2.0.1 → python_izone-2.1.1}/.vscode/settings.json +0 -0
  23. {python_izone-2.0.1 → python_izone-2.1.1}/README.md +0 -0
  24. {python_izone-2.0.1 → python_izone-2.1.1}/api_docs/AC-DOC-1401-11_iZoneEthernetInterface.pdf +0 -0
  25. {python_izone-2.0.1 → python_izone-2.1.1}/api_docs/iPower_JSON_datastrings_Out.h +0 -0
  26. {python_izone-2.0.1 → python_izone-2.1.1}/api_docs/iZone_JSON_datastrings.h +0 -0
  27. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.10.md +0 -0
  28. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.11.md +0 -0
  29. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.12.md +0 -0
  30. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.4.md +0 -0
  31. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.5.md +0 -0
  32. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.6.md +0 -0
  33. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.7.md +0 -0
  34. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.8.md +0 -0
  35. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v1.3.9.md +0 -0
  36. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v2.0.0.md +0 -0
  37. {python_izone-2.0.1 → python_izone-2.1.1}/docs/release-notes/v2.0.1.md +0 -0
  38. {python_izone-2.0.1 → python_izone-2.1.1}/docs/v2-confirmation.md +0 -0
  39. {python_izone-2.0.1 → python_izone-2.1.1}/licence.txt +0 -0
  40. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/const.py +0 -0
  41. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/discovery.py +0 -0
  42. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/power.py +0 -0
  43. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/py.typed +0 -0
  44. {python_izone-2.0.1 → python_izone-2.1.1}/pizone/types.py +0 -0
  45. {python_izone-2.0.1 → python_izone-2.1.1}/pyproject.toml +0 -0
  46. {python_izone-2.0.1 → python_izone-2.1.1}/scripts/check +0 -0
  47. {python_izone-2.0.1 → python_izone-2.1.1}/scripts/coverage +0 -0
  48. {python_izone-2.0.1 → python_izone-2.1.1}/scripts/izone_v1_probe.py +0 -0
  49. {python_izone-2.0.1 → python_izone-2.1.1}/tests/__init__.py +0 -0
  50. {python_izone-2.0.1 → python_izone-2.1.1}/tests/http_fakes.py +0 -0
  51. {python_izone-2.0.1 → python_izone-2.1.1}/tests/power_data.py +0 -0
  52. {python_izone-2.0.1 → python_izone-2.1.1}/tests/resources.py +0 -0
  53. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_control_zone.py +0 -0
  54. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_discovery.py +0 -0
  55. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_discovery_api.py +0 -0
  56. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_discovery_close_timeout.py +0 -0
  57. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_dump_state.py +0 -0
  58. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_hardware_controller.py +0 -0
  59. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_hardware_hosts.py +0 -0
  60. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_http.py +0 -0
  61. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_power.py +0 -0
  62. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_v2.py +0 -0
  63. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_v2_confirmation.py +0 -0
  64. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_v2_fan_capability.py +0 -0
  65. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_v2_vendor_enums.py +0 -0
  66. {python_izone-2.0.1 → python_izone-2.1.1}/tests/test_v2_zone_validation.py +0 -0
  67. {python_izone-2.0.1 → python_izone-2.1.1}/tests/v2_fixtures.py +0 -0
  68. {python_izone-2.0.1 → python_izone-2.1.1}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-izone
3
- Version: 2.0.1
3
+ Version: 2.1.1
4
4
  Summary: A python interface to the iZone airconditioner controller
5
5
  Project-URL: Homepage, https://github.com/Swamp-Ig/pizone
6
6
  Author-email: Penny Wood <pypl@ninjateaparty.com>
@@ -0,0 +1,11 @@
1
+ # Release notes — v2.1.0
2
+
3
+ **Compare range:** https://github.com/Swamp-Ig/pizone/compare/v2.0.1...v2.1.0
4
+
5
+ ## Since v2.0.1
6
+
7
+ ### Reprogrammed systems are detected
8
+
9
+ - If an installer reprograms the system (zone count, zone types or fan setup), refreshes and commands now raise the new `DeviceReconfigurationError` instead of carrying on with the old layout. Its `changes` attribute lists what changed.
10
+ - To recover, close the controller and create a new one with `DiscoveryService.create_controller()`.
11
+ - `DeviceReconfigurationError` is not a `ConnectionError`, so existing outage handling won't catch it. Callers should catch it and recreate the controller.
@@ -0,0 +1,13 @@
1
+ # Release notes — v2.1.1
2
+
3
+ **Compare range:** https://github.com/Swamp-Ig/pizone/compare/v2.1.0...v2.1.1
4
+
5
+ ## Since v2.1.0
6
+
7
+ ### V2 commands retry while the bridge is busy
8
+
9
+ - Some V2-only bridges reject commands with `{ERROR}` for a few seconds, seemingly while applying an earlier write ([home-assistant/core#194474](https://github.com/home-assistant/core/issues/194474)). V2 commands now retry every 0.5 s for up to 8 s, instead of once after 0.15 s.
10
+ - The sending lock is released between tries, so polls and other commands keep running while one command waits.
11
+ - A newer write to the same field (for example a zone's maximum airflow) replaces a write that is waiting to retry. The replaced call returns without sending again, and doesn't update the cache or run its later steps, so the newest value wins.
12
+ - A command the bridge keeps rejecting now takes up to 8 s to raise `ControllerCommandError`. The first FreeAir command on a bridge without V2 iSave support also waits out the window before falling back to V1.
13
+ - V1 commands are unchanged. No API changes.
@@ -35,6 +35,7 @@ from .discovery import DiscoveryService, create_discovery
35
35
  from .exceptions import (
36
36
  ControllerAlreadyClaimedError,
37
37
  ControllerCommandError,
38
+ DeviceReconfigurationError,
38
39
  EndpointVerifyError,
39
40
  InvalidValueError,
40
41
  ResponseDecodeError,
@@ -77,6 +78,7 @@ __all__ = [
77
78
  "ControllerAlreadyClaimedError",
78
79
  "ControllerCommandError",
79
80
  "ControllerEndpoint",
81
+ "DeviceReconfigurationError",
80
82
  "DiscoveredEndpoints",
81
83
  "DiscoveryService",
82
84
  "EndpointVerifyError",
@@ -15,7 +15,12 @@ from typing import TYPE_CHECKING, Any, Literal, Self, cast
15
15
  import aiohttp
16
16
 
17
17
  from . import power as power_mod, v2 as v2_mod
18
- from .exceptions import ControllerCommandError, InvalidValueError, ResponseDecodeError
18
+ from .exceptions import (
19
+ ControllerCommandError,
20
+ DeviceReconfigurationError,
21
+ InvalidValueError,
22
+ ResponseDecodeError,
23
+ )
19
24
  from .power import Power
20
25
  from .types import ControllerEndpoint, ControllerProbe
21
26
  from .zone import Zone
@@ -43,8 +48,17 @@ def _refresh_api(
43
48
 
44
49
  @wraps(method)
45
50
  async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
46
- async with self._refresh_scope():
47
- return await method(self, *args, **kwargs)
51
+ self._raise_if_reconfigured()
52
+ try:
53
+ async with self._refresh_scope():
54
+ result = await method(self, *args, **kwargs)
55
+ except Exception as ex:
56
+ # A read in this refresh saw the reconfigure; that outranks its errors.
57
+ if self._reconfigured is not None:
58
+ raise DeviceReconfigurationError(dict(self._reconfigured)) from ex
59
+ raise
60
+ self._raise_if_reconfigured()
61
+ return result
48
62
 
49
63
  return wrapper
50
64
 
@@ -95,6 +109,16 @@ class Controller:
95
109
  REQUEST_TIMEOUT = 10
96
110
  """Time to wait for a response from the device, in seconds."""
97
111
 
112
+ V2_ERROR_RETRY_INTERVAL = 0.5
113
+ """Gap between V2 command retries after ``{ERROR}``, in seconds."""
114
+
115
+ V2_ERROR_RETRY_WINDOW = 8.0
116
+ """How long to keep retrying a V2 command that returns ``{ERROR}``.
117
+
118
+ Some bridges reject commands for a few seconds while applying an earlier
119
+ write.
120
+ """
121
+
98
122
  ZONE_CONFIRM_DELAY = 0.25
99
123
  ZONE_CONFIRM_INTERVAL = 2.0
100
124
  ZONE_CONFIRM_WINDOW = 30.0
@@ -175,9 +199,13 @@ class Controller:
175
199
  self._izone_ok: bool = True
176
200
  self._fault_fields: tuple[str, ...] = ()
177
201
  self._last_fault: dict[str, Any] | None = None
202
+ # System fields the zones and fan modes were built from at connect.
203
+ self._built_from: dict[str, Any] | None = None
204
+ self._reconfigured: dict[str, tuple[Any, Any]] | None = None
178
205
  self._on_address_changed: Callable[[ControllerEndpoint], None] | None = None
179
206
 
180
207
  self._sending_lock = Lock()
208
+ self._v2_write_gens: dict[tuple[str, int | None], int] = {}
181
209
  self._refresh_depth: int = 0
182
210
  self._refresh_fail_ex: ConnectionError | None = None
183
211
  self._zone_mode_confirmations: dict[int, _ZoneModeConfirmation] = {}
@@ -260,19 +288,23 @@ class Controller:
260
288
  if settings is None:
261
289
  raise ConnectionError("SystemSettings device ID mismatch")
262
290
 
263
- if self._system_settings:
264
- fan_auto = str(self._system_settings.get("FanAuto", "disabled"))
265
- self.fan_modes = Controller._VALID_FAN_MODES.get(
266
- fan_auto, Controller._VALID_FAN_MODES["unknown"]
267
- )
268
- else:
269
- self.fan_modes = Controller._VALID_FAN_MODES["disabled"]
291
+ self.fan_modes = Controller._VALID_FAN_MODES.get(
292
+ self._fan_auto(self._system_settings),
293
+ Controller._VALID_FAN_MODES["unknown"],
294
+ )
270
295
 
271
296
  zone_count = int(settings["NoOfZones"])
272
297
  self.zones = [Zone(self, i) for i in range(zone_count)]
273
298
 
274
299
  await self._fetch_zones()
275
300
 
301
+ self._built_from = {
302
+ "NoOfZones": zone_count,
303
+ "NoOfConst": settings.get("NoOfConst"),
304
+ "SysType": settings.get("SysType"),
305
+ "FanAuto": self._fan_auto(self._system_settings),
306
+ }
307
+
276
308
  await self._probe_power()
277
309
 
278
310
  async def _probe_power(self) -> None:
@@ -347,6 +379,7 @@ class Controller:
347
379
  "fan_modes": [fan.value for fan in self.fan_modes],
348
380
  "system_settings": dict(self._system_settings),
349
381
  "last_fault": self._last_fault,
382
+ "reconfigured": self._reconfigured,
350
383
  "zones": [zone.dump_state() for zone in self.zones],
351
384
  "power": self._power.dump_state() if self._power is not None else None,
352
385
  }
@@ -423,8 +456,11 @@ class Controller:
423
456
  raise InvalidValueError("Free air system is not enabled")
424
457
  await self._set_system_state("FreeAir", "FreeAir", "on")
425
458
  else:
426
- if self.free_air:
427
- await self._set_system_state("FreeAir", "FreeAir", "off")
459
+ # A newer FreeAir write replaced ours; let it decide the mode.
460
+ if self.free_air and not await self._set_system_state(
461
+ "FreeAir", "FreeAir", "off"
462
+ ):
463
+ return
428
464
  await self._set_system_state("SysMode", "SystemMODE", value.value)
429
465
 
430
466
  @property
@@ -849,6 +885,7 @@ class Controller:
849
885
  """System + zones [+ power] fetch (no refresh scope)."""
850
886
  if self._read_api == "v2":
851
887
  await self._fetch_system()
888
+ self._raise_if_reconfigured()
852
889
  await self._fetch_zones()
853
890
  await self._fetch_power()
854
891
  return
@@ -895,8 +932,56 @@ class Controller:
895
932
 
896
933
  self._system_settings = values
897
934
  self._set_izone_ok(True)
935
+ if not faults and self._built_from is not None:
936
+ self._check_reconfigured(values)
898
937
  return values
899
938
 
939
+ @staticmethod
940
+ def _fan_auto(values: ControllerData) -> str:
941
+ """Return FanAuto as the fan modes read it; absent means disabled."""
942
+ if not values:
943
+ return "disabled"
944
+ return str(values.get("FanAuto", "disabled"))
945
+
946
+ def _check_reconfigured(self, values: ControllerData) -> None:
947
+ """Latch if a clean read no longer matches what was built at connect."""
948
+ built = cast(dict[str, Any], self._built_from)
949
+ if (
950
+ int(values["NoOfZones"]) == built["NoOfZones"]
951
+ and values.get("NoOfConst") == built["NoOfConst"]
952
+ and values.get("SysType") == built["SysType"]
953
+ and self._fan_auto(values) == built["FanAuto"]
954
+ ):
955
+ return
956
+ current = {
957
+ "NoOfZones": int(values["NoOfZones"]),
958
+ "NoOfConst": values.get("NoOfConst"),
959
+ "SysType": values.get("SysType"),
960
+ "FanAuto": self._fan_auto(values),
961
+ }
962
+ self._note_reconfigured(
963
+ {
964
+ field: (old, current[field])
965
+ for field, old in built.items()
966
+ if current[field] != old
967
+ }
968
+ )
969
+
970
+ def _note_reconfigured(self, changes: dict[str, tuple[Any, Any]]) -> None:
971
+ """Latch the reconfigured state; it only clears with a new controller."""
972
+ if self._reconfigured is None:
973
+ self._reconfigured = {}
974
+ _LOG.warning(
975
+ "iZone system reconfigured uid=%s: %s",
976
+ self._device_uid,
977
+ DeviceReconfigurationError(changes),
978
+ )
979
+ self._reconfigured.update(changes)
980
+
981
+ def _raise_if_reconfigured(self) -> None:
982
+ if self._reconfigured is not None:
983
+ raise DeviceReconfigurationError(dict(self._reconfigured))
984
+
900
985
  def _record_faults(
901
986
  self, values: ControllerData, faults: list[str], *, offline: bool
902
987
  ) -> None:
@@ -972,57 +1057,112 @@ class Controller:
972
1057
  command: str,
973
1058
  value: DictValue,
974
1059
  send: DictValue | None = None,
975
- ) -> None:
1060
+ ) -> bool:
976
1061
  """Send a system command and update the local cache.
977
1062
 
1063
+ Returns False if a newer write to the same field replaced it.
1064
+
978
1065
  Raises:
979
1066
  ConnectionError: If the HTTP request fails.
1067
+ DeviceReconfigurationError: If the system was reconfigured.
980
1068
 
981
1069
  """
1070
+ self._raise_if_reconfigured()
982
1071
  if send is None:
983
1072
  send = value
984
1073
 
985
- async with self._sending_lock, self._refresh_scope():
986
- if self._read_api == "v2":
987
- v2_payload = v2_mod.system_command_to_v2(state, value, send)
988
- if state == "FreeAir" and self._isave_v2_unsupported:
989
- v2_payload = None
990
- if v2_payload is not None:
991
- try:
992
- await self._http_command_v2(v2_payload)
993
- except ControllerCommandError:
994
- if state != "FreeAir":
995
- raise
996
- self._isave_v2_unsupported = True
997
- await self._http_post(command, {command: send})
998
- else:
999
- await self._http_post(command, {command: send})
1000
- self._system_settings[state] = value
1001
- await self._fetch_system_v2_unlocked()
1002
- else:
1074
+ if self._read_api != "v2":
1075
+ async with self._sending_lock, self._refresh_scope():
1003
1076
  await self._http_post(command, {command: send})
1004
1077
  self._system_settings[state] = value
1005
1078
  await self._fetch_system()
1079
+ return True
1080
+
1081
+ async def apply() -> None:
1082
+ self._system_settings[state] = value
1083
+ await self._fetch_system_v2_unlocked()
1084
+
1085
+ v2_payload = v2_mod.system_command_to_v2(state, value, send)
1086
+ if state == "FreeAir" and self._isave_v2_unsupported:
1087
+ v2_payload = None
1088
+ if v2_payload is not None:
1089
+ try:
1090
+ return await self._command_v2_retrying(v2_payload, apply)
1091
+ except ControllerCommandError:
1092
+ if state != "FreeAir":
1093
+ raise
1094
+ self._isave_v2_unsupported = True
1095
+ async with self._sending_lock, self._refresh_scope():
1096
+ await self._http_post(command, {command: send})
1097
+ await apply()
1098
+ return True
1006
1099
 
1007
1100
  async def _execute_zone_command(
1008
1101
  self, command: str, data: dict[str, Any], zone_index: int
1009
- ) -> None:
1010
- """POST a zone command and confirm with a zone refresh."""
1011
- async with self._sending_lock, self._refresh_scope():
1012
- if self._read_api == "v2":
1102
+ ) -> bool:
1103
+ """POST a zone command and confirm with a zone refresh.
1104
+
1105
+ Returns False if a newer write to the same field replaced it.
1106
+ """
1107
+ self._raise_if_reconfigured()
1108
+ if self._read_api != "v2":
1109
+ group = (zone_index // 4) * 4
1110
+ async with self._sending_lock, self._refresh_scope():
1111
+ await self._http_post(command, data)
1112
+ await self._fetch_zone_group(group)
1113
+ return True
1114
+
1115
+ payload = v2_mod.zone_command_to_v2(command, data, zone_index)
1116
+
1117
+ async def apply() -> None:
1118
+ if "ZoneMode" in payload:
1119
+ mode = v2_mod.zone_mode_from_wire(payload["ZoneMode"]["Mode"])
1120
+ self._track_zone_mode(zone_index, mode.value)
1121
+ else:
1122
+ await self._fetch_zone_v2_unlocked(zone_index)
1123
+
1124
+ return await self._command_v2_retrying(payload, apply)
1125
+
1126
+ async def _command_v2_retrying(
1127
+ self, payload: dict[str, Any], apply: Callable[[], Awaitable[None]]
1128
+ ) -> bool:
1129
+ """Send *payload* and run *apply*, retrying ``{ERROR}`` without the lock.
1130
+
1131
+ A newer write to the same field replaces one waiting to retry; the
1132
+ replaced call skips *apply* and returns False.
1133
+
1134
+ Raises:
1135
+ ConnectionError: If the HTTP request fails or the controller is closed.
1136
+ ControllerCommandError: If the bridge still rejects the command once
1137
+ ``V2_ERROR_RETRY_WINDOW`` has passed.
1138
+ DeviceReconfigurationError: If the system was reconfigured.
1139
+
1140
+ """
1141
+ key = v2_mod.command_key(payload)
1142
+ gen: int | None = None
1143
+ loop = asyncio.get_running_loop()
1144
+ deadline = loop.time() + self.V2_ERROR_RETRY_WINDOW
1145
+ while True:
1146
+ async with self._sending_lock, self._refresh_scope():
1147
+ if gen is None:
1148
+ gen = self._v2_write_gens.get(key, 0) + 1
1149
+ self._v2_write_gens[key] = gen
1150
+ elif self._v2_write_gens[key] != gen:
1151
+ _LOG.debug("Dropping %s, replaced by a newer write", payload)
1152
+ return False
1153
+ self._raise_if_reconfigured()
1013
1154
  if self._closed:
1014
1155
  raise ConnectionError("Controller is closed")
1015
- payload = v2_mod.zone_command_to_v2(command, data, zone_index)
1016
- await self._http_command_v2(payload)
1017
- if "ZoneMode" in payload:
1018
- mode = v2_mod.zone_mode_from_wire(payload["ZoneMode"]["Mode"])
1019
- self._track_zone_mode(zone_index, mode.value)
1156
+ try:
1157
+ await self._http_command_v2(payload)
1158
+ except ControllerCommandError:
1159
+ if loop.time() >= deadline:
1160
+ raise
1161
+ _LOG.debug("Bridge rejected %s, retrying", payload)
1020
1162
  else:
1021
- await self._fetch_zone_v2_unlocked(zone_index)
1022
- else:
1023
- group = (zone_index // 4) * 4
1024
- await self._http_post(command, data)
1025
- await self._fetch_zone_group(group)
1163
+ await apply()
1164
+ return True
1165
+ await asyncio.sleep(self.V2_ERROR_RETRY_INTERVAL)
1026
1166
 
1027
1167
  async def _fetch_zone_v2_unlocked(self, index: int) -> None:
1028
1168
  """Refresh one zone via Type=2. Caller must hold ``_sending_lock``."""
@@ -1082,7 +1222,11 @@ class Controller:
1082
1222
  """Bounded, read-only confirmation; never resend a zone command."""
1083
1223
  loop = asyncio.get_running_loop()
1084
1224
  try:
1085
- while self._zone_mode_confirmations and not self._closed:
1225
+ while (
1226
+ self._zone_mode_confirmations
1227
+ and not self._closed
1228
+ and self._reconfigured is None
1229
+ ):
1086
1230
  self._expire_zone_modes(loop.time())
1087
1231
  if not self._zone_mode_confirmations:
1088
1232
  break
@@ -1,5 +1,7 @@
1
1
  """pizone-specific exceptions."""
2
2
 
3
+ from typing import Any
4
+
3
5
  from .const import PLACEHOLDER_DEVICE_UID
4
6
  from .types import VerifyFailure, _failure_text
5
7
 
@@ -13,6 +15,39 @@ class ControllerCommandError(Exception):
13
15
  """
14
16
 
15
17
 
18
+ class DeviceReconfigurationError(Exception):
19
+ """The system no longer matches the controller built at connect.
20
+
21
+ Raised once a clean read shows that an installer has reprogrammed the
22
+ system, for example the number of zones or a zone type changed. The
23
+ controller stays this way: every refresh and command raises this until it
24
+ is closed and a new one is created with
25
+ :meth:`~pizone.discovery.DiscoveryService.create_controller`.
26
+
27
+ Not a :exc:`ConnectionError`: the device is reachable and answering.
28
+
29
+ Attributes:
30
+ changes: Each changed field, mapped to its value at connect and its
31
+ new value. Zone types use keys like ``"Zone 3 Type"``.
32
+
33
+ """
34
+
35
+ def __init__(self, changes: dict[str, tuple[Any, Any]]) -> None:
36
+ """Create the error for *changes*."""
37
+ super().__init__()
38
+ self.changes = changes
39
+
40
+ def __str__(self) -> str:
41
+ """Plain-English description, for logs and tracebacks."""
42
+ detail = ", ".join(
43
+ f"{field} {old!r} -> {new!r}" for field, (old, new) in self.changes.items()
44
+ )
45
+ return (
46
+ f"iZone system was reconfigured ({detail}); close this controller "
47
+ "and create a new one"
48
+ )
49
+
50
+
16
51
  class InvalidValueError(ValueError, AttributeError):
17
52
  """A setter rejected a value before sending anything to the device.
18
53
 
@@ -449,6 +449,12 @@ def system_command_to_v2(state: str, value: Any, send: Any) -> dict[str, Any] |
449
449
  return None
450
450
 
451
451
 
452
+ def command_key(payload: dict[str, Any]) -> tuple[str, int | None]:
453
+ """Return the field an iZoneCommandV2 payload writes: (command, zone index)."""
454
+ ((name, body),) = payload.items()
455
+ return name, body.get("Index") if isinstance(body, dict) else None
456
+
457
+
452
458
  def zone_command_to_v2(
453
459
  command: str, data: dict[str, Any], zone_index: int
454
460
  ) -> dict[str, Any]:
@@ -560,7 +566,10 @@ async def command_v2(
560
566
  use_content_type: bool | None,
561
567
  timeout: float = 10.0,
562
568
  ) -> tuple[str, bool | None]:
563
- """POST iZoneCommandV2; return (raw body text, content-type mode used)."""
569
+ """POST iZoneCommandV2; return (raw body text, content-type mode used).
570
+
571
+ Sends once; the controller retries ``{ERROR}`` with its lock released.
572
+ """
564
573
  if use_content_type is not None:
565
574
  body = await _post_once(
566
575
  session,
@@ -570,16 +579,6 @@ async def command_v2(
570
579
  use_content_type=use_content_type,
571
580
  timeout=timeout,
572
581
  )
573
- if body.strip().startswith("{ERROR"):
574
- await asyncio.sleep(V2_ERROR_BACKOFF)
575
- body = await _post_once(
576
- session,
577
- host,
578
- path="iZoneCommandV2",
579
- payload=payload,
580
- use_content_type=use_content_type,
581
- timeout=timeout,
582
- )
583
582
  return body, use_content_type
584
583
 
585
584
  for mode in (False, True):
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '2.0.1'
22
- __version_tuple__ = version_tuple = (2, 0, 1)
21
+ __version__ = version = '2.1.1'
22
+ __version_tuple__ = version_tuple = (2, 1, 1)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -90,6 +90,8 @@ class Zone:
90
90
  self._zone_data: Zone.ZoneData = {}
91
91
  self._index = index
92
92
  self._controller = controller
93
+ # Zone type at connect; None until the first clean read sets it.
94
+ self._built_type: Zone.DictValue | None = None
93
95
 
94
96
  @property
95
97
  def index(self) -> int:
@@ -203,8 +205,8 @@ class Zone:
203
205
  if value < 0 or value > 100:
204
206
  raise InvalidValueError(f"MinAir '{value}' is out of range")
205
207
 
206
- await self._send_command("AirMinCommand", value)
207
- self._zone_data["MinAir"] = value
208
+ if await self._send_command("AirMinCommand", value):
209
+ self._zone_data["MinAir"] = value
208
210
 
209
211
  async def set_airflow_max(self, value: int) -> None:
210
212
  """Change the zone maximum airflow in 5% increments.
@@ -219,8 +221,8 @@ class Zone:
219
221
  if value < 0 or value > 100:
220
222
  raise InvalidValueError(f"MaxAir '{value}' is out of range")
221
223
 
222
- await self._send_command("AirMaxCommand", value)
223
- self._zone_data["MaxAir"] = value
224
+ if await self._send_command("AirMaxCommand", value):
225
+ self._zone_data["MaxAir"] = value
224
226
 
225
227
  async def set_temp_setpoint(self, value: float) -> None:
226
228
  """Change the zone temperature setpoint in degrees C.
@@ -241,9 +243,9 @@ class Zone:
241
243
  if value < self._controller.temp_min or value > self._controller.temp_max:
242
244
  raise InvalidValueError(f"SetPoint '{value}' is out of range")
243
245
 
244
- await self._send_command("ZoneCommand", value)
245
- self._zone_data["Mode"] = "auto"
246
- self._zone_data["SetPoint"] = value
246
+ if await self._send_command("ZoneCommand", value):
247
+ self._zone_data["Mode"] = "auto"
248
+ self._zone_data["SetPoint"] = value
247
249
 
248
250
  async def set_mode(self, value: Zone.Mode) -> None:
249
251
  """Set the current zone mode.
@@ -259,14 +261,14 @@ class Zone:
259
261
  # V2 can select AUTO without overwriting a newer wall-panel setpoint.
260
262
  # V1 still needs the cached setpoint to select temperature control.
261
263
  if self._controller._read_api == "v2": # noqa: SLF001
262
- await self._send_command("ZoneCommand", value.value)
264
+ sent = await self._send_command("ZoneCommand", value.value)
263
265
  else:
264
- await self._send_command(
266
+ sent = await self._send_command(
265
267
  "ZoneCommand", self._get_zone_state("SetPoint")
266
268
  )
267
- self._zone_data["Mode"] = "auto"
268
- else:
269
- await self._send_command("ZoneCommand", value.value)
269
+ if sent:
270
+ self._zone_data["Mode"] = "auto"
271
+ elif await self._send_command("ZoneCommand", value.value):
270
272
  self._zone_data["Mode"] = value.value
271
273
 
272
274
  def _update_zone(self, zone_data: Zone.ZoneData) -> None:
@@ -278,9 +280,16 @@ class Zone:
278
280
  """
279
281
  if zone_data["Index"] != self._index:
280
282
  raise AttributeError("Can't change index of existing zone.")
281
- if str(zone_data.get("Type")) == "error":
283
+ zone_type = zone_data.get("Type")
284
+ if str(zone_type) == "error":
282
285
  return
283
286
  self._zone_data = zone_data
287
+ if self._built_type is None:
288
+ self._built_type = zone_type
289
+ elif zone_type != self._built_type:
290
+ self._controller._note_reconfigured( # noqa: SLF001
291
+ {f"Zone {self._index + 1} Type": (self._built_type, zone_type)}
292
+ )
284
293
 
285
294
  def _get_zone_state(self, state: str) -> DictValue:
286
295
  return self._zone_data[state]
@@ -307,14 +316,16 @@ class Zone:
307
316
  except KeyError, ValueError:
308
317
  return None
309
318
 
310
- async def _send_command(self, command: str, data: str | float) -> None:
319
+ async def _send_command(self, command: str, data: str | float) -> bool:
311
320
  """Send a zone command via the parent controller.
312
321
 
322
+ Returns False if a newer write to the same field replaced it.
323
+
313
324
  Raises:
314
325
  ConnectionError: If the device cannot be reached or the response is invalid.
315
326
 
316
327
  """
317
328
  send_data = {command: {"ZoneNo": str(self._index + 1), "Command": str(data)}}
318
- await self._controller._execute_zone_command( # noqa: SLF001
329
+ return await self._controller._execute_zone_command( # noqa: SLF001
319
330
  command, send_data, self._index
320
331
  )
@@ -41,6 +41,9 @@ _V1_SYSTEM_COMMAND_FIELDS = {
41
41
  class MockController(Controller):
42
42
  """Controller double backed by static response dictionaries."""
43
43
 
44
+ # Fail on the first {ERROR}; retry behaviour has its own tests.
45
+ V2_ERROR_RETRY_WINDOW = 0.0
46
+
44
47
  def __init__(
45
48
  self,
46
49
  discovery_service: DiscoveryService,
@@ -1004,6 +1004,36 @@ async def test_v2_free_air_falls_back_and_stays_on_v1() -> None:
1004
1004
  await svc.close()
1005
1005
 
1006
1006
 
1007
+ @pytest.mark.asyncio
1008
+ async def test_v2_set_mode_stops_when_free_air_off_is_replaced() -> None:
1009
+ """A newer set_mode that replaces our FreeAir off also decides SysMode."""
1010
+ svc, controller = await _v2_free_air_controller()
1011
+ controller._system_settings["FreeAir"] = "on"
1012
+ controller.V2_ERROR_RETRY_INTERVAL = 0.1
1013
+ controller.V2_ERROR_RETRY_WINDOW = 1.0
1014
+ sent: list[dict[str, object]] = []
1015
+
1016
+ async def send(payload: dict[str, object]) -> str:
1017
+ sent.append(payload)
1018
+ if len(sent) == 1:
1019
+ raise ControllerCommandError("Server returned error state {ERROR}")
1020
+ return ""
1021
+
1022
+ controller._http_command_v2 = send # type: ignore[method-assign]
1023
+
1024
+ older = asyncio.create_task(controller.set_mode(Controller.Mode.COOL))
1025
+ await asyncio.sleep(0.05)
1026
+ await controller.set_mode(Controller.Mode.HEAT)
1027
+ await older
1028
+
1029
+ assert sent == [
1030
+ {"iSaveOn": 0},
1031
+ {"iSaveOn": 0},
1032
+ {"SysMode": v2_mod.mode_to_wire(Controller.Mode.HEAT)},
1033
+ ]
1034
+ await svc.close()
1035
+
1036
+
1007
1037
  @pytest.mark.asyncio
1008
1038
  async def test_v2_other_commands_do_not_fall_back_on_command_error() -> None:
1009
1039
  """Only FreeAir's known-unreliable V2 command gets a V1 fallback."""
@@ -0,0 +1,259 @@
1
+ """Latching on a device reconfiguration seen in a clean read."""
2
+
3
+ import asyncio
4
+ from collections.abc import AsyncIterator
5
+ from copy import deepcopy
6
+ from typing import Any, cast
7
+ from unittest.mock import AsyncMock
8
+
9
+ import pytest
10
+
11
+ from pizone import DeviceReconfigurationError, v2
12
+
13
+ from .conftest import MockController, MockDiscoveryService, add_mock_controller
14
+ from .v2_fixtures import SAMPLE_SYSTEM_V2, SAMPLE_ZONES_V2
15
+
16
+
17
+ @pytest.fixture
18
+ async def v2_controller() -> AsyncIterator[MockController]:
19
+ svc = MockDiscoveryService()
20
+ ctrl = MockController(
21
+ svc,
22
+ device_uid="000025841",
23
+ device_ip="192.0.2.1",
24
+ is_v2=True,
25
+ is_ipower=False,
26
+ )
27
+ ctrl._read_api = "v2"
28
+ ctrl.v2_system = deepcopy(SAMPLE_SYSTEM_V2)
29
+ ctrl.v2_zones = deepcopy(SAMPLE_ZONES_V2)
30
+ svc._claim(ctrl)
31
+ try:
32
+ await ctrl._initialize(
33
+ system_settings=v2.system_v2_to_settings(
34
+ SAMPLE_SYSTEM_V2["SystemV2"], ctrl.device_uid
35
+ )
36
+ )
37
+ ctrl.sent.clear()
38
+ yield ctrl
39
+ finally:
40
+ await ctrl.close()
41
+ await svc.close()
42
+
43
+
44
+ def _v1(service: MockDiscoveryService) -> MockController:
45
+ return cast(MockController, service._controller("000000001"))
46
+
47
+
48
+ @pytest.mark.parametrize(
49
+ ("field", "value", "expected"),
50
+ [
51
+ pytest.param("NoOfZones", 7, (8, 7), id="zone_count"),
52
+ pytest.param("NoOfConst", 2, (1, 2), id="const_count"),
53
+ pytest.param("SysType", "310", ("320", "310"), id="sys_type"),
54
+ pytest.param("FanAuto", "disabled", ("3-speed", "disabled"), id="fan_auto"),
55
+ ],
56
+ )
57
+ @pytest.mark.asyncio
58
+ async def test_vital_field_change_latches(
59
+ service: MockDiscoveryService, field: str, value: Any, expected: tuple
60
+ ) -> None:
61
+ controller = _v1(service)
62
+ controller.resources["SystemSettings"][field] = value
63
+
64
+ with pytest.raises(DeviceReconfigurationError) as err:
65
+ await controller.refresh_system()
66
+
67
+ assert err.value.changes == {field: expected}
68
+ assert controller.dump_state()["reconfigured"] == {field: expected}
69
+
70
+
71
+ @pytest.mark.asyncio
72
+ async def test_missing_fan_auto_matches_disabled() -> None:
73
+ svc = MockDiscoveryService()
74
+ controller = MockController(
75
+ svc,
76
+ device_uid="000000001",
77
+ device_ip="8.8.8.8",
78
+ is_v2=False,
79
+ is_ipower=False,
80
+ )
81
+ del controller.resources["SystemSettings"]["FanAuto"]
82
+ svc._claim(controller)
83
+ await controller._initialize(
84
+ system_settings=deepcopy(controller.resources["SystemSettings"])
85
+ )
86
+ # Fan modes read an absent FanAuto as disabled, so the check must too.
87
+ controller.resources["SystemSettings"]["FanAuto"] = "disabled"
88
+
89
+ await controller.refresh_system()
90
+
91
+ assert controller._reconfigured is None
92
+ await svc.close()
93
+
94
+
95
+ @pytest.mark.asyncio
96
+ async def test_faulted_read_does_not_latch(service: MockDiscoveryService) -> None:
97
+ controller = _v1(service)
98
+ settings = controller.resources["SystemSettings"]
99
+ settings["NoOfConst"] = 3
100
+ settings["UnitType"] = "error"
101
+
102
+ await controller.refresh_system()
103
+
104
+ assert controller._reconfigured is None
105
+ settings["UnitType"] = "Panasonic/Toshiba"
106
+ with pytest.raises(DeviceReconfigurationError):
107
+ await controller.refresh_system()
108
+
109
+
110
+ @pytest.mark.asyncio
111
+ async def test_unchanged_refresh_does_not_latch(service: MockDiscoveryService) -> None:
112
+ controller = _v1(service)
113
+
114
+ await controller.refresh_all()
115
+ await controller.refresh_all()
116
+
117
+ assert controller._reconfigured is None
118
+
119
+
120
+ @pytest.mark.parametrize(
121
+ ("zone_type", "latched"),
122
+ [
123
+ pytest.param("opcl", True, id="type_changed"),
124
+ pytest.param("error", False, id="type_faulted"),
125
+ ],
126
+ )
127
+ @pytest.mark.asyncio
128
+ async def test_zone_type_change_latches(
129
+ service: MockDiscoveryService, zone_type: str, latched: bool
130
+ ) -> None:
131
+ controller = _v1(service)
132
+ controller.resources["Zones1_4"][2]["Type"] = zone_type
133
+
134
+ if latched:
135
+ with pytest.raises(DeviceReconfigurationError) as err:
136
+ await controller.refresh_zones()
137
+ assert err.value.changes == {"Zone 3 Type": ("auto", "opcl")}
138
+ else:
139
+ await controller.refresh_zones()
140
+ assert controller._reconfigured is None
141
+
142
+
143
+ @pytest.mark.asyncio
144
+ async def test_latched_controller_raises_before_io(
145
+ service: MockDiscoveryService,
146
+ ) -> None:
147
+ controller = _v1(service)
148
+ controller.resources["SystemSettings"]["NoOfZones"] = 7
149
+ with pytest.raises(DeviceReconfigurationError):
150
+ await controller.refresh_system()
151
+ get = AsyncMock(wraps=controller._http_get)
152
+ controller._http_get = get # type: ignore[method-assign]
153
+ controller.sent.clear()
154
+
155
+ with pytest.raises(DeviceReconfigurationError):
156
+ await controller.refresh_all()
157
+ with pytest.raises(DeviceReconfigurationError):
158
+ await controller.set_on(False)
159
+ with pytest.raises(DeviceReconfigurationError):
160
+ await controller.zones[0].set_temp_setpoint(22.0)
161
+
162
+ get.assert_not_awaited()
163
+ assert controller.sent == []
164
+
165
+
166
+ @pytest.mark.asyncio
167
+ async def test_v1_reconfigure_outranks_zone_error(
168
+ service: MockDiscoveryService,
169
+ ) -> None:
170
+ controller = _v1(service)
171
+ controller.resources["SystemSettings"]["NoOfZones"] = 4
172
+ del controller.resources["Zones5_8"]
173
+
174
+ with pytest.raises(DeviceReconfigurationError) as err:
175
+ await controller.refresh_all()
176
+
177
+ assert err.value.changes == {"NoOfZones": (8, 4)}
178
+ assert isinstance(err.value.__cause__, ConnectionError)
179
+
180
+
181
+ @pytest.mark.asyncio
182
+ async def test_v2_reconfigure_raises_before_zone_requests(
183
+ v2_controller: MockController,
184
+ ) -> None:
185
+ cast(dict, v2_controller.v2_system)["SystemV2"]["NoOfZones"] = 1
186
+
187
+ with pytest.raises(DeviceReconfigurationError) as err:
188
+ await v2_controller.refresh_all()
189
+
190
+ assert err.value.changes == {"NoOfZones": (2, 1)}
191
+ assert [item[1]["iZoneV2Request"]["Type"] for item in v2_controller.sent] == [1]
192
+
193
+
194
+ @pytest.mark.asyncio
195
+ async def test_v2_zone_type_change_latches(v2_controller: MockController) -> None:
196
+ v2_controller.v2_zones[1]["ZonesV2"]["ZoneType"] = 3
197
+
198
+ with pytest.raises(DeviceReconfigurationError) as err:
199
+ await v2_controller.refresh_zones()
200
+
201
+ assert err.value.changes == {"Zone 2 Type": ("opcl", "auto")}
202
+
203
+
204
+ @pytest.mark.asyncio
205
+ async def test_command_whose_confirm_read_latches_still_returns(
206
+ service: MockDiscoveryService,
207
+ ) -> None:
208
+ controller = _v1(service)
209
+ controller.resources["SystemSettings"]["NoOfZones"] = 7
210
+
211
+ await controller.set_on(False)
212
+
213
+ assert controller._reconfigured == {"NoOfZones": (8, 7)}
214
+ with pytest.raises(DeviceReconfigurationError):
215
+ await controller.set_on(True)
216
+
217
+
218
+ @pytest.mark.asyncio
219
+ async def test_confirm_loop_stops_when_latched(v2_controller: MockController) -> None:
220
+ v2_controller.ZONE_CONFIRM_DELAY = 0.01
221
+ v2_controller.ZONE_CONFIRM_INTERVAL = 0.01
222
+ await v2_controller.zones[0].set_mode(v2_controller.zones[0].Mode.CLOSE)
223
+ v2_controller._reconfigured = {"NoOfZones": (2, 1)}
224
+ read = AsyncMock(wraps=v2_controller._v2_request)
225
+ v2_controller._v2_request = read # type: ignore[method-assign]
226
+ v2_controller._zone_confirm_wake.set()
227
+
228
+ task = v2_controller._zone_confirm_task
229
+ assert task is not None
230
+ await asyncio.wait_for(task, 2)
231
+
232
+ read.assert_not_awaited()
233
+
234
+
235
+ @pytest.mark.asyncio
236
+ async def test_recreated_controller_is_not_latched() -> None:
237
+ svc = MockDiscoveryService()
238
+ controller = await add_mock_controller(svc, "000000001", "8.8.8.8")
239
+ controller.resources["SystemSettings"]["NoOfZones"] = 4
240
+ with pytest.raises(DeviceReconfigurationError):
241
+ await controller.refresh_system()
242
+
243
+ await controller.close()
244
+ fresh = MockController(
245
+ svc,
246
+ device_uid="000000001",
247
+ device_ip="8.8.8.8",
248
+ is_v2=False,
249
+ is_ipower=False,
250
+ )
251
+ fresh.resources["SystemSettings"]["NoOfZones"] = 4
252
+ svc._claim(fresh)
253
+ await fresh._initialize(system_settings=fresh.resources["SystemSettings"])
254
+
255
+ await fresh.refresh_all()
256
+
257
+ assert fresh._reconfigured is None
258
+ assert len(fresh.zones) == 4
259
+ await svc.close()
@@ -1,5 +1,6 @@
1
1
  """Tests for zone property reads and command validation."""
2
2
 
3
+ import asyncio
3
4
  from collections.abc import AsyncIterator, Awaitable, Callable
4
5
  from copy import deepcopy
5
6
  from typing import cast
@@ -361,3 +362,99 @@ async def test_zone_status_property_decoding(
361
362
  zone._zone_data[key] = raw
362
363
 
363
364
  assert getattr(zone, attr) == expected
365
+
366
+
367
+ def _rejecting_send(
368
+ controller: MockController, rejections: int
369
+ ) -> list[dict[str, object]]:
370
+ """Make iZoneCommandV2 return {ERROR} for the first *rejections* sends."""
371
+ sent: list[dict[str, object]] = []
372
+ remaining = rejections
373
+
374
+ async def send(payload: dict[str, object]) -> str:
375
+ nonlocal remaining
376
+ sent.append(payload)
377
+ if remaining:
378
+ remaining -= 1
379
+ raise ControllerCommandError("Server returned error state {ERROR}")
380
+ return ""
381
+
382
+ controller._http_command_v2 = send # type: ignore[method-assign]
383
+ return sent
384
+
385
+
386
+ @pytest.fixture
387
+ def fast_retries(v2_controller: MockController) -> MockController:
388
+ v2_controller.V2_ERROR_RETRY_INTERVAL = 0.01
389
+ v2_controller.V2_ERROR_RETRY_WINDOW = 1.0
390
+ return v2_controller
391
+
392
+
393
+ @pytest.mark.asyncio
394
+ async def test_v2_command_retries_until_bridge_accepts(
395
+ fast_retries: MockController,
396
+ ) -> None:
397
+ sent = _rejecting_send(fast_retries, rejections=2)
398
+ zone = fast_retries.zones[0]
399
+
400
+ await zone.set_airflow_max(40)
401
+
402
+ assert sent == [{"ZoneMaxAir": {"Index": 0, "MaxAir": 40}}] * 3
403
+ assert zone.airflow_max == 40
404
+
405
+
406
+ @pytest.mark.asyncio
407
+ async def test_v2_command_gives_up_after_retry_window(
408
+ fast_retries: MockController,
409
+ ) -> None:
410
+ fast_retries.V2_ERROR_RETRY_WINDOW = 0.05
411
+ sent = _rejecting_send(fast_retries, rejections=1000)
412
+ zone = fast_retries.zones[0]
413
+ before = zone.airflow_max
414
+
415
+ with pytest.raises(ControllerCommandError):
416
+ await zone.set_airflow_max(40)
417
+
418
+ assert len(sent) > 1
419
+ assert zone.airflow_max == before
420
+
421
+
422
+ @pytest.mark.asyncio
423
+ async def test_v2_retry_releases_lock_for_other_writes(
424
+ fast_retries: MockController,
425
+ ) -> None:
426
+ sent = _rejecting_send(fast_retries, rejections=1)
427
+ zone = fast_retries.zones[0]
428
+ fast_retries.V2_ERROR_RETRY_INTERVAL = 0.1
429
+
430
+ retrying = asyncio.create_task(zone.set_airflow_max(40))
431
+ await asyncio.sleep(0.05)
432
+ await zone.set_airflow_min(10)
433
+ await retrying
434
+
435
+ assert sent == [
436
+ {"ZoneMaxAir": {"Index": 0, "MaxAir": 40}},
437
+ {"ZoneMinAir": {"Index": 0, "MinAir": 10}},
438
+ {"ZoneMaxAir": {"Index": 0, "MaxAir": 40}},
439
+ ]
440
+
441
+
442
+ @pytest.mark.asyncio
443
+ async def test_v2_newer_write_replaces_retrying_write(
444
+ fast_retries: MockController,
445
+ ) -> None:
446
+ sent = _rejecting_send(fast_retries, rejections=1)
447
+ zone = fast_retries.zones[0]
448
+ fast_retries.V2_ERROR_RETRY_INTERVAL = 0.1
449
+
450
+ retrying = asyncio.create_task(zone.set_airflow_max(40))
451
+ await asyncio.sleep(0.05)
452
+ await zone.set_airflow_max(45)
453
+ await retrying
454
+
455
+ # The replaced write is not sent again and does not overwrite the cache.
456
+ assert sent == [
457
+ {"ZoneMaxAir": {"Index": 0, "MaxAir": 40}},
458
+ {"ZoneMaxAir": {"Index": 0, "MaxAir": 45}},
459
+ ]
460
+ assert zone.airflow_max == 45
File without changes
File without changes
File without changes
File without changes
File without changes