Skip to content

Commit c50a869

Browse files
authored
Merge pull request #239 from plugwise/more-sq-fixes
More SonarCloud fixes
2 parents d599e7a + 451d652 commit c50a869

File tree

10 files changed

+81
-62
lines changed

10 files changed

+81
-62
lines changed

plugwise_usb/messages/requests.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def start_response_timeout(self) -> None:
202202

203203
def stop_response_timeout(self) -> None:
204204
"""Stop timeout for node response."""
205-
self._waiting_for_response = True
205+
self._waiting_for_response = False
206206
if self._response_timeout is not None:
207207
self._response_timeout.cancel()
208208

@@ -1231,13 +1231,13 @@ def __init__(
12311231
async def send(self) -> NodeResponse | None:
12321232
"""Send request."""
12331233
result = await self._send_request()
1234-
_LOGGER.warning("NodeSleepConfigRequest result: %s", result)
1234+
_LOGGER.debug("NodeSleepConfigRequest result: %s", result)
12351235
if isinstance(result, NodeResponse):
12361236
return result
12371237
if result is None:
12381238
return None
12391239
raise MessageError(
1240-
f"Invalid response message. Received {result.__class__.__name__}, expected NodeAckResponse"
1240+
f"Invalid response message. Received {result.__class__.__name__}, expected NodeResponse"
12411241
)
12421242

12431243
def __repr__(self) -> str:

plugwise_usb/network/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ async def node_join_available_message(self, response: PlugwiseResponse) -> bool:
263263
raise NodeError(f"Unable to add Node ({mac}): {exc}") from exc
264264
if result:
265265
return True
266-
266+
267267
return False
268268

269269
async def node_rejoin_message(self, response: PlugwiseResponse) -> bool:
@@ -286,7 +286,7 @@ async def node_rejoin_message(self, response: PlugwiseResponse) -> bool:
286286
else:
287287
_LOGGER.debug("duplicate awake discovery for %s", mac)
288288
return True
289-
289+
290290
return False
291291

292292
def _unsubscribe_to_protocol_events(self) -> None:
@@ -299,7 +299,7 @@ def _unsubscribe_to_protocol_events(self) -> None:
299299
self._unsubscribe_stick_event = None
300300

301301
# endregion
302-
302+
303303
# region - Coordinator
304304
async def discover_network_coordinator(self, load: bool = False) -> bool:
305305
"""Discover the Zigbee network coordinator (Circle+/Stealth+)."""

plugwise_usb/network/registry.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,10 @@ async def load_registry_from_cache(self) -> None:
128128
"Unable to restore network registry because cache is not initialized"
129129
)
130130
return
131+
131132
if self._cache_restored:
132133
return
134+
133135
for address, registration in self._network_cache.registrations.items():
134136
mac, node_type = registration
135137
if self._registry.get(address) is None:
@@ -259,12 +261,12 @@ async def register_node(self, mac: str) -> None:
259261
try:
260262
await request.send()
261263
except StickError as exc:
262-
raise NodeError("{exc}") from exc
264+
raise NodeError(f"{exc}") from exc
263265

264266
async def unregister_node(self, mac: str) -> None:
265267
"""Unregister node from current Plugwise network."""
266268
if not validate_mac(mac):
267-
raise NodeError(f"MAC '{mac}' invalid")
269+
raise NodeError(f"MAC {mac} invalid")
268270

269271
mac_registered = False
270272
for registration in self._registry.values():

plugwise_usb/nodes/circle.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -822,14 +822,14 @@ async def _load_from_cache(self) -> bool:
822822
# Relay
823823
if await self._relay_load_from_cache():
824824
_LOGGER.debug(
825-
"Node %s failed to load relay state from cache",
825+
"Node %s successfully loaded relay state from cache",
826826
self._mac_in_str,
827827
)
828828
# Relay init config if feature is enabled
829829
if NodeFeature.RELAY_INIT in self._features:
830830
if await self._relay_init_load_from_cache():
831831
_LOGGER.debug(
832-
"Node %s failed to load relay_init state from cache",
832+
"Node %s successfully loaded relay_init state from cache",
833833
self._mac_in_str,
834834
)
835835
return True

