python-izone 2.0.0__py3-none-any.whl → 2.1.0__py3-none-any.whl

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.
pizone/__init__.py CHANGED
@@ -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",
pizone/controller.py CHANGED
@@ -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
 
@@ -175,6 +189,9 @@ class Controller:
175
189
  self._izone_ok: bool = True
176
190
  self._fault_fields: tuple[str, ...] = ()
177
191
  self._last_fault: dict[str, Any] | None = None
192
+ # System fields the zones and fan modes were built from at connect.
193
+ self._built_from: dict[str, Any] | None = None
194
+ self._reconfigured: dict[str, tuple[Any, Any]] | None = None
178
195
  self._on_address_changed: Callable[[ControllerEndpoint], None] | None = None
179
196
 
180
197
  self._sending_lock = Lock()
@@ -211,10 +228,11 @@ class Controller:
211
228
  self._set_bridge_ok(True)
212
229
 
213
230
  def _nudge_scan(self) -> None:
214
- """Non-blocking cooled-down IASD scan after HTTP transport failure."""
231
+ """Non-blocking cooled-down rediscovery after HTTP transport failure."""
215
232
  if self._closed:
216
233
  return
217
234
  self._discovery_service.schedule_cooled_scan()
235
+ self._discovery_service.schedule_name_check(self._device_uid)
218
236
 
219
237
  @classmethod
220
238
  async def create(
@@ -259,19 +277,23 @@ class Controller:
259
277
  if settings is None:
260
278
  raise ConnectionError("SystemSettings device ID mismatch")
261
279
 
262
- if self._system_settings:
263
- fan_auto = str(self._system_settings.get("FanAuto", "disabled"))
264
- self.fan_modes = Controller._VALID_FAN_MODES.get(
265
- fan_auto, Controller._VALID_FAN_MODES["unknown"]
266
- )
267
- else:
268
- self.fan_modes = Controller._VALID_FAN_MODES["disabled"]
280
+ self.fan_modes = Controller._VALID_FAN_MODES.get(
281
+ self._fan_auto(self._system_settings),
282
+ Controller._VALID_FAN_MODES["unknown"],
283
+ )
269
284
 
270
285
  zone_count = int(settings["NoOfZones"])
271
286
  self.zones = [Zone(self, i) for i in range(zone_count)]
272
287
 
273
288
  await self._fetch_zones()
274
289
 
290
+ self._built_from = {
291
+ "NoOfZones": zone_count,
292
+ "NoOfConst": settings.get("NoOfConst"),
293
+ "SysType": settings.get("SysType"),
294
+ "FanAuto": self._fan_auto(self._system_settings),
295
+ }
296
+
275
297
  await self._probe_power()
276
298
 
277
299
  async def _probe_power(self) -> None:
@@ -346,6 +368,7 @@ class Controller:
346
368
  "fan_modes": [fan.value for fan in self.fan_modes],
347
369
  "system_settings": dict(self._system_settings),
348
370
  "last_fault": self._last_fault,
371
+ "reconfigured": self._reconfigured,
349
372
  "zones": [zone.dump_state() for zone in self.zones],
350
373
  "power": self._power.dump_state() if self._power is not None else None,
351
374
  }
@@ -848,6 +871,7 @@ class Controller:
848
871
  """System + zones [+ power] fetch (no refresh scope)."""
849
872
  if self._read_api == "v2":
850
873
  await self._fetch_system()
874
+ self._raise_if_reconfigured()
851
875
  await self._fetch_zones()
852
876
  await self._fetch_power()
853
877
  return
@@ -894,8 +918,56 @@ class Controller:
894
918
 
895
919
  self._system_settings = values
896
920
  self._set_izone_ok(True)
921
+ if not faults and self._built_from is not None:
922
+ self._check_reconfigured(values)
897
923
  return values
898
924
 
