aiocomfoconnect 0.4.2__tar.gz → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiocomfoconnect
3
- Version: 0.4.2
3
+ Version: 0.4.3
4
4
  Summary: aiocomfoconnect is an asyncio Python 3 library for communicating with a Zehnder ComfoAir Q350/450/600 ventilation system
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -85,6 +85,8 @@ $ python -m aiocomfoconnect set-property --host 192.168.1.213 30 1 4 6 120 # Se
85
85
  - `async get_temperature_profile()`: Get the temperature profile, or `None` when no profile is set and the unit follows its schedule.
86
86
  - `async set_temperature_profile(profile)`: Set the temperature profile. (warm / normal / cool)
87
87
  - `async get_property(prop, node_id=None)`: Get the value of a property, e.g. `PROPERTY_RMOT_HEATING_THRESHOLD`. It is read from the node the property lives on: the ventilation unit, or the ComfoClime for the `PROPERTY_CLIME_*` properties. Pass `node_id` to read it from another node. A `NodeNotFoundException` is raised when the node isn't on the bus.
88
+ - `async get_properties(props, node_id=None)`: Get several properties of one node in one request, converted like `get_property`, e.g. `await comfoconnect.get_properties([PROPERTY_MODEL, PROPERTY_SERIAL_NUMBER])`.
89
+ - `async get_node_info(node_id=None)`: Get the `NodeInfo` (name, model, article number, serial number, firmware version and hardware version) of a node, the ventilation unit by default, in one request. A property that the node doesn't have, like the model of the bridge, is `None`.
88
90
  - `async set_property(prop, value, node_id=None)`: Set a property, on the same node as `get_property`.
89
91
  - The airflow in m³/h of each fan speed is a property: `PROPERTY_FLOW_AWAY`, `PROPERTY_FLOW_LOW`, `PROPERTY_FLOW_MEDIUM` and `PROPERTY_FLOW_HIGH`, e.g. `await comfoconnect.set_property(PROPERTY_FLOW_LOW, 120)`.
90
92
  - Properties that are an enum, like `PROPERTY_SENSOR_VENTILATION_TEMP_PASSIVE`, `PROPERTY_SENSOR_VENTILATION_HUMIDITY_COMFORT` and `PROPERTY_SENSOR_VENTILATION_HUMIDITY_PROTECTION` (off / auto / on), `PROPERTY_TEMPERATURE_PROFILE_MODE` (adaptive / fixed), `PROPERTY_CLIME_SEASON` and `PROPERTY_CLIME_TEMPERATURE_PROFILE`, have `options`: `get_property` returns the option and `set_property` takes it. `get_property_constraints` still uses the raw values.
@@ -67,6 +67,8 @@ $ python -m aiocomfoconnect set-property --host 192.168.1.213 30 1 4 6 120 # Se
67
67
  - `async get_temperature_profile()`: Get the temperature profile, or `None` when no profile is set and the unit follows its schedule.
68
68
  - `async set_temperature_profile(profile)`: Set the temperature profile. (warm / normal / cool)
69
69
  - `async get_property(prop, node_id=None)`: Get the value of a property, e.g. `PROPERTY_RMOT_HEATING_THRESHOLD`. It is read from the node the property lives on: the ventilation unit, or the ComfoClime for the `PROPERTY_CLIME_*` properties. Pass `node_id` to read it from another node. A `NodeNotFoundException` is raised when the node isn't on the bus.
70
+ - `async get_properties(props, node_id=None)`: Get several properties of one node in one request, converted like `get_property`, e.g. `await comfoconnect.get_properties([PROPERTY_MODEL, PROPERTY_SERIAL_NUMBER])`.
71
+ - `async get_node_info(node_id=None)`: Get the `NodeInfo` (name, model, article number, serial number, firmware version and hardware version) of a node, the ventilation unit by default, in one request. A property that the node doesn't have, like the model of the bridge, is `None`.
70
72
  - `async set_property(prop, value, node_id=None)`: Set a property, on the same node as `get_property`.
