Skip to content

Commit d599e7a

Browse files
authored
Merge pull request #237 from plugwise/async-sq-fixes
Various fixes for SQ-reports
2 parents 27212cc + b8dc581 commit d599e7a

File tree

15 files changed

+97
-91
lines changed

15 files changed

+97
-91
lines changed

plugwise_usb/connection/__init__.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,8 @@ async def _handle_stick_event(self, event: StickEvent) -> None:
156156
if not self._queue.is_running:
157157
self._queue.start(self._manager)
158158
await self.initialize_stick()
159-
elif event == StickEvent.DISCONNECTED:
160-
if self._queue.is_running:
161-
await self._queue.stop()
159+
elif event == StickEvent.DISCONNECTED and self._queue.is_running:
160+
await self._queue.stop()
162161

163162
async def initialize_stick(self) -> None:
164163
"""Initialize connection to the USB-stick."""

plugwise_usb/messages/requests.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -283,27 +283,34 @@ async def process_node_response(self, response: PlugwiseResponse) -> bool:
283283

284284
async def _process_stick_response(self, stick_response: StickResponse) -> None:
285285
"""Process incoming stick response."""
286-
if self._response_future.done():
286+
if (
287+
self._response_future.done()
288+
or self._seq_id is None
289+
or self._seq_id != stick_response.seq_id
290+
):
287291
return
288-
if self._seq_id is None or self._seq_id != stick_response.seq_id:
292+
293+
if stick_response.ack_id == StickResponseType.ACCEPT:
289294
return
295+
290296
if stick_response.ack_id == StickResponseType.TIMEOUT:
291297
self._response_timeout_expired(stick_timeout=True)
292-
elif stick_response.ack_id == StickResponseType.FAILED:
298+
return
299+
300+
if stick_response.ack_id == StickResponseType.FAILED:
293301
self._unsubscribe_from_node()
294302
self._seq_id = None
295303
self._response_future.set_exception(
296304
NodeError(f"Stick failed request {self._seq_id}")
297305
)
298-
elif stick_response.ack_id == StickResponseType.ACCEPT:
299-
pass
300-
else:
301-
_LOGGER.debug(
302-
"Unknown StickResponseType %s at %s for request %s",
303-
str(stick_response.ack_id),
304-
stick_response,
305-
self,
306-
)
306+
return
307+
308+
_LOGGER.debug(
309+
"Unknown StickResponseType %s at %s for request %s",
310+
str(stick_response.ack_id),
311+
stick_response,
312+
self,
313+
)
307314

308315
async def _send_request(self, suppress_node_errors=False) -> PlugwiseResponse | None:
309316
"""Send request."""
@@ -1287,11 +1294,11 @@ def __init__(
12871294
self,
12881295
send_fn: Callable[[PlugwiseRequest, bool], Awaitable[PlugwiseResponse | None]],
12891296
mac: bytes,
1290-
taskId: int,
1297+
task_id: int,
12911298
) -> None:
12921299
"""Initialize NodeClearGroupMacRequest message object."""
12931300
super().__init__(send_fn, mac)
1294-
self._args.append(Int(taskId, length=2))
1301+
self._args.append(Int(task_id, length=2))
12951302

12961303

12971304
class CircleSetScheduleValueRequest(PlugwiseRequest):

plugwise_usb/messages/responses.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -590,25 +590,17 @@ def __init__(self, protocol_version: str = "2.0") -> None:
590590
"""Initialize NodeInfoResponse message object."""
591591
super().__init__(b"0024")
592592