925
+ @staticmethod
926
+ def _fan_auto(values: ControllerData) -> str:
927
+ """Return FanAuto as the fan modes read it; absent means disabled."""
928
+ if not values:
929
+ return "disabled"
930
+ return str(values.get("FanAuto", "disabled"))
931
+
932
+ def _check_reconfigured(self, values: ControllerData) -> None:
933
+ """Latch if a clean read no longer matches what was built at connect."""
934
+ built = cast(dict[str, Any], self._built_from)
935
+ if (
936
+ int(values["NoOfZones"]) == built["NoOfZones"]
937
+ and values.get("NoOfConst") == built["NoOfConst"]
938
+ and values.get("SysType") == built["SysType"]
939
+ and self._fan_auto(values) == built["FanAuto"]
940
+ ):
941
+ return
942
+ current = {
943
+ "NoOfZones": int(values["NoOfZones"]),
944
+ "NoOfConst": values.get("NoOfConst"),
945
+ "SysType": values.get("SysType"),
946
+ "FanAuto": self._fan_auto(values),
947
+ }
948
+ self._note_reconfigured(
949
+ {
950
+ field: (old, current[field])
951
+ for field, old in built.items()
952
+ if current[field] != old
953
+ }
954
+ )
955
+
956
+ def _note_reconfigured(self, changes: dict[str, tuple[Any, Any]]) -> None:
957
+ """Latch the reconfigured state; it only clears with a new controller."""
958
+ if self._reconfigured is None:
959
+ self._reconfigured = {}
960
+ _LOG.warning(
961
+ "iZone system reconfigured uid=%s: %s",
962
+ self._device_uid,
963
+ DeviceReconfigurationError(changes),
964
+ )
965
+ self._reconfigured.update(changes)
966
+
967
+ def _raise_if_reconfigured(self) -> None:
968
+ if self._reconfigured is not None:
969
+ raise DeviceReconfigurationError(dict(self._reconfigured))
970
+
899
971
  def _record_faults(
900
972
  self, values: ControllerData, faults: list[str], *, offline: bool
901
973
  ) -> None:
@@ -976,8 +1048,10 @@ class Controller:
976
1048
 
977
1049
  Raises:
978
1050
  ConnectionError: If the HTTP request fails.
1051
+ DeviceReconfigurationError: If the system was reconfigured.
979
1052
 
980
1053
  """
1054
+ self._raise_if_reconfigured()
981
1055
  if send is None:
982
1056
  send = value
983
1057
 
@@ -1007,6 +1081,7 @@ class Controller:
1007
1081
  self, command: str, data: dict[str, Any], zone_index: int
1008
1082
  ) -> None:
1009
1083
  """POST a zone command and confirm with a zone refresh."""
1084
+ self._raise_if_reconfigured()
1010
1085
  async with self._sending_lock, self._refresh_scope():
1011
1086
  if self._read_api == "v2":
1012
1087
  if self._closed:
@@ -1081,7 +1156,11 @@ class Controller:
1081
1156
  """Bounded, read-only confirmation; never resend a zone command."""
1082
1157
  loop = asyncio.get_running_loop()
1083
1158
  try:
1084
- while self._zone_mode_confirmations and not self._closed:
1159
+ while (
1160
+ self._zone_mode_confirmations
1161
+ and not self._closed
1162
+ and self._reconfigured is None
1163
+ ):
1085
1164
  self._expire_zone_modes(loop.time())
1086
1165
  if not self._zone_mode_confirmations:
1087
1166
  break
pizone/discovery.py CHANGED
@@ -119,6 +119,15 @@ _FAILURE_RANK = {
119
119
  type _VerifyResult = ControllerEndpoint | UnverifiedEndpoint | None
120
120
 
121
121
 
122
+ def _is_ipv4(host: str) -> bool:
123
+ """Return whether *host* is an IPv4 address rather than a name."""
124
+ try:
125
+ IPv4Address(host)
126
+ except ValueError:
127
+ return False
128
+ return True
129
+
130
+
122
131
  @dataclass(slots=True)
123
132
  class _Entry:
124
133
  state: _State
@@ -128,6 +137,10 @@ class _Entry:
128
137
  # for KNOWN/CLAIMED a move that applies only once it answers.
129
138
  candidate: ControllerEndpoint | None = None
130
139
  verify: Task[_VerifyResult] | None = None
140
+ # CLAIMED only: the name the controller was created from, re-resolved
141
+ # after a transport failure since UDP discovery may not reach the bridge.
142
+ host_name: str | None = None
143
+ last_name_check: float = float("-inf")
131
144
 
132
145
 
133
146
  class DiscoveryService:
@@ -295,6 +308,43 @@ class DiscoveryService:
295
308
 
296
309
  asyncio.get_running_loop().create_task(_run())
297
310
 
311
+ def schedule_name_check(self, uid: str) -> None:
312
+ """Re-resolve a claimed controller's name in the background, if it has one.
313
+
314
+ Repoints the controller when its UID answers at a new address. Cooled
315
+ down per UID.
316
+ """
317
+ if self.is_closed:
318
+ return
319
+ entry = self._entry(uid, _State.CLAIMED)
320
+ if entry is None or (name := entry.host_name) is None:
321
+ return
322
+ now = asyncio.get_running_loop().time()
323
+ if now - entry.last_name_check < RESCAN_COOLDOWN:
324
+ return
325
+ entry.last_name_check = now
326
+
327
+ async def _run() -> None:
328
+ try:
329
+ addresses = await self._resolve(name)
330
+ if entry.endpoint.host in addresses:
331
+ return
332
+ if entry.candidate is not None and entry.candidate.host in addresses:
333
+ return # A UDP verify of that address is already in flight.
334
+ probed = await self._probe_first(addresses, expected_uid=uid)
335
+ if isinstance(probed, _ProbeFailed):
336
+ _LOG.debug(
337
+ "Name %s for %s did not verify: %s", name, uid, probed.failure
338
+ )
339
+ return
340
+ if self.is_closed or self._endpoints.get(uid) is not entry:
341
+ return
342
+ self._apply_verified(probed.endpoint)
343
+ except Exception: # noqa: BLE001
344
+ _LOG.debug("Name check for %s failed", uid, exc_info=True)
345
+
346
+ self.create_task(_run())
347
+
298
348
  def _entry(self, uid: str, *states: _State) -> _Entry | None:
299
349
  """Return the entry for *uid* when it is in one of *states*."""
300
350
  entry = self._endpoints.get(uid)
@@ -429,7 +479,7 @@ class DiscoveryService:
429
479
  if self._discover_all_notified is not None:
430
480
  self._discover_all_notified.add(endpoint.uid)
431
481
 
432
- async def discover_by_host(self, host: str) -> ControllerEndpoint | None:
482
+ async def discover_by_host(self, host: str) -> ControllerEndpoint:
433
483
  """Return the controller endpoint at *host*, an IPv4 address or a name.