71
73
  - The airflow in m³/h of each fan speed is a property: `PROPERTY_FLOW_AWAY`, `PROPERTY_FLOW_LOW`, `PROPERTY_FLOW_MEDIUM` and `PROPERTY_FLOW_HIGH`, e.g. `await comfoconnect.set_property(PROPERTY_FLOW_LOW, 120)`.
72
74
  - Properties that are an enum, like `PROPERTY_SENSOR_VENTILATION_TEMP_PASSIVE`, `PROPERTY_SENSOR_VENTILATION_HUMIDITY_COMFORT` and `PROPERTY_SENSOR_VENTILATION_HUMIDITY_PROTECTION` (off / auto / on), `PROPERTY_TEMPERATURE_PROFILE_MODE` (adaptive / fixed), `PROPERTY_CLIME_SEASON` and `PROPERTY_CLIME_TEMPERATURE_PROFILE`, have `options`: `get_property` returns the option and `set_property` takes it. `get_property_constraints` still uses the raw values.
@@ -13,7 +13,7 @@ from aiocomfoconnect import DEFAULT_NAME, DEFAULT_PIN, DEFAULT_UUID
13
13
  from aiocomfoconnect.comfoconnect import ComfoConnect
14
14
  from aiocomfoconnect.const import ProductId
15
15
  from aiocomfoconnect.discovery import discover_bridges
16
- from aiocomfoconnect.exceptions import BridgeNotFoundException, ComfoConnectNotAllowed
16
+ from aiocomfoconnect.exceptions import AioComfoConnectError, BridgeNotFoundException, ComfoConnectNotAllowed
17
17
  from aiocomfoconnect.properties import Property
18
18
  from aiocomfoconnect.sensors import SENSORS
19
19
 