593+
self.datetime = DateTime()
593594
self._logaddress_pointer = LogAddr(0, length=8)
594-
if protocol_version == "1.0":
595-
# FIXME: Define "absoluteHour" variable
596-
self.datetime = DateTime()
595+
if protocol_version in ("1.0", "2.0"):
596+
# FIXME 1.0: Define "absoluteHour" variable
597597
self._relay_state = Int(0, length=2)
598598
self._params += [
599599
self.datetime,
600600
self._logaddress_pointer,
601601
self._relay_state,
602602
]
603-
elif protocol_version == "2.0":
604-
self.datetime = DateTime()
605-
self._relay_state = Int(0, length=2)
606-
self._params += [
607-
self.datetime,
608-
self._logaddress_pointer,
609-
self._relay_state,
610-
]
611-
elif protocol_version == "2.3":
603+
if protocol_version == "2.3":
612604
# FIXME: Define "State_mask" variable
613605
self.state_mask = Int(0, length=2)
614606
self._params += [

plugwise_usb/network/__init__.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -208,30 +208,34 @@ async def _handle_stick_event(self, event: StickEvent) -> None:
208208
await gather(*[node.disconnect() for node in self._nodes.values()])
209209
self._is_running = False
210210

211-
async def node_awake_message(self, response: PlugwiseResponse) -> bool:
211+
async def node_awake_message(self, response: PlugwiseResponse) -> None:
212212
"""Handle NodeAwakeResponse message."""
213213
if not isinstance(response, NodeAwakeResponse):
214214
raise MessageError(
215215
f"Invalid response message type ({response.__class__.__name__}) received, expected NodeAwakeResponse"
216216
)
217+
217218
mac = response.mac_decoded
218219
if self._awake_discovery.get(mac) is None:
219220
self._awake_discovery[mac] = response.timestamp - timedelta(seconds=15)
221+
220222
if mac in self._nodes:
221223
if self._awake_discovery[mac] < (
222224
response.timestamp - timedelta(seconds=10)
223225
):
224226
await self._notify_node_event_subscribers(NodeEvent.AWAKE, mac)
225227
self._awake_discovery[mac] = response.timestamp
226-
return True
228+
return
229+
227230
if (address := self._register.network_address(mac)) is None:
228231
if self._register.scan_completed:
229-
return True
232+
return
233+
230234
_LOGGER.debug(
231235
"Skip node awake message for %s because network registry address is unknown",
232236
mac,
233237
)
234-
return True
238+
return
235239

236240
if self._nodes.get(mac) is None:
237241
if (
@@ -243,7 +247,6 @@ async def node_awake_message(self, response: PlugwiseResponse) -> bool:
243247
)
244248
else:
245249
_LOGGER.debug("duplicate maintenance awake discovery for %s", mac)
246-
return True
247250

248251
async def node_join_available_message(self, response: PlugwiseResponse) -> bool:
249252
"""Handle NodeJoinAvailableResponse messages."""
@@ -275,11 +278,8 @@ async def node_rejoin_message(self, response: PlugwiseResponse) -> bool:
275278
raise NodeError(f"Failed to obtain address for node {mac}")
276279

277280
if self._nodes.get(mac) is None:
278-
if self._discover_sed_tasks.get(mac) is None:
279-
self._discover_sed_tasks[mac] = create_task(
280-
self._discover_battery_powered_node(address, mac)
281-
)
282-
elif self._discover_sed_tasks[mac].done():
281+
task = self._discover_sed_tasks.get(mac)
282+
if task is None or task.done():
283283
self._discover_sed_tasks[mac] = create_task(
284284
self._discover_battery_powered_node(address, mac)
285285
)

plugwise_usb/network/registry.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@ async def retrieve_network_registration(
145145
return await self.retrieve_network_registration(address, retry=False)
146146
return None
147147
address = response.network_address
148-
mac_of_node = response.registered_mac
149148
if (mac_of_node := response.registered_mac) == "FFFFFFFFFFFFFFFF":
150149
mac_of_node = ""
151150
return (address, mac_of_node)

plugwise_usb/nodes/celsius.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,22 @@ async def load(self) -> bool:
2727
"""Load and activate node features."""
2828
if self._loaded:
2929
return True
30-
self._node_info.is_battery_powered = True
3130

31+
self._node_info.is_battery_powered = True
32+
mac = self._node_info.mac
3233
if self._cache_enabled:
33-
_LOGGER.debug(
34-
"Load Celsius node %s from cache", self._node_info.mac
35-
)
36-
if await self._load_from_cache():
37-
pass
34+
_LOGGER.debug("Loading Celsius node %s from cache", mac)
35+
if not await self._load_from_cache():
36+
_LOGGER.debug("Loading Celsius node %s from cache failed", mac)
3837

3938
self._loaded = True
4039
self._setup_protocol(
4140
CELSIUS_FIRMWARE_SUPPORT,
4241
(NodeFeature.INFO, NodeFeature.TEMPERATURE),
4342
)
4443
if await self.initialize():
45-
await self._loaded_callback(NodeEvent.LOADED, self.mac)
44+
await self._loaded_callback(NodeEvent.LOADED, mac)
4645
return True
47-
_LOGGER.debug("Load of Celsius node %s failed", self._node_info.mac)
46+
47+
_LOGGER.debug("Loading of Celsius node %s failed", mac)
4848
return False

plugwise_usb/nodes/circle.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
EnergyCalibrationRequest,
3939
NodeInfoRequest,
4040
)
41-
from ..messages.responses import NodeInfoResponse, NodeResponse, NodeResponseType
41+
from ..messages.responses import NodeInfoResponse, NodeResponseType
4242
from .helpers import EnergyCalibration, raise_not_loaded
4343
from .helpers.counter import EnergyCounters
4444
from .helpers.firmware import CIRCLE_FIRMWARE_SUPPORT
@@ -532,7 +532,6 @@ async def energy_log_update(self, address: int | None) -> bool:
532532

533533
async def _energy_log_records_load_from_cache(self) -> bool:
534534
"""Load energy_log_record from cache."""
535-
cache_data = self._get_cache(CACHE_ENERGY_COLLECTION)
536535
if (cache_data := self._get_cache(CACHE_ENERGY_COLLECTION)) is None:
537536
_LOGGER.warning(
538537
"Failed to restore energy log records from cache for node %s", self.name
@@ -733,7 +732,6 @@ async def clock_synchronize(self) -> bool:
733732
datetime.now(tz=UTC),
734733
self._node_protocols.max,
735734
)
736-
node_response: NodeResponse | None = await set_clock_request.send()
737735
if (node_response := await set_clock_request.send()) is None:
738736
_LOGGER.warning(
739737
"Failed to (re)set the internal clock of %s",
@@ -849,12 +847,14 @@ async def initialize(self) -> bool:
849847
)
850848
self._initialized = False
851849
return False
850+
852851
if not self._calibration and not await self.calibration_update():
853852
_LOGGER.debug(
854853
"Failed to initialized node %s, no calibration", self._mac_in_str
855854
)
856855
self._initialized = False
857856
return False
857+
858858
if (
859859
self.skip_update(self._node_info, 30)
860860
and await self.node_info_update() is None
@@ -869,7 +869,9 @@ async def initialize(self) -> bool:
869869
)
870870
self._initialized = False
871871
return False
872-
return await super().initialize()
872+
873+
await super().initialize()
874+
return True
873875

874876
async def node_info_update(
875877
self, node_info: NodeInfoResponse | None = None
@@ -1083,15 +1085,14 @@ def _correct_power_pulses(self, pulses: int, offset: int) -> float:
10831085
async def get_state(self, features: tuple[NodeFeature]) -> dict[NodeFeature, Any]:
10841086
"""Update latest state for given feature."""
10851087
states: dict[NodeFeature, Any] = {}
1086-
if not self._available:
1087-
if not await self.is_online():
1088-
_LOGGER.debug(
1089-
"Node %s did not respond, unable to update state", self._mac_in_str
1090-
)
1091-
for feature in features:
1092-
states[feature] = None
1093-
states[NodeFeature.AVAILABLE] = self.available_state
1094-
return states
1088+
if not self._available and not await self.is_online():
1089+
_LOGGER.debug(
1090+
"Node %s did not respond, unable to update state", self._mac_in_str
1091+
)
1092+
for feature in features:
1093+
states[feature] = None
1094+
states[NodeFeature.AVAILABLE] = self.available_state
1095+
return states
10951096

10961097
for feature in features:
10971098
if feature not in self._features:

plugwise_usb/nodes/helpers/counter.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,8 @@ def add_pulse_log( # pylint: disable=too-many-arguments
8282
"""Add pulse log."""
8383
if self._pulse_collection.add_log(
8484
address, slot, timestamp, pulses, import_only
85-
):
86-
if not import_only:
87-
self.update()
85+
) and not import_only:
86+
self.update()
8887

8988
def get_pulse_logs(self) -> dict[int, dict[int, PulseLogRecord]]:
9089
"""Return currently collected pulse logs."""

plugwise_usb/nodes/helpers/pulses.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -935,8 +935,6 @@ def _missing_addresses_before(
935935
):
936936
# Use consumption interval
937937
calc_interval_cons = timedelta(minutes=self._log_interval_consumption)
938-
if self._log_interval_consumption == 0:
939-
pass
940938

941939
if not self._log_production:
942940
expected_timestamp = (

plugwise_usb/nodes/node.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -337,14 +337,14 @@ def _setup_protocol(
337337
for feature in node_features:
338338
if (
339339
required_version := FEATURE_SUPPORTED_AT_FIRMWARE.get(feature)
340-
) is not None:
341-
if (
342-
self._node_protocols.min
343-
<= required_version
344-
<= self._node_protocols.max
345-
and feature not in self._features
346-
):
347-
self._features += (feature,)
340+
) is not None and (
341+
self._node_protocols.min
342+
<= required_version
343+
<= self._node_protocols.max
344+
and feature not in self._features
345+
):
346+
self._features += (feature,)
347+
348348
self._node_info.features = self._features
349349

350350
async def reconnect(self) -> None:
@@ -398,15 +398,15 @@ async def _load_from_cache(self) -> bool:
398398
return False
399399
return True
400400

401-
async def initialize(self) -> bool:
401+
async def initialize(self) -> None:
402402
"""Initialize node configuration."""
403403
if self._initialized:
404-
return True
404+
return
405+
405406
self._initialization_delay_expired = datetime.now(tz=UTC) + timedelta(
406407
minutes=SUPPRESS_INITIALIZATION_WARNINGS
407408
)
408409
self._initialized = True
409-
return True
410410

411411
async def _available_update_state(
412412
self, available: bool, timestamp: datetime | None = None

0 commit comments

Comments
 (0)