434
484
 
435
485
  A name is resolved to IPv4 addresses first; the returned endpoint always
@@ -604,9 +654,10 @@ class DiscoveryService:
604
654
 
605
655
  Preferred entry point after :func:`create_discovery`. One-shot per
606
656
  UID. *host* may be an IPv4 address or a name; a name is resolved and
607
- the controller runs on the IP that answers. HTTP probe is the trust
608
- boundary; callers must handle the device being unreachable even after a
609
- recent discovery notify.
657
+ the controller runs on the IP that answers. The name is resolved again
658
+ after a transport failure, in case the bridge moved. HTTP probe is the
659
+ trust boundary; callers must handle the device being unreachable even
660
+ after a recent discovery notify.
610
661
 
611
662
  Raises:
612
663
  UnpairedBridgeError: If *uid* is the unpaired placeholder (no I/O).
@@ -657,6 +708,9 @@ class DiscoveryService:
657
708
  del self._endpoints[uid]
658
709
  raise
659
710
 
711
+ if not _is_ipv4(host) and (claimed := self._entry(uid, _State.CLAIMED)):
712
+ claimed.host_name = host
713
+
660
714
  if pending_address_changed is not None and on_address_changed is not None:
661
715
  self.schedule_address_changed(on_address_changed, pending_address_changed)
662
716
  return controller
pizone/exceptions.py CHANGED
@@ -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
 
pizone/power.py CHANGED
@@ -148,8 +148,11 @@ class PowerDevice:
148
148
  class PowerGroup:
149
149
  """Grouped power channels."""
150
150
 
151
- def __init__(self, power: Power, channels: Iterable[PowerChannel]) -> None:
151
+ def __init__(
152
+ self, power: Power, group_number: int, channels: Iterable[PowerChannel]
153
+ ) -> None:
152
154
  self._power = power
155
+ self._group_number = group_number
153
156
  self._channels = tuple(channels)
154
157
  devices: set[PowerDevice] = set()
155
158
  for chan in channels:
@@ -159,7 +162,7 @@ class PowerGroup:
159
162
  @property
160
163
  def group_number(self) -> int:
161
164
  """The group id."""
162
- return self._channels[0].group_number or -1
165
+ return self._group_number
163
166
 
164
167
  @property
165
168
  def name(self) -> str:
@@ -218,7 +221,9 @@ class Power:
218
221
  for chan in dev.channels:
219
222
  if chan.group_number is not None:
220
223
  gdict.setdefault(chan.group_number, []).append(chan)
221
- self._groups = tuple(PowerGroup(self, gl) for gl in gdict.values())
224
+ self._groups = tuple(
225
+ PowerGroup(self, number, chans) for number, chans in gdict.items()
226
+ )
222
227
 
