aiocomfoconnect 0.4.3__tar.gz → 0.4.5__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.3
3
+ Version: 0.4.5
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
@@ -63,11 +63,14 @@ $ python -m aiocomfoconnect set-property --host 192.168.1.213 30 1 4 6 120 # Se
63
63
 
64
64
  ## Available methods
65
65
 
66
- - `async connect()`: Connect to the bridge. The connection is kept: when it is lost, it reconnects, and when nothing was received for `heartbeat_interval` seconds (30 by default, `None` disables it), it checks that the bridge still answers.
66
+ - `async connect()`: Connect to the bridge. The connection is kept: when it is lost, it reconnects, and when nothing was sent or received for `heartbeat_interval` seconds (30 by default, `None` disables it), it asks the bridge for its time. That keeps the bridge from closing the connection (it does so after about 90 seconds in which the client sent nothing, even while it pushes sensor values), and detects a bridge that stopped answering.
67
67
  - `connection_state_callback`: Pass it to `ComfoConnect()` to be called with a `ConnectionState` when the state of the session changes.
68
+ - `node_callback`: Pass it to `ComfoConnect()` to be called with a `Node` every time the bridge announces one: at the start of every session (already while `connect()` runs, and often more than once), and when a node joins or goes offline (`node.is_offline`).
68
69
  - `async disconnect()`: Disconnect from the bridge.
69
70
  - `async register_sensor(sensor)`: Register a sensor.
70
71
  - `async deregister_sensor(sensor)`: Deregister a sensor.
72
+ - `sensor_values`: The latest value of every registered sensor, by sensor id, converted like for the sensor callback (`None` until the bridge sent one).
73
+ - `bridge_node`: The `Node` of the bridge itself on the ComfoNet bus: product id 222 for a ComfoConnect Pro, 5 for a ComfoConnect LAN C, or 9 for the WiFi connection module of a ComfoAir Flex. It is `None` when the bridge didn't announce it (yet): it does so a little after the ventilation unit.
71
74
  - `async get_mode()`: Get the ventilation mode.
72
75
  - `async set_mode(mode)`: Set the ventilation mode. (auto / manual) Selecting `auto` also cancels the temporary fan-speed override and returns control to the unit's schedule.
73
76
  - `async get_comfocool_mode()`: Get Comfocool mode
@@ -86,13 +89,12 @@ $ python -m aiocomfoconnect set-property --host 192.168.1.213 30 1 4 6 120 # Se
86
89
  - `async set_temperature_profile(profile)`: Set the temperature profile. (warm / normal / cool)
87
90
  - `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
91
  - `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`.
92
+ - `async get_node_info(node_id=None)`: Get the `NodeInfo` (name, model, article number, serial number, firmware version, hardware version and product variant) 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`.
90
93
  - `async set_property(prop, value, node_id=None)`: Set a property, on the same node as `get_property`.