@@ -24,6 +24,9 @@ PRODUCT_NAMES = {value: name.lower() for name, value in vars(ProductId).items()
24
24
  # How long show-sensor waits for the first value. The bridge only reports a sensor after the sensor hold (5 seconds by default).
25
25
  SENSOR_VALUE_TIMEOUT = 30
26
26
 
27
+ # How long list-nodes waits for the nodes to be announced. The bridge announces its own node a bit after connecting.
28
+ NODE_REQUEST_WAIT = 2
29
+
27
30
 
28
31
  class CliError(Exception):
29
32
  """An error that is shown to the user without a traceback."""
@@ -191,12 +194,25 @@ async def run_list_nodes(args):
191
194
  async with connected(args) as comfoconnect:
192
195
  await comfoconnect.cmd_node_request()
193
196
  # Nodes arrive as unsolicited notifications, so give the bridge a moment to report them all.
194
- await asyncio.sleep(2)
197
+ await asyncio.sleep(NODE_REQUEST_WAIT)
195
198
 
196
199
  print("Nodes on the ComfoNet bus:")
197
200
  for node in sorted(comfoconnect.nodes.values(), key=lambda n: n.node_id):
198
201
  product = PRODUCT_NAMES.get(node.product_id, "unknown")
199
202
  print(f"* node {node.node_id}: product {node.product_id} ({product}), zone {node.zone_id}, mode {node.mode}")
203
+ try:
204
+ info = await comfoconnect.get_node_info(node.node_id)
205
+ except AioComfoConnectError as exc:
206
+ print(f" could not read the node info: {exc}")
207
+ continue
208
+ fields = {
209
+ "name": info.name,
210
+ "model": info.model,
211
+ "firmware": info.firmware,
212
+ "hardware version": info.hardware_version,
213
+ "serial number": info.serial_number,
214
+ }
215
+ print(" " + ", ".join(f"{label}: {value}" for label, value in fields.items() if value is not None))
200
216
 
201
217
 
202
218
  def build_parser() -> argparse.ArgumentParser:
@@ -45,11 +45,21 @@ from aiocomfoconnect.exceptions import (
45
45
  ComfoConnectError,
46
46
  ComfoConnectNotAllowed,
47
47
  ComfoConnectOtherSession,
48
+ ComfoConnectRmiError,
48
49
  NodeNotFoundException,
49
50
  )
50
- from aiocomfoconnect.properties import Property, PropertyConstraints
51
+ from aiocomfoconnect.properties import (
52
+ PROPERTY_ARTICLE,
53
+ PROPERTY_FIRMWARE_VERSION,
54
+ PROPERTY_HARDWARE_VERSION,
55
+ PROPERTY_MODEL,
56
+ PROPERTY_NAME,
57
+ PROPERTY_SERIAL_NUMBER,
58
+ Property,
59
+ PropertyConstraints,
60
+ )
51
61
  from aiocomfoconnect.sensors import Sensor
52
- from aiocomfoconnect.util import bytearray_to_bits, bytestring, encode_pdo_value, version_decode
62
+ from aiocomfoconnect.util import bytearray_to_bits, encode_pdo_value, version_decode
53
63
 
54
64
  _LOGGER = logging.getLogger(__name__)
55
65
 
@@ -68,6 +78,45 @@ BYPASS_MODES = (VentilationSetting.AUTO, VentilationSetting.ON, VentilationSetti
68
78
  TEMPERATURE_PROFILES = (VentilationTemperatureProfile.NORMAL, VentilationTemperatureProfile.COOL, VentilationTemperatureProfile.WARM)
69
79
 
70
80
 
81
+ # The size in bytes of the value of the property types that aren't a string.
82
+ VALUE_SIZES = {PdoType.TYPE_CN_BOOL: 1, PdoType.TYPE_CN_VERSION: 4} | {pdo_type: size for pdo_type, (size, _) in NUMERIC_PROPERTY_TYPES.items()}
83
+
84
+
85
+ def _decode_value(property_type: Optional[int], raw: bytes) -> Any:
86
+ """Decode the raw value of a property of the given type. A type we don't know is returned as bytes."""
87
+ if property_type == PdoType.TYPE_CN_STRING:
88
+ return raw.decode("utf-8").rstrip("\x00")
89
+ if property_type in NUMERIC_PROPERTY_TYPES:
90
+ _, signed = NUMERIC_PROPERTY_TYPES[property_type]
91
+ return int.from_bytes(raw, byteorder="little", signed=signed)
92
+ if property_type == PdoType.TYPE_CN_BOOL:
93
+ return bool(raw[0])
94
+ if property_type == PdoType.TYPE_CN_VERSION:
95
+ return version_decode(int.from_bytes(raw, byteorder="little"))
96
+ return raw
97
+
98
+
99
+ def _property_value(prop: Property, value: Any) -> Any:
100
+ """Return the option or the scaled value of a decoded property value."""
101
+ if prop.options is None:
102
+ return prop.scaled(value)
103
+ if value not in prop.options:
104
+ raise ValueError(f"Invalid value: {value}")
105
+ return prop.options[value]
106
+
107
+
108
+ @dataclass
109
+ class NodeInfo:
110
+ """What a node tells about itself. A property that the node doesn't have is None, e.g. the model of the bridge."""
111
+
112
+ name: Optional[str]
113
+ model: Optional[str]
114
+ article_number: Optional[str]
115
+ serial_number: Optional[str]
116
+ firmware: Optional[str]
117
+ hardware_version: Optional[int]
118
+
119
+
71
120
  @dataclass
72
121
  class TimerEntry:
73
122
  """A timer of the SCHEDULE unit, that overrides a setting with a value for a while."""
@@ -365,27 +414,76 @@ class ComfoConnect(Bridge):
365
414
  async def get_property(self, prop: Property, node_id: Optional[int] = None) -> Any:
366
415
  """Get a property from the node it lives on (or node_id), and convert it to the right type, its option or its scaled value."""
367
416
  value = await self.get_single_property(prop.unit, prop.subunit, prop.property_id, prop.property_type, node_id=self._node_id_for(prop, node_id))
368
- if prop.options is None:
369
- return prop.scaled(value)
370
- if value not in prop.options:
371
- raise ValueError(f"Invalid value: {value}")
372
- return prop.options[value]
417
+ return _property_value(prop, value)
418
+
419
+ async def get_properties(self, props: List[Property], node_id: Optional[int] = None) -> List[Any]:
420
+ """Get several properties of one node in one request, converted like get_property.
421
+
422
+ The properties are read in groups of consecutive properties of the same unit and subunit, of at most 7 like the
423
+ official app. A ValueError is raised for properties on different nodes, or of a type whose size we don't know.
424
+ """
425
+ node_ids = {self._node_id_for(prop, node_id) for prop in props}
426
+ if len(node_ids) > 1:
427
+ raise ValueError("The properties live on different nodes")
428
+ for prop in props:
429
+ if prop.property_type != PdoType.TYPE_CN_STRING and prop.property_type not in VALUE_SIZES:
430
+ raise ValueError(f"Property type {prop.property_type} can't be read with other properties")
431
+
432
+ groups: List[List[Property]] = []
433
+ for prop in props:
434
+ if groups and len(groups[-1]) < 7 and (groups[-1][0].unit, groups[-1][0].subunit) == (prop.unit, prop.subunit):
435
+ groups[-1].append(prop)
436
+ else:
437
+ groups.append([prop])
438
+
439
+ request = [0x02, len(groups)]
440
+ for group in groups:
441
+ request += [group[0].unit, group[0].subunit, 0x10 | len(group)] + [prop.property_id for prop in group]
442
+ result = await self.cmd_rmi_request(bytes(request), node_id=node_ids.pop() if node_ids else None)
443
+
444
+ # The values follow each other: a string ends with a NUL, the other types have a fixed size.
445
+ message = bytes(result.message)
446
+ values = []
447
+ for prop in props:
448
+ if prop.property_type == PdoType.TYPE_CN_STRING:
449
+ size = message.find(b"\x00") + 1 or len(message)
450
+ else:
451
+ size = VALUE_SIZES[prop.property_type]
452
+ if len(message) < size:
453
+ raise ValueError(f"The response is too short for the value of property {prop.property_id}")
454
+ values.append(_property_value(prop, _decode_value(prop.property_type, message[:size])))
455
+ message = message[size:]
456
+ if message:
457
+ raise ValueError(f"Unexpected {len(message)} bytes at the end of the response")
458
+ return values
459
+
460
+ async def get_node_info(self, node_id: Optional[int] = None) -> NodeInfo:
461
+ """Get the NodeInfo of a node (the ventilation unit by default), in one request when the node has all its properties.
462
+
463
+ Raises ComfoConnectRmiError when none of the properties can be read, e.g. for a node that doesn't exist.
464
+ """
465
+ props = [PROPERTY_NAME, PROPERTY_MODEL, PROPERTY_ARTICLE, PROPERTY_SERIAL_NUMBER, PROPERTY_FIRMWARE_VERSION, PROPERTY_HARDWARE_VERSION]
466
+ try:
467
+ return NodeInfo(*await self.get_properties(props, node_id))
468
+ except ComfoConnectRmiError as exc:
469
+ error = exc
470
+
471
+ # A request fails as a whole when the node lacks one of the properties, so read them one by one.
472
+ async def get_or_none(prop: Property) -> Any:
473
+ try:
474
+ return await self.get_property(prop, node_id)
475
+ except ComfoConnectRmiError:
476
+ return None
477
+
478
+ values = [await get_or_none(prop) for prop in props]
479
+ if all(value is None for value in values):
480
+ raise error # Nothing could be read, e.g. the node doesn't exist.
481
+ return NodeInfo(*values)
373
482
 
374
483
  async def get_single_property(self, unit: int, subunit: int, property_id: int, property_type: int = None, node_id: Optional[int] = None) -> Any:
375
484
  """Get a property and convert to the right type."""
376
485
  result = await self.cmd_rmi_request(bytes([0x01, unit, subunit, 0x10, property_id]), node_id=node_id)
377
-
378
- if property_type == PdoType.TYPE_CN_STRING:
379
- return result.message.decode("utf-8").rstrip("\x00")
380
- if property_type in NUMERIC_PROPERTY_TYPES:
381
- _, signed = NUMERIC_PROPERTY_TYPES[property_type]
382
- return int.from_bytes(result.message, byteorder="little", signed=signed)
383
- if property_type == PdoType.TYPE_CN_BOOL:
384
- return bool(result.message[0])
385
- if property_type == PdoType.TYPE_CN_VERSION:
386
- return version_decode(int.from_bytes(result.message, byteorder="little"))
387
-
388
- return result.message
486
+ return _decode_value(property_type, result.message)
389
487
 
390
488
  async def get_property_constraints(self, prop: Property, node_id: Optional[int] = None) -> PropertyConstraints:
391
489
  """Get the (scaled) value of a numeric property, together with the range and step size the unit accepts, in one request."""
@@ -402,12 +500,6 @@ class ComfoConnect(Bridge):
402
500
  value, minimum, maximum, step = (int.from_bytes(message[i : i + size], byteorder="little", signed=signed) for i in range(0, 4 * size, size))
403
501
  return PropertyConstraints(value=prop.scaled(value), minimum=prop.scaled(minimum), maximum=prop.scaled(maximum), step=prop.scaled(step))
404
502
 
405
- async def get_multiple_properties(self, unit: int, subunit: int, property_ids: List[int], node_id: Optional[int] = None) -> Any:
406
- """Get multiple properties."""
407
- result = await self.cmd_rmi_request(bytestring([0x02, unit, subunit, 0x01, 0x10 | len(property_ids), bytes(property_ids)]), node_id=node_id)
408
-
409
- return result.message
410
-
411
503
  async def set_property(self, prop: Property, value: int | float | str, node_id: Optional[int] = None) -> Any:
412
504
  """Set a property on the node it lives on (or node_id), encoded for its type.
413
505
 
@@ -50,6 +50,7 @@ class PropertyConstraints:
50
50
 
51
51
 
52
52
  PROPERTY_SERIAL_NUMBER = Property(UNIT_NODE, 0x01, 0x04, PdoType.TYPE_CN_STRING)
53
+ PROPERTY_HARDWARE_VERSION = Property(UNIT_NODE, 0x01, 0x05, PdoType.TYPE_CN_UINT8)
53
54
  PROPERTY_FIRMWARE_VERSION = Property(UNIT_NODE, 0x01, 0x06, PdoType.TYPE_CN_VERSION) # A UINT32, decoded with version_decode().
54
55
  PROPERTY_MODEL = Property(UNIT_NODE, 0x01, 0x08, PdoType.TYPE_CN_STRING)
55
56
  PROPERTY_ARTICLE = Property(UNIT_NODE, 0x01, 0x0B, PdoType.TYPE_CN_STRING)
@@ -5,11 +5,6 @@ from __future__ import annotations
5
5
  from aiocomfoconnect.const import NUMERIC_PROPERTY_TYPES, PdoType
6
6
 
7
7
 
8
- def bytestring(arr):
9
- """Join an array of bytes into a bytestring. Unlike `bytes()`, this method supports a mixed array with integers and bytes."""
10
- return b"".join([i if isinstance(i, bytes) else bytes([i]) for i in arr])
11
-
12
-
13
8
  def bytearray_to_bits(arr):
14
9
  """Convert a bytearray to a list of set bits."""
15
10
  bits = []
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "aiocomfoconnect"
3
- version = "0.4.2"
3
+ version = "0.4.3"
4
4
  description = "aiocomfoconnect is an asyncio Python 3 library for communicating with a Zehnder ComfoAir Q350/450/600 ventilation system"
5
5
  authors = ["Michaël Arnauts <michael.arnauts@gmail.com>"]
6
6
  license = "MIT"
File without changes