diff --git a/app/middleware/communication/__init__.py b/app/middleware/communication/__init__.py index 31ae70f..ff66df1 100644 --- a/app/middleware/communication/__init__.py +++ b/app/middleware/communication/__init__.py @@ -7,17 +7,22 @@ """ import websockets +import asyncio """***************************** Initial configurations *****************************""" -esp32_ip = '172.168.1.132' # set it to the assigned IP address to ESP32 when connected to WiFi. +esp32_ip = '192.168.64.165' # set it to the assigned IP address to ESP32 when connected to WiFi. camera_port, data_port = 81, 82 # configured ports for camera and data-transfer in ESP32. camera_ws_url = "ws://"+esp32_ip+":"+str(camera_port) # url of camera websockets data_txrx_url = "ws://"+esp32_ip+":"+str(data_port) # url of data transfer websockets # FIXME: make the way of setting the IP and ports - dynamically. Say by use of environment variables. #### Establish websocket communications... -camera_ws = websockets.connect(camera_ws_url) -data_ws = websockets.connect(data_txrx_url) +async def establish_connection(): + global camera_ws, data_ws # defining as global, as to be used in other file + camera_ws = await websockets.connect(camera_ws_url) + data_ws = await websockets.connect(data_txrx_url) + +asyncio.get_event_loop().run_until_complete(establish_connection()) # Expose functionalities of this module to other modules... from .esp32_communicator import get_cam_feed diff --git a/app/middleware/communication/esp32_communicator.py b/app/middleware/communication/esp32_communicator.py index 40c7bf7..e313821 100644 --- a/app/middleware/communication/esp32_communicator.py +++ b/app/middleware/communication/esp32_communicator.py @@ -6,7 +6,7 @@ import cv2 import numpy as np # Necessary local imports -from . import camera_ws, data_ws # import websockets for communication +from . import camera_ws as ws, data_ws # import websockets for communication """ --------------- Utility functions ------------ """ # Camera related.. @@ -18,16 +18,19 @@ async def get_cam_feed(): Yields: cv2 image: Frames sent by ESP32 """ - async with camera_ws as ws: + 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) - yield img ## <<<<<<<<<<<<<<<<--- caller function gets the cam feed from here - cv2.imshow("[DEBUG] ESP32 cam feed", img) + cv2.imshow("img", img) if cv2.waitKey(1) == 27: print('EXITING') break + except Exception as e: + print(e) + finally: + await ws.ws_client.close() diff --git a/test.py b/test.py new file mode 100644 index 0000000..7c746f8 --- /dev/null +++ b/test.py @@ -0,0 +1,8 @@ +""" +This is just a test script to test the functionality made. +Deleted later. +""" +from app import get_cam_feed +import asyncio + +asyncio.get_event_loop().run_until_complete(get_cam_feed()) \ No newline at end of file