91
94
  - 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)`.
92
95
  - 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.
93
96
  - Temperatures in tenths of a degree, like `PROPERTY_RMOT_HEATING_THRESHOLD`, `PROPERTY_PROFILE_TEMPERATURE_NORMAL` and the ComfoClime temperatures, have `scale=0.1`: `get_property` and `get_property_constraints` return °C (215 becomes 21.5) and `set_property` takes °C.
94
97
  - `async get_property_constraints(prop, node_id=None)`: Get the value of a numeric property, together with the range and step size the unit accepts.
95
- - `bridge_type`: The type of the bridge (`GatewayType.LANC`, `SEASON` or `PRO`). Discovery reports it, and a ComfoConnect Pro is also recognised once a session has started.
96
98
 
97
99
  ### Low-level API
98
100
 
@@ -45,11 +45,14 @@ $ python -m aiocomfoconnect set-property --host 192.168.1.213 30 1 4 6 120 # Se
45
45
 
46
46
  ## Available methods
47
47
 
48
- - `async connect()`: Connect to the bridge. The connection is kept: when it is lost, it reconnects, and when nothing was received for `heartbeat_interval` seconds (30 by default, `None` disables it), it checks that the bridge still answers.
48
+ - `async connect()`: Connect to the bridge. The connection is kept: when it is lost, it reconnects, and when nothing was sent or received for `heartbeat_interval` seconds (30 by default, `None` disables it), it asks the bridge for its time. That keeps the bridge from closing the connection (it does so after about 90 seconds in which the client sent nothing, even while it pushes sensor values), and detects a bridge that stopped answering.
49
49
  - `connection_state_callback`: Pass it to `ComfoConnect()` to be called with a `ConnectionState` when the state of the session changes.
50
+ - `node_callback`: Pass it to `ComfoConnect()` to be called with a `Node` every time the bridge announces one: at the start of every session (already while `connect()` runs, and often more than once), and when a node joins or goes offline (`node.is_offline`).
50
51
  - `async disconnect()`: Disconnect from the bridge.
51
52
  - `async register_sensor(sensor)`: Register a sensor.
52
53
  - `async deregister_sensor(sensor)`: Deregister a sensor.
54
+ - `sensor_values`: The latest value of every registered sensor, by sensor id, converted like for the sensor callback (`None` until the bridge sent one).
55
+ - `bridge_node`: The `Node` of the bridge itself on the ComfoNet bus: product id 222 for a ComfoConnect Pro, 5 for a ComfoConnect LAN C, or 9 for the WiFi connection module of a ComfoAir Flex. It is `None` when the bridge didn't announce it (yet): it does so a little after the ventilation unit.
53
56
  - `async get_mode()`: Get the ventilation mode.
54
57
  - `async set_mode(mode)`: Set the ventilation mode. (auto / manual) Selecting `auto` also cancels the temporary fan-speed override and returns control to the unit's schedule.
55
58
  - `async get_comfocool_mode()`: Get Comfocool mode
@@ -68,13 +71,12 @@ $ python -m aiocomfoconnect set-property --host 192.168.1.213 30 1 4 6 120 # Se
68
71
  - `async set_temperature_profile(profile)`: Set the temperature profile. (warm / normal / cool)
69
72
  - `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
73
  - `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`.
74
+ - `async get_node_info(node_id=None)`: Get the `NodeInfo` (name, model, article number, serial number, firmware version, hardware version and product variant) 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`.
72
75
  - `async set_property(prop, value, node_id=None)`: Set a property, on the same node as `get_property`.
73
76
  - 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)`.
74
77
  - 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.
75
78
  - Temperatures in tenths of a degree, like `PROPERTY_RMOT_HEATING_THRESHOLD`, `PROPERTY_PROFILE_TEMPERATURE_NORMAL` and the ComfoClime temperatures, have `scale=0.1`: `get_property` and `get_property_constraints` return °C (215 becomes 21.5) and `set_property` takes °C.
76
79
  - `async get_property_constraints(prop, node_id=None)`: Get the value of a numeric property, together with the range and step size the unit accepts.
77
- - `bridge_type`: The type of the bridge (`GatewayType.LANC`, `SEASON` or `PRO`). Discovery reports it, and a ComfoConnect Pro is also recognised once a session has started.
78
80
 
79
81
  ### Low-level API
80
82
 
