Skip to content

Commit 16a9ab8

Browse files
author
autoruff
committed
fixup: cache Python code reformatted using Ruff
1 parent b1cb78f commit 16a9ab8

30 files changed

+191
-147
lines changed

plugwise_usb/__init__.py

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -20,41 +20,43 @@
2020

2121
FuncT = TypeVar("FuncT", bound=Callable[..., Any])
2222

23-
NOT_INITIALIZED_STICK_ERROR: Final[StickError] = StickError("Cannot load nodes when network is not initialized")
23+
NOT_INITIALIZED_STICK_ERROR: Final[StickError] = StickError(
24+
"Cannot load nodes when network is not initialized"
25+
)
2426
_LOGGER = logging.getLogger(__name__)
2527

2628

2729
def raise_not_connected(func: FuncT) -> FuncT:
2830
"""Validate existence of an active connection to Stick. Raise StickError when there is no active connection."""
31+
2932
@wraps(func)
3033
def decorated(*args: Any, **kwargs: Any) -> Any:
3134
if not args[0].is_connected:
32-
raise StickError(
33-
"Not connected to USB-Stick, connect to USB-stick first."
34-
)
35+
raise StickError("Not connected to USB-Stick, connect to USB-stick first.")
3536
return func(*args, **kwargs)
37+
3638
return cast(FuncT, decorated)
3739

3840

3941
def raise_not_initialized(func: FuncT) -> FuncT:
4042
"""Validate if active connection is initialized. Raise StickError when not initialized."""
43+
4144
@wraps(func)
4245
def decorated(*args: Any, **kwargs: Any) -> Any:
4346
if not args[0].is_initialized:
4447
raise StickError(
45-
"Connection to USB-Stick is not initialized, " +
46-
"initialize USB-stick first."
48+
"Connection to USB-Stick is not initialized, "
49+
+ "initialize USB-stick first."
4750
)
4851
return func(*args, **kwargs)
52+
4953
return cast(FuncT, decorated)
5054

5155

5256
class Stick:
5357
"""Plugwise connection stick."""
5458

55-
def __init__(
56-
self, port: str | None = None, cache_enabled: bool = True
57-
) -> None:
59+
def __init__(self, port: str | None = None, cache_enabled: bool = True) -> None:
5860
"""Initialize Stick."""
5961
self._loop = get_running_loop()
6062
self._loop.set_debug(True)
@@ -170,13 +172,8 @@ def port(self) -> str | None:
170172
@port.setter
171173
def port(self, port: str) -> None:
172174
"""Path to serial port of USB-Stick."""
173-
if (
174-
self._controller.is_connected
175-
and port != self._port
176-
):
177-
raise StickError(
178-
"Unable to change port while connected. Disconnect first"
179-
)
175+
if self._controller.is_connected and port != self._port:
176+
raise StickError("Unable to change port while connected. Disconnect first")
180177

181178
self._port = port
182179

@@ -189,10 +186,8 @@ async def energy_reset_request(self, mac: str) -> bool:
189186
raise NodeError(f"{exc}") from exc
190187

