Skip to content

Commit 338ed98

Browse files
committed
Prevent reconnection race after disconnect.
Don't print on error, emit an event instead to users can opt in (the plugs can run out of TCP buffer space on occasion, resulting in truncated JSON objects).
1 parent 36a5d23 commit 338ed98

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

src/powersensor_local/plug_listener.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,11 @@ class PlugListener(AsyncEventEmitter):
1919
- ("disconnected") When a connection is dropped, be it intentional or not.
2020
- ("message",{...}) For each event message received from the plug. The
2121
plug's JSON message is decoded into a dict which is passed as the second
22-
argument to the registered event handler(s). The event handlers must be
23-
async.
22+
argument to the registered event handler(s).
23+
- ("malformed",line) If JSON decoding of a message fails. The raw line
24+
is included (as a byte string).
25+
26+
The event handlers must be async.
2427
"""
2528

2629
def __init__(self, ip, port=49476):
@@ -67,6 +70,8 @@ async def _close_connection(self):
6770
await self.emit('disconnected')
6871

6972
async def _do_connection(self, backoff = 0):
73+
if self._disconnecting:
74+
return
7075
if backoff < 9:
7176
backoff += 1
7277
try:
@@ -106,7 +111,7 @@ async def _process_line(self, reader, writer):
106111
else:
107112
await self.emit('message', message)
108113
except (json.decoder.JSONDecodeError) as ex:
109-
print(f"JSON error {ex} from {data}")
114+
await self.emit('malformed', data)
110115

111116
async def _send_subscribe(self, writer):
112117
writer.write(b'subscribe(60)\n')

0 commit comments

Comments
 (0)