Skip to content

Commit b1ca625

Browse files
committed
random unimportant cleanups
1 parent 839a37e commit b1ca625

File tree

9 files changed

+55
-55
lines changed

9 files changed

+55
-55
lines changed

docs/source/conf.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,15 @@
1010

1111
# Project information
1212
project = "powersensor_local"
13-
copyright = "2025, DiUS"
13+
copyright = "2025, DiUS" # noqa A001
1414
author = "Powersensor Team!"
1515

1616
html_favicon = "_static/powersensor-logo.png"
1717
html_logo = "_static/powersensor-logo.png"
1818

1919
# The full version, including alpha/beta/rc tags
2020
try:
21-
from powersensor_local import __version__
22-
release = __version__
21+
from powersensor_local import __version__ as release
2322
except ImportError:
2423
release = "0.1.0"
2524

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import Any
2+
3+
4+
class EventBuffer:
5+
def __init__(self, keep: int):
6+
self._keep = keep
7+
self._evs = []
8+
9+
def find_by_key(self, key: str, value: Any):
10+
for ev in self._evs:
11+
if key in ev and ev[key] == value:
12+
return ev
13+
return None
14+
15+
def append(self, ev: dict):
16+
self._evs.append(ev)
17+
if len(self._evs) > self._keep:
18+
del self._evs[0]
19+
20+
def evict_older(self, key: str, value: float):
21+
while len(self._evs) > 0:
22+
ev = self._evs[0]
23+
if key in ev and ev[key] <= value:
24+
del self._evs[0]
25+
else:
26+
return

src/powersensor_local/__init__.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,15 @@
1818
Lower-level interfaces are available in the PlugListenerUdp and PlugListenerTcp
1919
classes, though they are not recommended for general use.
2020
21-
Additionally a convience abstraction for translating some of the events into
21+
Additionally, a convenience abstraction for translating some of the events into
2222
a household view is available in VirtualHousehold.
2323
2424
Quick overview:
2525
• PlugApi is the recommended API layer
2626
• PlugListenerUdp is the UDP lower-level abstraction used by PlugApi
2727
• PlugListenerTcp is the TCP lower-level abstraction used by PlugApi
2828
• PowersensorDevices is the legacy main API layer
29-
LegadyDiscovery provides access to the legacy discovery mechanism
29+
LegacyDiscovery provides access to the legacy discovery mechanism
3030
• VirtualHousehold can be used to translate events into a household view
3131
3232
The 'plugevents' and 'rawplug' modules are helper utilities provided as
@@ -35,14 +35,13 @@
3535
nder the names ps-events, and offers up the events from PowersensorDevices.
3636
"""
3737
__all__ = [
38-
'devices',
39-
'legacy_discovery',
40-
'plug_api',
41-
'plug_listener_tcp',
42-
'plug_listener_udp',
43-
'virtual_household'
38+
'VirtualHousehold',
39+
'PlugApi',
40+
'__version__',
41+
'PlugListenerTcp',
42+
'PlugListenerUdp'
4443
]
45-
__version__ = "2.0.0"
44+
__version__ = "2.0.1"
4645
from .devices import PowersensorDevices
4746
from .legacy_discovery import LegacyDiscovery
4847
from .plug_api import PlugApi

src/powersensor_local/devices.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
import json
32
import sys
43

54
from datetime import datetime, timezone
@@ -10,7 +9,6 @@
109

1110
from powersensor_local.legacy_discovery import LegacyDiscovery
1211
from powersensor_local.plug_api import PlugApi
13-
from powersensor_local.xlatemsg import translate_raw_message
1412

1513
EXPIRY_CHECK_INTERVAL_S = 30
1614
EXPIRY_TIMEOUT_S = 5 * 60

src/powersensor_local/legacy_discovery.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def __init__(self, broadcast_addr = '<broadcast>'):
1313
"""
1414
super().__init__()
1515
self._dst_addr = broadcast_addr
16+
self._found = dict()
1617