191188
# Follow up by an energy-intervals (re)set
192-
if (
193-
result := await self.set_energy_intervals(
194-
mac, DEFAULT_CONS_INTERVAL, NO_PRODUCTION_INTERVAL
195-
)
189+
if result := await self.set_energy_intervals(
190+
mac, DEFAULT_CONS_INTERVAL, NO_PRODUCTION_INTERVAL
196191
):
197192
return result
198193

@@ -238,7 +233,9 @@ def subscribe_to_node_events(
238233
Returns the function to be called to unsubscribe later.
239234
"""
240235
if self._network is None:
241-
raise SubscriptionError("Unable to subscribe to node events without network connection initialized")
236+
raise SubscriptionError(
237+
"Unable to subscribe to node events without network connection initialized"
238+
)
242239
return self._network.subscribe_to_node_events(
243240
node_event_callback,
244241
events,
@@ -252,9 +249,7 @@ def _validate_node_discovery(self) -> None:
252249
if self._network is None or not self._network.is_running:
253250
raise StickError("Plugwise network node discovery is not active.")
254251

255-
async def setup(
256-
self, discover: bool = True, load: bool = True
257-
) -> None:
252+
async def setup(self, discover: bool = True, load: bool = True) -> None:
258253
"""Fully connect, initialize USB-Stick and discover all connected nodes."""
259254
if not self.is_connected:
260255
await self.connect()
@@ -271,17 +266,17 @@ async def connect(self, port: str | None = None) -> None:
271266
"""Connect to USB-Stick. Raises StickError if connection fails."""
272267
if self._controller.is_connected:
273268
raise StickError(
274-
f"Already connected to {self._port}, " +
275-
"Close existing connection before (re)connect."
269+
f"Already connected to {self._port}, "
270+
+ "Close existing connection before (re)connect."
276271
)
277272

278273
if port is not None:
279274
self._port = port
280275

281276
if self._port is None:
282277
raise StickError(
283-
"Unable to connect. " +
284-
"Path to USB-Stick is not defined, set port property first"
278+
"Unable to connect. "
279+
+ "Path to USB-Stick is not defined, set port property first"
285280
)
286281

287282
await self._controller.connect_to_stick(
@@ -319,9 +314,7 @@ async def load_nodes(self) -> bool:
319314
if self._network is None:
320315
raise NOT_INITIALIZED_STICK_ERROR
321316
if not self._network.is_running:
322-
raise StickError(
323-
"Cannot load nodes when network is not started"
324-
)
317+
raise StickError("Cannot load nodes when network is not started")
325318
return await self._network.discover_nodes(load=True)
326319

327320
@raise_not_connected

plugwise_usb/api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,13 +233,15 @@ class EnergyStatistics:
233233
day_production: float | None = None
234234
day_production_reset: datetime | None = None
235235

236+
236237
@dataclass
237238
class SenseStatistics:
238239
"""Sense statistics collection."""
239240

240241
temperature: float | None = None
241242
humidity: float | None = None
242243

244+
243245
class PlugwiseNode(Protocol):
244246
"""Protocol definition of a Plugwise device node."""
245247

@@ -704,5 +706,4 @@ async def message_for_node(self, message: Any) -> None:
704706
705707
"""
706708

707-
708709
# endregion

plugwise_usb/connection/__init__.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,19 +209,15 @@ async def get_node_details(
209209
ping_response: NodePingResponse | None = None
210210
if ping_first:
211211
# Define ping request with one retry
212-
ping_request = NodePingRequest(
213-
self.send, bytes(mac, UTF8), retries=1
214-
)
212+
ping_request = NodePingRequest(self.send, bytes(mac, UTF8), retries=1)
215213
try:
216214
ping_response = await ping_request.send()
217215
except StickError:
218216
return (None, None)
219217
if ping_response is None:
220218
return (None, None)
221219

222-
info_request = NodeInfoRequest(
223-
self.send, bytes(mac, UTF8), retries=1
224-
)
220+
info_request = NodeInfoRequest(self.send, bytes(mac, UTF8), retries=1)
225221
try:
226222
info_response = await info_request.send()
227223
except StickError:

plugwise_usb/connection/queue.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ async def stop(self) -> None:
7676

7777
async def submit(self, request: PlugwiseRequest) -> PlugwiseResponse | None:
7878
"""Add request to queue and return the received node-response when applicable.
79-
79+
8080
Raises an error when something fails.
8181
"""
8282
if request.waiting_for_response:
@@ -103,7 +103,8 @@ async def submit(self, request: PlugwiseRequest) -> PlugwiseResponse | None:
103103
if isinstance(request, NodePingRequest):
104104
# For ping requests it is expected to receive timeouts, so lower log level
105105
_LOGGER.debug(
106-
"%s, cancel because timeout is expected for NodePingRequests", exc
106+
"%s, cancel because timeout is expected for NodePingRequests",
107+
exc,
107108
)
108109
elif request.resend:
109110
_LOGGER.debug("%s, retrying", exc)
@@ -147,7 +148,9 @@ async def _send_queue_worker(self) -> None:
147148
if self._stick.queue_depth > 3:
148149
await sleep(0.125)
149150
if self._stick.queue_depth > 3:
150-
_LOGGER.warning("Awaiting plugwise responses %d", self._stick.queue_depth)
151+
_LOGGER.warning(
152+
"Awaiting plugwise responses %d", self._stick.queue_depth
153+
)
151154

152155
await self._stick.write_to_stick(request)
153156
self._submit_queue.task_done()

plugwise_usb/connection/receiver.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,4 +513,5 @@ async def _notify_node_response_subscribers(
513513
name=f"Postpone subscription task for {node_response.seq_id!r} retry {node_response.retries}",
514514
)
515515

516+
516517
# endregion

plugwise_usb/connection/sender.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __init__(self, stick_receiver: StickReceiver, transport: Transport) -> None:
4848
def processed_messages(self) -> int:
4949
"""Return the number of processed messages."""
5050
return self._processed_msgs
51-
51+
5252
async def start(self) -> None:
5353
"""Start the sender."""
5454
# Subscribe to ACCEPT stick responses, which contain the seq_id we need.
@@ -79,7 +79,9 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
7979

8080
# Write message to serial port buffer
8181
serialized_data = request.serialize()
82-
_LOGGER.debug("write_request_to_port | Write %s to port as %s", request, serialized_data)
82+
_LOGGER.debug(
83+
"write_request_to_port | Write %s to port as %s", request, serialized_data
84+
)
8385
self._transport.write(serialized_data)
8486
# Don't timeout when no response expected
8587
if not request.no_response:
@@ -106,7 +108,11 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
106108
_LOGGER.warning("Exception for %s: %s", request, exc)
107109
request.assign_error(exc)
108110
else:
109-
_LOGGER.debug("write_request_to_port | USB-Stick replied with %s to request %s", response, request)
111+
_LOGGER.debug(
112+
"write_request_to_port | USB-Stick replied with %s to request %s",
113+
response,
114+
request,
115+
)
110116
if response.response_type == StickResponseType.ACCEPT:
111117
if request.seq_id is not None:
112118
request.assign_error(
@@ -120,7 +126,9 @@ async def write_request_to_port(self, request: PlugwiseRequest) -> None:
120126
self._receiver.subscribe_to_stick_responses,
121127
self._receiver.subscribe_to_node_responses,
122128
)
123-
_LOGGER.debug("write_request_to_port | request has subscribed : %s", request)
129+
_LOGGER.debug(
130+
"write_request_to_port | request has subscribed : %s", request
131+
)
124132
elif response.response_type == StickResponseType.TIMEOUT:
125133
_LOGGER.warning(
126134
"USB-Stick directly responded with communication timeout for %s",

plugwise_usb/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Plugwise Stick constants."""
2+
23
from __future__ import annotations
34

45
import datetime as dt

plugwise_usb/helpers/cache.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,15 @@ async def initialize_cache(self, create_root_folder: bool = False) -> None:
5353
"""Set (and create) the plugwise cache directory to store cache file."""
5454
if self._root_dir != "":
5555
if not create_root_folder and not await ospath.exists(self._root_dir):
56-
raise CacheError(f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exists.")
56+
raise CacheError(
57+
f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exists."
58+
)
5759
cache_dir = self._root_dir
5860
else:
5961
cache_dir = self._get_writable_os_dir()
6062
await makedirs(cache_dir, exist_ok=True)
6163
self._cache_path = cache_dir
62-
64+
6365
self._cache_file = os_path_join(self._cache_path, self._file_name)
6466
self._cache_file_exists = await ospath.exists(self._cache_file)
6567
self._initialized = True
@@ -72,13 +74,17 @@ def _get_writable_os_dir(self) -> str:
7274
if os_name == "nt":
7375
if (data_dir := os_getenv("APPDATA")) is not None:
7476
return os_path_join(data_dir, CACHE_DIR)
75-
raise CacheError("Unable to detect writable cache folder based on 'APPDATA' environment variable.")
77+
raise CacheError(
78+
"Unable to detect writable cache folder based on 'APPDATA' environment variable."
79+
)
7680
return os_path_join(os_path_expand_user("~"), CACHE_DIR)
7781

7882
async def write_cache(self, data: dict[str, str], rewrite: bool = False) -> None:
79-
""""Save information to cache file."""
83+
""" "Save information to cache file."""
8084
if not self._initialized:
81-
raise CacheError(f"Unable to save cache. Initialize cache file '{self._file_name}' first.")
85+
raise CacheError(
86+
f"Unable to save cache. Initialize cache file '{self._file_name}' first."
87+
)
8288

8389
current_data: dict[str, str] = {}
8490
if not rewrite:
@@ -111,19 +117,20 @@ async def write_cache(self, data: dict[str, str], rewrite: bool = False) -> None
111117
if not self._cache_file_exists:
112118
self._cache_file_exists = True
113119
_LOGGER.debug(
114-
"Saved %s lines to cache file %s",
115-
str(len(data)),
116-
self._cache_file
120+
"Saved %s lines to cache file %s", str(len(data)), self._cache_file
117121
)
118122

119123
async def read_cache(self) -> dict[str, str]:
120124
"""Return current data from cache file."""
121125
if not self._initialized:
122-
raise CacheError(f"Unable to save cache. Initialize cache file '{self._file_name}' first.")
126+
raise CacheError(
127+
f"Unable to save cache. Initialize cache file '{self._file_name}' first."
128+
)
123129
current_data: dict[str, str] = {}
124130
if not self._cache_file_exists:
125131
_LOGGER.debug(
126-
"Cache file '%s' does not exists, return empty cache data", self._cache_file
132+
"Cache file '%s' does not exists, return empty cache data",
133+
self._cache_file,
127134
)
128135
return current_data
129136
try:
@@ -146,10 +153,10 @@ async def read_cache(self) -> dict[str, str]:
146153
_LOGGER.warning(
147154
"Skip invalid line '%s' in cache file %s",
148155
data,
149-
str(self._cache_file)
156+
str(self._cache_file),
150157
)
151158
break
152-
current_data[data[:index_separator]] = data[index_separator + 1:]
159+
current_data[data[:index_separator]] = data[index_separator + 1 :]
153160
return current_data
154161

155162
async def delete_cache(self) -> None:

plugwise_usb/helpers/util.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Plugwise utility helpers."""
2+
23
from __future__ import annotations
34

45
import re
@@ -21,7 +22,7 @@ def validate_mac(mac: str) -> bool:
2122
return True
2223

2324

24-
def version_to_model(version: str | None) -> tuple[str|None, str]:
25+
def version_to_model(version: str | None) -> tuple[str | None, str]:
2526
"""Translate hardware_version to device type."""
2627
if version is None:
2728
return (None, "Unknown")

plugwise_usb/messages/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class Priority(Enum):
1919
MEDIUM = 2
2020
LOW = 3
2121

22+
2223
class PlugwiseMessage:
2324
"""Plugwise message base class."""
2425

0 commit comments

Comments
 (0)