223
228
  async def refresh(self) -> bool:
224
229
  """Refresh power usage data from the device.
pizone/version.py CHANGED
@@ -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.0'
22
- __version_tuple__ = version_tuple = (2, 0, 0)
21
+ __version__ = version = '2.1.0'
22
+ __version_tuple__ = version_tuple = (2, 1, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
pizone/zone.py CHANGED
@@ -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:
@@ -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]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-izone
3
- Version: 2.0.0
3
+ Version: 2.1.0
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,15 @@
1
+ pizone/__init__.py,sha256=Q3in9_rEc4gMUJJqOkrvcJJQoCAl2pQIcAnTB_sxQBI,3010
2
+ pizone/const.py,sha256=0skTh6zBe61AJ_57fqdBrxz3aVBM3T4Ak_cPSkOx2Bo,153
3
+ pizone/controller.py,sha256=umLIQicUYuhqm2iJ2ECj-aEefRlasyH6lv_40ogMfac,50274
4
+ pizone/discovery.py,sha256=UX5IAZTAXEk51nHsCLzFe4W80MZjlm31W8HYfszGuwo,43447
5
+ pizone/exceptions.py,sha256=IJMsGOocv-sqBDsZP4MuOb_a3b1kRhGLig3YykncgI0,4527
6
+ pizone/power.py,sha256=2ltoFotv3phsRJHXxP9Yu7M4PmvUVi8Q_0KJUVvuGkc,10533
7
+ pizone/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pizone/types.py,sha256=W7pAoBPw1cDt0V_5MbasgUiz7Iwq0zfdxpH4gHTmzsQ,2860
9
+ pizone/v2.py,sha256=F-jsKfOVFAtRrjzHeGQcuG48_DJ3C-0sRKE_2urTwEw,19276
10
+ pizone/version.py,sha256=v9WVy_5yL3epBJmMyIAo86Fa1LzYly1fPB2fENrVANg,520
11
+ pizone/zone.py,sha256=TaUnHKZUSupP1NHy8SJglXmkv6yG42e-MUu20u00Pv0,10909
12
+ python_izone-2.1.0.dist-info/METADATA,sha256=SypgaparUHrPPq_CDRy2yYgfP3ND0V0ilvPTVr9P5Ko,4282
13
+ python_izone-2.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ python_izone-2.1.0.dist-info/licenses/licence.txt,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
15
+ python_izone-2.1.0.dist-info/RECORD,,
@@ -1,15 +0,0 @@
1
- pizone/__init__.py,sha256=0mUQKWmIebkS8h5yxgqVOqJAXfmQcESGsnkCh6Dkvbo,2944
2
- pizone/const.py,sha256=0skTh6zBe61AJ_57fqdBrxz3aVBM3T4Ak_cPSkOx2Bo,153
3
- pizone/controller.py,sha256=oenlsQ1LnVCQFKCFGUy5yMt9kDW6xhuwOwFGHQ9GjXA,47255
4
- pizone/discovery.py,sha256=raW8FYVsOin8pjHnNq9yJ5va31DXLvAWve6A1l47aPw,41265
5
- pizone/exceptions.py,sha256=gd4Xuo05TDtQRob1F65WWhLBEKhsWveK3nK6w-j8Lr4,3270
6
- pizone/power.py,sha256=1nwdOi6w-FfdctIDtOxYTnQaY0mC2U1K0bUyRV3iMeg,10433
7
- pizone/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- pizone/types.py,sha256=W7pAoBPw1cDt0V_5MbasgUiz7Iwq0zfdxpH4gHTmzsQ,2860
9
- pizone/v2.py,sha256=F-jsKfOVFAtRrjzHeGQcuG48_DJ3C-0sRKE_2urTwEw,19276
10
- pizone/version.py,sha256=M8-womMCm6RC2xFuYRGDGvgpBN64psyQZImZ5vOrGmc,520
11
- pizone/zone.py,sha256=u6NLmha6fr19_75UOnipkSTQ-PPkhVQ9ivpqRCchq6c,10470
12
- python_izone-2.0.0.dist-info/METADATA,sha256=Im9lkaaMQX3woNBlA7ypmc9qZa4bpHh_sEdDW50QCqQ,4282
13
- python_izone-2.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
- python_izone-2.0.0.dist-info/licenses/licence.txt,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
15
- python_izone-2.0.0.dist-info/RECORD,,