@@ -43,7 +43,7 @@ async def connected(args, *, connect: bool = True, **kwargs) -> AsyncIterator[Co
43
43
  if not bridges:
44
44
  raise BridgeNotFoundException("No bridge found")
45
45
 
46
- comfoconnect = ComfoConnect(bridges[0].host, bridges[0].uuid, bridge_type=bridges[0].bridge_type, **kwargs)
46
+ comfoconnect = ComfoConnect(bridges[0].host, bridges[0].uuid, **kwargs)
47
47
  try:
48
48
  if connect:
49
49
  try:
@@ -82,14 +82,11 @@ async def run_register(args):
82
82
  """Register an app on the bridge."""
83
83
  async with connected(args, connect=False) as comfoconnect:
84
84
  try:
85
- registered = await comfoconnect.register(args.uuid, args.name, args.pin)
85
+ await comfoconnect.register(args.uuid, args.name, args.pin)
86
86
  except ComfoConnectNotAllowed as exc:
87
87
  raise CliError("Registration failed. Please check the PIN.") from exc
88
88
 
89
- if registered:
90
- print(f"UUID {args.uuid} is now registered.")
91
- else:
92
- print(f"UUID {args.uuid} is already registered.")
89
+ print(f"UUID {args.uuid} is registered.")
93
90
 
94
91
  await print_registered_apps(comfoconnect)
95
92
 
@@ -208,6 +205,7 @@ async def run_list_nodes(args):
208
205
  fields = {
209
206
  "name": info.name,
210
207
  "model": info.model,
208
+ "product variant": info.product_variant,
211
209
  "firmware": info.firmware,
212
210
  "hardware version": info.hardware_version,
213
211
  "serial number": info.serial_number,
@@ -14,7 +14,7 @@ from typing import Awaitable, Callable, Dict, Iterator, Optional
14
14
  from google.protobuf.message import DecodeError
15
15
  from google.protobuf.message import Message as ProtobufMessage
16
16
 
17
- from .const import NUMERIC_PROPERTY_TYPES, VENTILATION_UNIT_PRODUCT_IDS, GatewayType, ProductId
17
+ from .const import BRIDGE_PRODUCT_IDS, NUMERIC_PROPERTY_TYPES, VENTILATION_UNIT_PRODUCT_IDS, ProductId
18
18
  from .exceptions import (
19
19
  AioComfoConnectNotConnected,
20
20
  AioComfoConnectNotReachable,
@@ -81,6 +81,11 @@ class Node:
81
81
  """Returns True if this node is the ventilation unit that handles RMI commands."""
82
82
  return self.product_id in VENTILATION_UNIT_PRODUCT_IDS
83
83
 
84
+ @property
85
+ def is_bridge(self) -> bool:
86
+ """Returns True if this node is a bridge, like the ComfoConnect LAN C."""
87
+ return self.product_id in BRIDGE_PRODUCT_IDS
88
+
84
89
  @property
85
90
  def is_comfoclime(self) -> bool:
86
91
  """Returns True if this node is a ComfoClime heat pump module."""
@@ -96,12 +101,9 @@ class Bridge:
96
101
  self,
97
102
  host: str,
98
103
  uuid: str,
99
- bridge_type: int = 0,
100
104
  ):
101
105
  self.host: str = host
102
106
  self.uuid: str = uuid
103
- # One of GatewayType. Discovery reports it, and a ComfoConnect Pro also identifies itself when a session starts.
104
- self.bridge_type: int = bridge_type
105
107
  self._local_uuid: Optional[str] = None
106
108
 
107
109
  self._reader: Optional[StreamReader] = None
@@ -113,14 +115,16 @@ class Bridge:
113
115
 
114
116
  self._nodes: Dict[int, Node] = {}
115
117
  self._ventilation_node_found: Optional[asyncio.Event] = None
118
+ self.__node_callback_fn: Optional[Callable[[Node], None]] = None
116
119
 
117
120
  self.__sensor_callback_fn: Optional[Callable[[int, int], None]] = None
118
121
  self._sensor_pdo_types: Dict[int, int] = {}
119
122
  self.__alarm_callback_fn: Optional[Callable[[int, ProtobufMessage], None]] = None
120
123
 
121
124
  self._read_task = None
122
- # The time.monotonic() of the last message we received from the bridge.
125
+ # The time.monotonic() of the last message we received from the bridge, and of the last one we sent.
123
126
  self._last_received: float = 0
127
+ self._last_sent: float = 0
124
128
 
125
129
  def __repr__(self):
126
130
  return f"<Bridge {self.host}, UID={self.uuid}>"
@@ -133,31 +137,27 @@ class Bridge:
133
137
  """Set a callback to be called when an alarm is received."""
134
138
  self.__alarm_callback_fn = callback
135
139
 
140
+ def set_node_callback(self, callback: Optional[Callable[[Node], None]]):
141
+ """Set a callback to be called every time the bridge announces a node, also when it goes offline (see Node.is_offline).
142
+
143
+ The bridge announces the nodes when a session starts, often more than once, so a node can be announced again.
144
+ """
145
+ self.__node_callback_fn = callback
146
+
136
147
  async def connect(self, uuid: str):
137
148
  """Connect to the bridge and start reading messages."""
138
149
  await self._open_connection(uuid)
139
150
 
140
- async def register(self, uuid: str, name: str, pin: int) -> bool:
151
+ async def register(self, uuid: str, name: str, pin: int) -> None:
141
152
  """Register this app on the bridge and start a session.
142
153
 
143
- For LAN C bridges, attempts to start a session first; if the session
144
- succeeds the app is already registered and no re-registration occurs.
145
- For Pro bridges, registers directly to avoid a connection timeout that
146
- the Pro issues when the app is not yet registered.
147
-
148
- Returns True if the app was newly registered, False if it was already registered.
154
+ Like the official app, this registers directly: a bridge accepts an app that is registered already, as long as
155
+ the PIN is right. We don't start a session first to find out, since a ComfoConnect Pro doesn't answer that for an
156
+ app that isn't registered. ComfoConnectNotAllowed is raised for a wrong PIN.
149
157
  """
150
158
  await self._open_connection(uuid)
151
- if self.bridge_type != GatewayType.PRO:
152
- # LAN C: check whether we are already registered by starting a session.
153
- try:
154
- await self.cmd_start_session()
155
- return False # Already registered; session is now active.
156
- except ComfoConnectNotAllowed:
157
- pass # Not registered yet; fall through to register below.
158
159
  await self.cmd_register_app(uuid, name, pin)
159
160
  await self.cmd_start_session()
160
- return True
161
161
 
162
162
  async def _open_connection(self, uuid: str):
163
163
  """Open TCP connection to the bridge and start reading messages."""
@@ -182,7 +182,7 @@ class Bridge:
182
182
 
183
183
  self._reference = itertools.count(1)
184
184
  self._local_uuid = uuid
185
- self._last_received = time.monotonic()
185
+ self._last_received = self._last_sent = time.monotonic()
186
186
  self._pending = {}
187
187
 
188
188
  # The bridge announces its nodes at the start of every session, so forget what we knew.
@@ -265,13 +265,15 @@ class Bridge:
265
265
  if node.is_offline:
266
266
  _LOGGER.debug("Node %s went offline", node.node_id)
267
267
  self._nodes.pop(node.node_id, None)
268
- return
268
+ else:
269
+ _LOGGER.debug("Discovered node %s with product id %s in zone %s", node.node_id, node.product_id, node.zone_id)
270
+ self._nodes[node.node_id] = node
269
271
 
270
- _LOGGER.debug("Discovered node %s with product id %s in zone %s", node.node_id, node.product_id, node.zone_id)
271
- self._nodes[node.node_id] = node
272
+ if node.is_ventilation_unit and self._ventilation_node_found is not None:
273
+ self._ventilation_node_found.set()
272
274
 
273
- if node.is_ventilation_unit and self._ventilation_node_found is not None:
274
- self._ventilation_node_found.set()
275
+ if self.__node_callback_fn:
276
+ self.__node_callback_fn(node)
275
277
 
276
278
  @property
277
279
  def nodes(self) -> Dict[int, Node]:
@@ -284,6 +286,15 @@ class Bridge:
284
286
  candidates = [node.node_id for node in self._nodes.values() if node.is_ventilation_unit]
285
287
  return min(candidates) if candidates else None
286
288
 
289
+ @property
290
+ def bridge_node(self) -> Optional[Node]:
291
+ """The node of the bridge itself, or None when the bridge hasn't announced it (yet).
292
+
293
+ A ComfoAir Flex with a ComfoConnect LAN C would have two, and then it's the LAN C (see BRIDGE_PRODUCT_IDS).
294
+ """
295
+ candidates = [node for node in self._nodes.values() if node.is_bridge]
296
+ return min(candidates, key=lambda node: (BRIDGE_PRODUCT_IDS.index(node.product_id), node.node_id)) if candidates else None
297
+
287
298
  @property
288
299
  def comfoclime_node_id(self) -> Optional[int]:
289
300
  """The node id of the ComfoClime, or None when the bridge hasn't announced one."""
@@ -407,6 +418,7 @@ class Bridge:
407
418
  try:
408
419
  self._writer.write(message.encode())
409
420
  await self._writer.drain()
421
+ self._last_sent = time.monotonic()
410
422
  except (ConnectionError, OSError) as exc:
411
423
  _LOGGER.warning("Failed to send message: %s", exc)
412
424
  raise AioComfoConnectNotConnected("Connection lost while sending") from exc
@@ -470,16 +482,11 @@ class Bridge:
470
482
  """Starts the session on the device by logging in and optionally disconnecting an already existing session."""
471
483
  _LOGGER.debug("StartSessionRequest")
472
484
  # pylint: disable=no-member
473
- reply = await self._send(
485
+ return await self._send(
474
486
  zehnder_pb2.StartSessionRequest,
475
487
  zehnder_pb2.GatewayOperation.StartSessionRequestType,
476
488
  {"takeover": take_over},
477
489
  )
478
- # A ComfoConnect Pro sets the devicename of a successful session to "ccpro", a LAN C leaves it empty. This also
479
- # tells us the type of a bridge that was connected to by IP address, without discovery.
480
- if getattr(reply, "devicename", None) == "ccpro":
481
- self.bridge_type = GatewayType.PRO
482
- return reply
483
490
 
484
491
  def cmd_close_session(self) -> Awaitable[Message]:
485
492
  """Stops the current session."""
@@ -10,7 +10,7 @@ from dataclasses import dataclass
10
10
  from typing import Any, Awaitable, Callable, Dict, List, Literal, Optional
11
11
 
12
12
  from aiocomfoconnect import Bridge
13
- from aiocomfoconnect.bridge import Message
13
+ from aiocomfoconnect.bridge import Message, Node
14
14
  from aiocomfoconnect.const import (
15
15
  ERRORS,
16
16
  ERRORS_140,
@@ -54,6 +54,7 @@ from aiocomfoconnect.properties import (
54
54
  PROPERTY_HARDWARE_VERSION,
55
55
  PROPERTY_MODEL,
56
56
  PROPERTY_NAME,
57
+ PROPERTY_PRODUCT_VARIANT,
57
58
  PROPERTY_SERIAL_NUMBER,
58
59
  Property,
59
60
  PropertyConstraints,
@@ -96,6 +97,11 @@ def _decode_value(property_type: Optional[int], raw: bytes) -> Any:
96
97
  return raw
97
98
 
98
99
 
100
+ def _sensor_value(sensor: Sensor, raw: int) -> Any:
101
+ """Convert the raw value of a sensor."""
102
+ return sensor.value_fn(raw) if sensor.value_fn else round(raw, 2)
103
+
104
+
99
105
  def _property_value(prop: Property, value: Any) -> Any:
100
106
  """Return the option or the scaled value of a decoded property value."""
101
107
  if prop.options is None:
@@ -115,6 +121,7 @@ class NodeInfo:
115
121
  serial_number: Optional[str]
116
122
  firmware: Optional[str]
117
123
  hardware_version: Optional[int]
124
+ product_variant: Optional[int] # Which model of the product, e.g. 3 is a Q600 for a ComfoAir Q (see PROTOCOL-RMI.md).
118
125
 
119
126
 
120
127
  @dataclass
@@ -139,21 +146,26 @@ class ComfoConnect(Bridge):
139
146
  alarm_callback=None,
140
147
  sensor_delay=5,
141
148
  connect_timeout=30,
142
- bridge_type: int = 0,
143
149
  heartbeat_interval: Optional[float] = HEARTBEAT_INTERVAL,
144
150
  connection_state_callback: Optional[Callable[[str], None]] = None,
151
+ node_callback: Optional[Callable[[Node], None]] = None,
145
152
  ):
146
153
  """Initialize the ComfoConnect class.
147
154
 
148
- When we received nothing for heartbeat_interval seconds, we ask the bridge for its time, and reconnect when it
149
- doesn't answer. This detects a bridge that stopped answering without closing the connection. None disables it.
155
+ When we sent or received nothing for heartbeat_interval seconds, we ask the bridge for its time, and reconnect when
156
+ it doesn't answer. This keeps the bridge from closing a connection on which we send nothing, and detects a bridge
157
+ that stopped answering without closing the connection. None disables it.
150
158
 
151
159
  The connection_state_callback is called with a ConnectionState when the state of the session changes.
160
+
161
+ The node_callback is called with a Node every time the bridge announces one: at the start of every session, already
162
+ while connect() runs and often more than once, and when a node joins or goes offline (see Node.is_offline).
152
163
  """
153
- super().__init__(host, uuid, bridge_type)
164
+ super().__init__(host, uuid)
154
165
 
155
166
  self.set_sensor_callback(self._sensor_callback) # Set the callback to our _sensor_callback method, so we can proces the callbacks.
156
167
  self.set_alarm_callback(self._alarm_callback) # Set the callback to our _alarm_callback method, so we can proces the callbacks.
168
+ self.set_node_callback(node_callback)
157
169
  self.sensor_delay = sensor_delay
158
170
  self.connect_timeout = connect_timeout
159
171
  self.heartbeat_interval = heartbeat_interval
@@ -285,10 +297,15 @@ class ComfoConnect(Bridge):
285
297
  _LOGGER.info("Reconnect loop stopped")
286
298
 
287
299
  async def _wait_for_disconnect(self):
288
- """Wait until the connection is lost, or until the bridge doesn't answer the heartbeat."""
300
+ """Wait until the connection is lost, or until the bridge doesn't answer the heartbeat.
301
+
302
+ The heartbeat asks the bridge for its time when we sent or received nothing for heartbeat_interval seconds. The
303
+ bridge closes a connection on which we sent nothing for about 90 seconds, also while it pushes sensor values, and a
304
+ bridge that stopped answering doesn't send anything.
305
+ """
289
306
  # The read task ends when the connection is lost. It has already logged why.
290
307
  while not self._read_task.done():
291
- idle = time.monotonic() - self._last_received
308
+ idle = time.monotonic() - min(self._last_sent, self._last_received)
292
309
  if self.heartbeat_interval is None or idle < self.heartbeat_interval:
293
310
  timeout = None if self.heartbeat_interval is None else self.heartbeat_interval - idle
294
311
  await asyncio.wait([self._read_task], timeout=timeout)
@@ -302,6 +319,18 @@ class ComfoConnect(Bridge):
302
319
  _LOGGER.warning("The bridge did not answer the heartbeat")
303
320
  return
304
321
 
322
+ @property
323
+ def sensor_values(self) -> Dict[int, Any]:
324
+ """The latest value of every subscribed sensor, by sensor id, converted like for the sensor callback.
325
+
326
+ A value is None until the bridge sent one. Right after subscribing, it can be the invalid value that the bridge
327
+ sends first, which the sensor callback holds back (see sensor_delay).
328
+ """
329
+ return {
330
+ sensor_id: None if self._sensors_values.get(sensor_id) is None else _sensor_value(sensor, self._sensors_values[sensor_id])
331
+ for sensor_id, sensor in self._sensors.items()
332
+ }
333
+
305
334
  @property
306
335
  def connection_state(self) -> str:
307
336
  """The state of the session, one of ConnectionState. Unlike is_connected(), this is only CONNECTED once the session is up."""
@@ -458,31 +487,36 @@ class ComfoConnect(Bridge):
458
487
  return values
459
488
 
460
489
  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.
490
+ """Get the NodeInfo of a node (the ventilation unit by default). A property that the node doesn't have is None.
462
491
 
463
- Raises ComfoConnectRmiError when none of the properties can be read, e.g. for a node that doesn't exist.
492
+ The properties are read one by one: a node fails a request for several as a whole when it lacks one of them, and
493
+ a ComfoConnect Pro answers it with fewer values than asked. Raises ComfoConnectRmiError when none of the
494
+ properties can be read, e.g. for a node that doesn't exist.
464
495
  """
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
496
+ props = [PROPERTY_NAME, PROPERTY_MODEL, PROPERTY_ARTICLE, PROPERTY_SERIAL_NUMBER, PROPERTY_FIRMWARE_VERSION, PROPERTY_HARDWARE_VERSION, PROPERTY_PRODUCT_VARIANT]
497
+ errors: List[ComfoConnectRmiError] = []
470
498
 
471
- # A request fails as a whole when the node lacks one of the properties, so read them one by one.
472
499
  async def get_or_none(prop: Property) -> Any:
473
500
  try:
474
501
  return await self.get_property(prop, node_id)
475
- except ComfoConnectRmiError:
502
+ except ComfoConnectRmiError as exc:
503
+ errors.append(exc)
476
504
  return None
477
505
 
478
506
  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.
507
+ if len(errors) == len(props):
508
+ raise errors[0]
481
509
  return NodeInfo(*values)
482
510
 
483
511
  async def get_single_property(self, unit: int, subunit: int, property_id: int, property_type: int = None, node_id: Optional[int] = None) -> Any:
484
- """Get a property and convert to the right type."""
512
+ """Get a property and convert to the right type.
513
+
514
+ Raises ComfoConnectRmiError when the node doesn't have the property: it answers with an RMI error, or, like the
515
+ node of a ComfoConnect Pro, with an empty message.
516
+ """
485
517
  result = await self.cmd_rmi_request(bytes([0x01, unit, subunit, 0x10, property_id]), node_id=node_id)
518
+ if not result.message:
519
+ raise ComfoConnectRmiError(f"The node sent no value for property {property_id}")
486
520
  return _decode_value(property_type, result.message)
487
521
 
488
522
  async def get_property_constraints(self, prop: Property, node_id: Optional[int] = None) -> PropertyConstraints:
@@ -520,9 +554,6 @@ class ComfoConnect(Bridge):
520
554
 
521
555
  def _sensor_callback(self, sensor_id, sensor_value):
522
556
  """Callback function for sensor updates."""
523
- if self._sensor_callback_fn is None:
524
- return
525
-
526
557
  sensor = self._sensors.get(sensor_id)
527
558
  if sensor is None:
528
559
  # After a quick reconnect, the bridge can still push the sensors of our previous session before we subscribe again.
@@ -540,11 +571,8 @@ class ComfoConnect(Bridge):
540
571
  _LOGGER.debug("Got a valid value for sensor %s, releasing the hold", sensor_id)
541
572
  self._sensor_holds.pop(sensor_id).cancel()
542
573
 
543
- if sensor.value_fn:
544
- val = sensor.value_fn(sensor_value)
545
- else:
546
- val = round(sensor_value, 2)
547
- self._sensor_callback_fn(sensor, val)
574
+ if self._sensor_callback_fn is not None:
575
+ self._sensor_callback_fn(sensor, _sensor_value(sensor, sensor_value))
548
576
 
549
577
  def _alarm_callback(self, node_id, alarm):
550
578
  """Callback function for alarm updates."""
@@ -30,16 +30,12 @@ class ProductId:
30
30
  # nodes on the bus (gateway, connection board, sensors, ...) will reply with RMI_ERROR.
31
31
  VENTILATION_UNIT_PRODUCT_IDS = (ProductId.COMFOAIRQ, ProductId.COMFOAIRFLEX)
32
32
 
33
-
34
- # PDO Types
35
- class GatewayType:
36
- """Defines the type of a bridge, with the values of the GatewayType in the discovery response."""
37
-
38
- LANC = 0 # ComfoConnect LAN C
39
- SEASON = 1 # The built-in WiFi module of a ComfoAir Flex
40
- PRO = 2 # ComfoConnect Pro
33
+ # The product ids of the bridge itself on the bus, in order of preference: a ComfoConnect Pro, a ComfoConnect LAN C,
34
+ # and the WiFi connection module built into a ComfoAir Flex. A Flex with a LAN C would have both of the last two.
35
+ BRIDGE_PRODUCT_IDS = (ProductId.COMFOCONNECTPRO, ProductId.ZEHNDERGATEWAY, ProductId.COMFOAIRFLEXCONNECTIONBOARD)
41
36
 
42
37
 
38
+ # PDO Types
43
39
  class ConnectionState:
44
40
  """The state of the session with the bridge, as reported to the connection state callback."""
45
41
 
@@ -55,12 +51,14 @@ class PdoType:
55
51
  TYPE_CN_UINT8 = 0x01
56
52
  TYPE_CN_UINT16 = 0x02
57
53
  TYPE_CN_UINT32 = 0x03
54
+ TYPE_CN_UINT64 = 0x04
58
55
  TYPE_CN_INT8 = 0x05
59
56
  TYPE_CN_INT16 = 0x06
57
+ TYPE_CN_INT32 = 0x07
60
58
  TYPE_CN_INT64 = 0x08
61
59
  TYPE_CN_STRING = 0x09
62
- TYPE_CN_TIME = 0x10
63
- TYPE_CN_VERSION = 0x11
60
+ TYPE_CN_TIME = 0x0A
61
+ TYPE_CN_VERSION = 0x0B
64
62
 
65
63
 
66
64
  # The size in bytes and the signedness of the numeric PDO and property types.
@@ -68,8 +66,10 @@ NUMERIC_PROPERTY_TYPES = {
68
66
  PdoType.TYPE_CN_UINT8: (1, False),
69
67
  PdoType.TYPE_CN_UINT16: (2, False),
70
68
  PdoType.TYPE_CN_UINT32: (4, False),
69
+ PdoType.TYPE_CN_UINT64: (8, False),
71
70
  PdoType.TYPE_CN_INT8: (1, True),
72
71
  PdoType.TYPE_CN_INT16: (2, True),
72
+ PdoType.TYPE_CN_INT32: (4, True),
73
73
  PdoType.TYPE_CN_INT64: (8, True),
74
74
  }
75
75
 
@@ -77,7 +77,6 @@ class BridgeDiscoveryProtocol(asyncio.DatagramProtocol):
77
77
  Bridge(
78
78
  host=parser.searchGatewayResponse.ipaddress,
79
79
  uuid=uuid,
80
- bridge_type=parser.searchGatewayResponse.type,
81
80
  )
82
81
  )
83
82
 
@@ -49,6 +49,7 @@ class PropertyConstraints:
49
49
  step: int | float
50
50
 
51
51
 
52
+ PROPERTY_PRODUCT_VARIANT = Property(UNIT_NODE, 0x01, 0x03, PdoType.TYPE_CN_UINT8) # E.g. 1=Q350, 2=Q450, 3=Q600 on a ComfoAir Q.
52
53
  PROPERTY_SERIAL_NUMBER = Property(UNIT_NODE, 0x01, 0x04, PdoType.TYPE_CN_STRING)
53
54
  PROPERTY_HARDWARE_VERSION = Property(UNIT_NODE, 0x01, 0x05, PdoType.TYPE_CN_UINT8)
54
55
  PROPERTY_FIRMWARE_VERSION = Property(UNIT_NODE, 0x01, 0x06, PdoType.TYPE_CN_VERSION) # A UINT32, decoded with version_decode().
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "aiocomfoconnect"
3
- version = "0.4.3"
3
+ version = "0.4.5"
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