plugwise_usb/nodes/helpers/pulses.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ def update_pulse_counter(
271271
self, pulses_consumed: int, pulses_produced: int, timestamp: datetime
272272
) -> None:
273273
"""Update pulse counter.
274-
274+
275275
Both device consumption and production counters reset after the beginning of a new hour.
276276
"""
277277
self._cons_pulsecounter_reset = False
@@ -287,7 +287,7 @@ def update_pulse_counter(
287287

288288
if (
289289
self._pulses_production is not None
290-
and self._pulses_production < pulses_produced
290+
and self._pulses_production < pulses_produced
291291
):
292292
self._prod_pulsecounter_reset = True
293293
_LOGGER.debug("update_pulse_counter | production pulses reset")
@@ -313,9 +313,9 @@ def update_pulse_counter(
313313

314314
def _update_rollover(self) -> None:
315315
"""Update rollover states.
316-
316+
317317
When the last found timestamp is outside the interval `_last_log_timestamp`
318-
to `_next_log_timestamp` the pulses should not be counted as part of the
318+
to `_next_log_timestamp` the pulses should not be counted as part of the
319319
ongoing collection-interval.
320320
"""
321321
if self._log_addresses_missing is not None and self._log_addresses_missing:
@@ -341,7 +341,7 @@ def _detect_rollover(
341341
next_log_timestamp: datetime | None,
342342
is_consumption=True,
343343
) -> bool:
344-
"""Helper function for _update_rollover()."""
344+
"""Detect rollover based on timestamp comparisons."""
345345

346346
if (
347347
self._pulses_timestamp is not None
@@ -824,7 +824,7 @@ def _logs_missing(self, from_timestamp: datetime) -> list[int] | None:
824824
"The Circle %s does not overwrite old logged data, please reset the Circle's energy-logs via Source",
825825
self._mac,
826826
)
827-
return
827+
return None
828828

829829
if (
830830
last_address == first_address

plugwise_usb/nodes/node.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@ async def _available_update_state(
416416
if (
417417
self._last_seen is not None
418418
and timestamp is not None
419-
and (timestamp - self._last_seen).seconds > 5
419+
and int((timestamp - self._last_seen).total_seconds()) > 5
420420

421421
):
422422
self._last_seen = timestamp
@@ -618,15 +618,22 @@ def _get_cache_as_datetime(self, setting: str) -> datetime | None:
618618
if (timestamp_str := self._get_cache(setting)) is not None:
619619
data = timestamp_str.split("-")
620620
if len(data) == 6:
621-
return datetime(
622-
year=int(data[0]),
623-
month=int(data[1]),
624-
day=int(data[2]),
625-
hour=int(data[3]),
626-
minute=int(data[4]),
627-
second=int(data[5]),
628-
tzinfo=UTC,
629-
)
621+
try:
622+
return datetime(
623+
year=int(data[0]),
624+
month=int(data[1]),
625+
day=int(data[2]),
626+
hour=int(data[3]),
627+
minute=int(data[4]),
628+
second=int(data[5]),
629+
tzinfo=UTC,
630+
)
631+
except ValueError:
632+
_LOGGER.warning(
633+
"Invalid datetime format in cache for setting %s: %s",
634+
setting,
635+
timestamp_str,
636+
)
630637
return None
631638

632639
def _set_cache(self, setting: str, value: Any) -> None:

plugwise_usb/nodes/scan.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@
4747
# Light override
4848
SCAN_DEFAULT_DAYLIGHT_MODE: Final = False
4949

50+
# Sensitivity values for motion sensor configuration
51+
SENSITIVITY_HIGH_VALUE = 20 # 0x14
52+
SENSITIVITY_MEDIUM_VALUE = 30 # 0x1E
53+
SENSITIVITY_OFF_VALUE = 255 # 0xFF
54+
5055
# endregion
5156

5257

@@ -169,7 +174,7 @@ def _motion_from_cache(self) -> bool:
169174
if (
170175
cached_motion_state == "True"
171176
and (motion_timestamp := self._motion_timestamp_from_cache()) is not None
172-
and (datetime.now(tz=UTC) - motion_timestamp).seconds < self._reset_timer_from_cache() * 60
177+
and int((datetime.now(tz=UTC) - motion_timestamp).total_seconds()) < self._reset_timer_from_cache() * 60
173178
):
174179
return True
175180
return False
@@ -378,7 +383,7 @@ async def _motion_state_update(
378383
self._set_cache(CACHE_MOTION_STATE, "False")
379384
if self._motion_state.state is None or self._motion_state.state:
380385
if self._reset_timer_motion_on is not None:
381-
reset_timer = (timestamp - self._reset_timer_motion_on).seconds
386+
reset_timer = int((timestamp - self._reset_timer_motion_on).total_seconds())
382387
if self._motion_config.reset_timer is None:
383388
self._motion_config = replace(
384389
self._motion_config,
@@ -464,12 +469,13 @@ async def scan_configure(
464469
daylight_mode: bool,
465470
) -> bool:
466471
"""Configure Scan device settings. Returns True if successful."""
467-
# Default to medium:
468-
sensitivity_value = 30 # b'1E'
469-
if sensitivity_level == MotionSensitivity.HIGH:
470-
sensitivity_value = 20 # b'14'
471-
if sensitivity_level == MotionSensitivity.OFF:
472-
sensitivity_value = 255 # b'FF'
472+
sensitivity_map = {
473+
MotionSensitivity.HIGH: SENSITIVITY_HIGH_VALUE,
474+
MotionSensitivity.MEDIUM: SENSITIVITY_MEDIUM_VALUE,
475+
MotionSensitivity.OFF: SENSITIVITY_OFF_VALUE,
476+
}
477+
# Default to medium
478+
sensitivity_value = sensitivity_map.get(sensitivity_level, SENSITIVITY_MEDIUM_VALUE)
473479
request = ScanConfigureRequest(
474480
self._send,
475481
self._mac_in_bytes,
@@ -484,17 +490,20 @@ async def scan_configure(
484490
self._new_daylight_mode = None
485491
_LOGGER.warning("Failed to configure scan settings for %s", self.name)
486492
return False
493+
487494
if response.node_ack_type == NodeAckResponseType.SCAN_CONFIG_ACCEPTED:
488495
await self._scan_configure_update(
489496
motion_reset_timer, sensitivity_level, daylight_mode
490497
)
491498
return True
499+
492500
_LOGGER.warning(
493501
"Unexpected response ack type %s for %s",
494502
response.node_ack_type,
495503
self.name,
496504
)
497505
return False
506+
498507
self._new_reset_timer = None
499508
self._new_sensitivity_level = None
500509
self._new_daylight_mode = None

plugwise_usb/nodes/sed.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -453,23 +453,23 @@ async def _configure_sed_task(self) -> bool:
453453
self.name,
454454
)
455455
self._sed_config_task_scheduled = False
456-
change_required = True
457-
if self._new_battery_config.awake_duration is not None:
458-
change_required = True
459-
if self._new_battery_config.clock_interval is not None:
460-
change_required = True
461-
if self._new_battery_config.clock_sync is not None:
462-
change_required = True
463-
if self._new_battery_config.maintenance_interval is not None:
464-
change_required = True
465-
if self._new_battery_config.sleep_duration is not None:
456+
change_required = False
457+
if (
458+
self._new_battery_config.awake_duration is not None
459+
or self._new_battery_config.clock_interval is not None
460+
or self._new_battery_config.clock_sync is not None
461+
or self._new_battery_config.maintenance_interval is not None
462+
or self._new_battery_config.sleep_duration is not None
463+
):
466464
change_required = True
465+
467466
if not change_required:
468467
_LOGGER.debug(
469468
"_configure_sed_task | Device %s | no change",
470469
self.name,
471470
)
472471
return True
472+
473473
_LOGGER.debug(
474474
"_configure_sed_task | Device %s | request change",
475475
self.name,

plugwise_usb/nodes/sense.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,10 @@ async def load(self) -> bool:
5252
"""Load and activate Sense node features."""
5353
if self._loaded:
5454
return True
55+
5556
self._node_info.is_battery_powered = True
5657
if self._cache_enabled:
57-
_LOGGER.debug("Load Sense node %s from cache", self._node_info.mac)
58+
_LOGGER.debug("Loading Sense node %s from cache", self._node_info.mac)
5859
if await self._load_from_cache():
5960
self._loaded = True
6061
self._setup_protocol(
@@ -64,7 +65,8 @@ async def load(self) -> bool:
6465
if await self.initialize():
6566
await self._loaded_callback(NodeEvent.LOADED, self.mac)
6667
return True
67-
_LOGGER.debug("Load of Sense node %s failed", self._node_info.mac)
68+
69+
_LOGGER.debug("Loading of Sense node %s failed", self._node_info.mac)
6870
return False
6971

7072
@raise_not_loaded
@@ -94,6 +96,7 @@ async def _sense_report(self, response: PlugwiseResponse) -> bool:
9496
raise MessageError(
9597
f"Invalid response message type ({response.__class__.__name__}) received, expected SenseReportResponse"
9698
)
99+
report_received = False
97100
await self._available_update_state(True, response.timestamp)
98101
if response.temperature.value != 65535:
99102
self._temperature = int(
@@ -103,6 +106,8 @@ async def _sense_report(self, response: PlugwiseResponse) -> bool:
103106
await self.publish_feature_update_to_subscribers(
104107
NodeFeature.TEMPERATURE, self._temperature
105108
)
109+
report_received = True
110+
106111
if response.humidity.value != 65535:
107112
self._humidity = int(
108113
SENSE_HUMIDITY_MULTIPLIER * (response.humidity.value / 65536)
@@ -111,8 +116,9 @@ async def _sense_report(self, response: PlugwiseResponse) -> bool:
111116
await self.publish_feature_update_to_subscribers(
112117
NodeFeature.HUMIDITY, self._humidity
113118
)
114-
return True
115-
return False
119+
report_received = True
120+
121+
return report_received
116122

117123
@raise_not_loaded
118124
async def get_state(self, features: tuple[NodeFeature]) -> dict[NodeFeature, Any]:

plugwise_usb/nodes/switch.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def __init__(
4040
super().__init__(mac, address, controller, loaded_callback)
4141
self._switch_subscription: Callable[[], None] | None = None
4242
self._switch_state: bool | None = None
43-
self._switch: bool | None = None
43+
self._switch: bool = False
4444

4545
async def load(self) -> bool:
4646
"""Load and activate Switch node features."""
@@ -107,26 +107,21 @@ async def _switch_group(self, response: PlugwiseResponse) -> bool:
107107
async def _switch_state_update(
108108
self, switch_state: bool, timestamp: datetime
109109
) -> None:
110-
"""Process motion state update."""
110+
"""Process switch state update."""
111111
_LOGGER.debug(
112112
"_switch_state_update for %s: %s -> %s",
113113
self.name,
114114
self._switch_state,
115115
switch_state,
116116
)
117117
state_update = False
118-
# Switch on
119-
if switch_state:
120-
self._set_cache(CACHE_SWITCH_STATE, "True")
121-
if self._switch_state is None or not self._switch:
122-
self._switch_state = True
123-
state_update = True
124-
else:
125-
# Switch off
126-
self._set_cache(CACHE_SWITCH_STATE, "False")
127-
if self._switch is None or self._switch:
128-
self._switch_state = False
129-
state_update = True
118+
# Update cache
119+
self._set_cache(CACHE_SWITCH_STATE, str(switch_state))
120+
# Check for a state change
121+
if self._switch_state != switch_state:
122+
self._switch_state = switch_state
123+
state_update = True
124+
130125
self._set_cache(CACHE_SWITCH_TIMESTAMP, timestamp)
131126
if state_update:
132127
self._switch = switch_state

0 commit comments

Comments
 (0)