-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
⚗️ Use websockets w/o context manager and export it
- Loading branch information
1 parent
40b1b95
commit e99be95
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
System/ESP32_communicator/async_stream_without_context_mgr.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
""" | ||
This file is modification of `asynchronouse_streaming.py` with a change as | ||
- Stream without using context manager (~not using `with` operator which handles opening and closing) | ||
1st test: | ||
- test without using context manager - as per the ref. below. | ||
2nd test: | ||
- initiate the connection in another file and use that in this file. | ||
- this is done by using another file called `connection_initiator.py` | ||
""" | ||
import websockets | ||
import asyncio | ||
import numpy as np | ||
import cv2 | ||
from connection_initiator import ws | ||
|
||
# url = "ws://192.168.64.165:81" | ||
async def listen(): | ||
# ws = await websockets.connect(url) | ||
try: | ||
while True: | ||
msg = await ws.recv() | ||
# print("Received message", msg) | ||
npimg = np.array(bytearray(msg), dtype=np.uint8) # even try with msg.data | ||
# print(npimg) | ||
img = cv2.imdecode(npimg, -1) | ||
cv2.imshow("img", img) | ||
if cv2.waitKey(1) == 27: | ||
print('EXITING') | ||
break | ||
except Exception as e: | ||
print(e) | ||
finally: | ||
await ws.ws_client.close() | ||
|
||
|
||
asyncio.get_event_loop().run_until_complete(listen()) | ||
|
||
# Reference: https://stackoverflow.com/questions/64897045/how-to-connect-to-websocket-without-context-manager |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
""" | ||
This file is created as a part of 2nd test in `async_stream_without_context_mgr.py` | ||
""" | ||
import websockets | ||
import asyncio | ||
|
||
url = "ws://192.168.64.165:81" | ||
async def listen(): | ||
global ws | ||
ws = await websockets.connect(url) | ||
|
||
|
||
asyncio.get_event_loop().run_until_complete(listen()) |