Skip to content

Commit 9b46e7a

Browse files
authored
Optimize processing of websocket messages (#57)
Switch to asyncio.timeout/async_timeout to avoid task creation - asyncio.wait_for creates a task which is not needed here - the wait_for implementation will eventually be replaced but not until 3.12 in python/cpython#98518 Use orjson for parsing json
1 parent a6f8625 commit 9b46e7a

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

sense_energy/asyncsenseable.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import asyncio
22
import json
33
import ssl
4+
import sys
45

56
import aiohttp
7+
import orjson
68
import websockets
79

810
from .sense_api import *
911
from .sense_exceptions import *
1012

13+
if sys.version_info[:2] < (3, 11):
14+
from async_timeout import timeout as asyncio_timeout
15+
else:
16+
from asyncio import timeout as asyncio_timeout
1117

1218
class ASyncSenseable(SenseableBase):
1319
def __init__(
@@ -145,11 +151,12 @@ async def async_realtime_stream(self, callback=None, single=False):
145151
async with websockets.connect(url, ssl=self.ssl_context) as ws:
146152
while True:
147153
try:
148-
message = await asyncio.wait_for(ws.recv(), timeout=self.wss_timeout)
154+
async with asyncio_timeout(self.wss_timeout):
155+
message = await ws.recv()
149156
except asyncio.TimeoutError as ex:
150157
raise SenseAPITimeoutException("API websocket timed out") from ex
151158

152-
result = json.loads(message)
159+
result = orjson.loads(message)
153160
if result.get("type") == "realtime_update":
154161
data = result["payload"]
155162
self._set_realtime(data)

setup.py

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
name = 'sense_energy',
99
packages = ['sense_energy'],
1010
install_requires=[
11+
'async_timeout>=3.0.1',
12+
'orjson',
1113
'requests',
1214
'websocket-client',
1315
'websockets;python_version>="3.5"',

0 commit comments

Comments
 (0)