Skip to content

Commit

Permalink
🚧 ⚗️ #1 Converting to FastAPI ... in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
Balaji-Ganesh committed Jun 15, 2023
1 parent 2e2d7cc commit 2f64234
Show file tree
Hide file tree
Showing 24 changed files with 141 additions and 138 deletions.
79 changes: 0 additions & 79 deletions app/middleware/communication/__init__.py

This file was deleted.

57 changes: 0 additions & 57 deletions app/middleware/communication/esp32_communicator.py

This file was deleted.

2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from app import create_app, socketio, esp32_comm, web_comm
from web import create_app, socketio, esp32_comm, web_comm


# FIXME: later figure out the way to place this in some file like, `web` and `feed`
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
85 changes: 85 additions & 0 deletions middleware/communication/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# This file is from the branch `experiments` as `fastapi_as_api_in_class.py`
import asyncio
from fastapi import FastAPI, APIRouter
import cv2

# Get the helpers..
from . import esp32

class ESP32Manager:
"""Manages all the communication related to the ESP32.
"""
def __init__(self, esp32IP: str, cam_port: int = 81, data_port: int = 82):
# set it to the assigned IP address to ESP32 when connected to WiFi.
esp32_ip: str = esp32IP
camera_port: int = cam_port
# configured ports for camera and data-transfer in ESP32.
data_port: int = data_port
self.camera_ws_url: str = "ws://"+esp32_ip+":" + \
str(camera_port) # url of camera websockets
self.data_txrx_url: str = "ws://"+esp32_ip+":" + \
str(data_port) # url of data transfer websockets

self.cam_task = None
self.data_task = None

self.task = None
self.router = APIRouter()

@self.router.get("/")
async def read_root():
return {"Hello": "World"}

@self.router.get("/camera-feed/{function}")
async def camera_feed_handler(function: str):
if function == 'start':
if self.cam_task is None:
self.cam_task = asyncio.create_task(esp32._camera_client(self))
return {"message": "Camera task started."}
else:
return {"message": "Camera task is already running."}
elif function == 'stop':
if self.cam_task is not None:
self.cam_task.cancel()
try:
await self.cam_task
except asyncio.CancelledError:
pass
self.cam_task = None
#FIXME: The below one, is for testing purposes. Remove once done.
cv2.destroyAllWindows()
return {"message": "Camera task stopped."}
else:
return {"message": "No camera task is currently running."}

@self.router.get("/collision-distance/{function}")
async def collision_dist_handler(function: str):
if function == 'start':
if self.data_task is None:
self.data_task = asyncio.create_task(
esp32._collision_dist_fetcher(self))
return {"message": "Collision-data task started."}
else:
return {"message": "Collision-data task is already running."}
elif function == 'stop':
if self.data_task is not None:
self.data_task.cancel()
try:
await self.data_task
except asyncio.CancelledError:
pass
self.data_task = None
return {"message": "Collision-data task stopped."}
else:
return {"message": "No collision-data task is currently running."}


class WebManager:
"""Manages all the connections to the web-app.
"""
def __init__(self):
self.router = APIRouter()

@self.router.get('/web')
def sayhello():
return 'Hello Web app'
41 changes: 41 additions & 0 deletions middleware/communication/esp32.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import cv2
import websockets
import numpy as np
import logging

# The below functions will become data members of ESP32Manager in __init__.py


async def _camera_client(self):
try:
cam_ws = await websockets.connect(self.camera_ws_url)
while True:
msg = await cam_ws.recv()
# even try with msg.data
npimg = np.array(bytearray(msg), dtype=np.uint8)
img = cv2.imdecode(npimg, -1)
cv2.imshow("img", img)
if cv2.waitKey(1) == 27:
print('EXITING')
cv2.destroyAllWindows()
return 'Camera feed stopped by user'
except Exception as e:
logging.error(
"[EXCEPTION] Camera streaming interrupted. Error: ", e)
finally:
await cam_ws.close()
logging.debug("Camera Websockets Connection closed successfully")
return 'ERROR in fetching feed'


async def _collision_dist_fetcher(self):
async with websockets.connect(self.data_txrx_url) as websocket:
while True:
message = await websocket.recv()
print(f"Received message: {message}")

# Process the message or perform any other task logic

# response = f"Processed: {message}"
# await websocket.send(response)
# print(f"Sent response: {response}")
13 changes: 13 additions & 0 deletions middleware/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# This file is from the branch `experiments` as `fastapi_as_api_in_class.py`
from fastapi import FastAPI, APIRouter
from communication import ESP32Manager, WebManager

app = FastAPI()
esp32 = ESP32Manager(esp32IP='192.168.134.165')
web = WebManager()

app.include_router(esp32.router)
app.include_router(web.router)

# if __name__ == "__main__":
# uvicorn.run(app, host="127.0.0.2", port=8000, reload=True)
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
This is just a test script to test the functionality made.
Deleted later.
"""
from app import get_cam_feed
from web import get_cam_feed
# from app.middleware.communication.esp32_communicator import get_cam_feed
import asyncio

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 2f64234

Please sign in to comment.