|
1 | 1 | """Websocket class for OpenEVSE HTTP.""" |
2 | 2 |
|
3 | 3 | import asyncio |
| 4 | +import json |
4 | 5 | import logging |
5 | 6 |
|
6 | 7 | import aiohttp # type: ignore |
@@ -39,6 +40,7 @@ def __init__( |
39 | 40 | self._state = None |
40 | 41 | self.failed_attempts = 0 |
41 | 42 | self._error_reason = None |
| 43 | + self._client = None |
42 | 44 |
|
43 | 45 | @property |
44 | 46 | def state(self): |
@@ -74,6 +76,7 @@ async def running(self): |
74 | 76 | ) as ws_client: |
75 | 77 | await OpenEVSEWebsocket.state.fset(self, STATE_CONNECTED) |
76 | 78 | self.failed_attempts = 0 |
| 79 | + self._client = ws_client |
77 | 80 |
|
78 | 81 | async for message in ws_client: |
79 | 82 | if self.state == STATE_STOPPED: |
@@ -133,3 +136,16 @@ async def listen(self): |
133 | 136 | async def close(self): |
134 | 137 | """Close the listening websocket.""" |
135 | 138 | await OpenEVSEWebsocket.state.fset(self, STATE_STOPPED) |
| 139 | + |
| 140 | + async def keepalive(self): |
| 141 | + """Send ping requests to websocket.""" |
| 142 | + data = json.dumps({"ping": 1}) |
| 143 | + _LOGGER.debug("Sending message: %s to websocket.", data) |
| 144 | + try: |
| 145 | + await self._client.send_str(data) |
| 146 | + _LOGGER.debug("Ping message sent.") |
| 147 | + except TypeError as err: |
| 148 | + _LOGGER.error("Attempt to send ping data failed: %s", err) |
| 149 | + except Exception as err: # pylint: disable=broad-exception-caught |
| 150 | + _LOGGER.error("Problem sending ping request: %s", err) |
| 151 | + await OpenEVSEWebsocket.state.fset(self, STATE_STOPPED) |
0 commit comments