1718
async def scan(self, timeout_sec = 2.0):
1819
"""Scans the local network for discoverable devices.

src/powersensor_local/plug_api.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,8 @@ async def disconnect(self):
5959
async def _on_message(self, _, message):
6060
"""Translates the raw message and emits the resulting messages, if any.
6161
62-
Also synthesises 'now_relaying_for' messages as needed.
62+
Also synthesizes 'now_relaying_for' messages as needed.
6363
"""
64-
evs = None
6564
try:
6665
evs = translate_raw_message(message, self._mac)
6766
except KeyError:

src/powersensor_local/plug_listener_tcp.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ async def _close_connection(self):
6969

7070
async def _do_connection(self, backoff = 0):
7171
if self._disconnecting:
72-
return
72+
return None
7373
if backoff < 9:
7474
backoff += 1
7575
try:
@@ -89,7 +89,7 @@ async def _do_connection(self, backoff = 0):
8989
# Handle disconnection and retry with exponential backoff
9090
await self._close_connection()
9191
if self._disconnecting:
92-
return
92+
return None
9393
await asyncio.sleep(min(5 * 60, 2**backoff * 1))
9494
return await self._do_connection(backoff)
9595

@@ -108,10 +108,11 @@ async def _process_line(self, reader, writer):
108108
pass
109109
else:
110110
await self.emit('message', message)
111-
except (json.decoder.JSONDecodeError) as ex:
111+
except json.decoder.JSONDecodeError:
112112
await self.emit('malformed', data)
113113

114-
async def _send_subscribe(self, writer):
114+
@staticmethod
115+
async def _send_subscribe(writer):
115116
writer.write(b'subscribe(60)\n')
116117
await writer.drain()
117118

src/powersensor_local/plug_listener_udp.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ async def _do_connection(self):
9292
family = socket.AF_INET,
9393
remote_addr = (self._ip, self._port))
9494
self._reconnect = loop.call_later(
95-
min(5*60, 2**self._backoff + 2), self._retry)
95+
min(5*60, 2**self._backoff + 2), self._retry) # noqa
9696

9797
def _send_subscribe(self):
9898
if self._transport is not None:
@@ -123,7 +123,7 @@ def datagram_received(self, data, addr):
123123
if self._inactive is not None:
124124
self._inactive.cancel()
125125
loop = asyncio.get_running_loop()
126-
self._inactive = loop.call_later(60, self._on_inactivity)
126+
self._inactive = loop.call_later(60, self._on_inactivity) # noqa
127127

128128
lines = data.decode('utf-8').splitlines()
129129
for line in lines:
@@ -137,7 +137,7 @@ def datagram_received(self, data, addr):
137137
pass
138138
else:
139139
asyncio.create_task(self.emit('message', message))
140-
except (json.decoder.JSONDecodeError) as ex:
140+
except json.decoder.JSONDecodeError:
141141
asyncio.create_task(self.emit('malformed', data))
142142

143143
def error_received(self, exc):

src/powersensor_local/virtual_household.py

Lines changed: 9 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import sys
44
from pathlib import Path
5+
6+
from powersensor_local.EventBuffer import EventBuffer
7+
58
project_root = str(Path(__file__).parents[1])
69
if project_root not in sys.path:
710
sys.path.append(project_root)
@@ -48,7 +51,7 @@ def same_duration(ev1: dict, ev2: dict):
4851
d2 = round(ev2[dur], 0)
4952
return d1 == d2
5053

51-
def matching_instants(starttime_utc: int, solar_events: list, housenet_events: list) -> Optional[InstantaneousValues]:
54+
def matching_instants(starttime_utc: int, solar_events: EventBuffer, housenet_events: EventBuffer) -> Optional[InstantaneousValues]:
5255
"""Attempts to match and merge solar+housenet average_power events."""
5356
solar = solar_events.find_by_key(KEY_START, starttime_utc)
5457
housenet = housenet_events.find_by_key(KEY_START, starttime_utc)
@@ -73,7 +76,7 @@ def make_instant_housenet(ev: dict) -> Optional[InstantaneousValues]:
7376
duration_s = round(ev[KEY_DUR_S], 0)
7477
)
7578

76-
def matching_summations(starttime_utc: int, solar_events: list, housenet_events: list) -> Optional[SummationValues]:
79+
def matching_summations(starttime_utc: int, solar_events: EventBuffer, housenet_events: EventBuffer) -> Optional[SummationValues]:
7780
"""Attempts to match and merge solar+housenet summation events."""
7881
solar = solar_events.find_by_key(KEY_START, starttime_utc)
7982
housenet = housenet_events.find_by_key(KEY_START, starttime_utc)
@@ -148,10 +151,10 @@ def __init__(self, with_solar: bool):
148151
self._expect_solar = with_solar
149152
self._summation = self.SummationInfo(0, 0, 0, 0)
150153
self._counters = self.Counters(0, 0, 0, 0, 0)
151-
self._solar_instants = self.EventBuffer(31)
152-
self._housenet_instants = self.EventBuffer(31)
153-
self._solar_summations = self.EventBuffer(5)
154-
self._housenet_summations = self.EventBuffer(5)
154+
self._solar_instants = EventBuffer(31)
155+
self._housenet_instants = EventBuffer(31)
156+
self._solar_summations = EventBuffer(5)
157+
self._housenet_summations = EventBuffer(5)
155158

156159
async def process_average_power_event(self, ev: dict):
157160
"""Ingests an event of type 'average_power'."""
@@ -186,7 +189,6 @@ async def process_summation_event(self, ev: dict):
186189
await self._process_summations(starttime_utc)
187190

188191
async def _process_instants(self, starttime_utc: int):
189-
v = None
190192
if self._expect_solar:
191193
v = matching_instants(starttime_utc, self._solar_instants, self._housenet_instants)
192194
else:
@@ -216,7 +218,6 @@ async def _process_instants(self, starttime_utc: int):
216218
})
217219

218220
async def _process_summations(self, starttime_utc: int):
219-
v = None
220221
if self._expect_solar:
221222
v = matching_summations(starttime_utc, self._solar_summations, self._housenet_summations)
222223
else:
@@ -295,30 +296,6 @@ def _increment_counters(self, d: SummationDeltas):
295296
self._counters.from_grid += d.from_grid
296297
self._counters.home_use += d.home_use
297298

298-
class EventBuffer:
299-
def __init__(self, keep: int):
300-
self._keep = keep
301-
self._evs = []
302-
303-
def find_by_key(self, key: str, value: any):
304-
for ev in self._evs:
305-
if key in ev and ev[key] == value:
306-
return ev
307-
return None
308-
309-
def append(self, ev: dict):
310-
self._evs.append(ev)
311-
if len(self._evs) > self._keep:
312-
del self._evs[0]
313-
314-
def evict_older(self, key: str, value: float):
315-
while len(self._evs) > 0:
316-
ev = self._evs[0]
317-
if key in ev and ev[key] <= value:
318-
del self._evs[0]
319-
else:
320-
return
321-
322299
@dataclass
323300
class SummationInfo:
324301
solar_resettime: int

0 commit comments

Comments
 (0)