Skip to content

Commit

Permalink
⚗️ Use websockets w/o context manager and export it
Browse files Browse the repository at this point in the history
  • Loading branch information
Balaji-Ganesh committed Jun 10, 2023
1 parent 40b1b95 commit e99be95
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
39 changes: 39 additions & 0 deletions System/ESP32_communicator/async_stream_without_context_mgr.py
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
13 changes: 13 additions & 0 deletions System/ESP32_communicator/connection_initiator.py
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())

0 comments on commit e99be95

Please sign in to comment.