I am using WebSockets and FastAPI to send two different types of data to my frontend: data from pressure/temperature readings and video data from a camera.
Is there a way in Python, to create an event loop such that if the first generator is still waiting on a response, then it will skip a section of code and go to the next generator? Essentially, the video data is basically real time. We can send a frame as often as we like. But the temperature/pressure data comes either every 10 seconds or every 5 seconds. Here is an example of what I would like:
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_json({"text": "testing"})
iter_one = get_rtd() #this is the temp/pressure data
iter_two = get_frame() #this is the video feed
while True:
await asyncio.sleep(0.1)
if waiting_for_response(iter_one):
payload = next(iter_two)
await websocket.send_json({"type": "video", "payload": payload})
else:
payload = next(iter_one)
await websocket.send_json({"type": "rtd", "payload": payload})
The generators in my current solution are not asynchronous. My current solution is to have two different websocket endpoints, one for the temp/pressure data and the other for video. I have my temp/pressure loop wait 4.5 seconds so it blocks while the camera data is sent. It's not ideal because the camera data then freezes once the temp/pressure loop unblocks and the live video feed slowly falls further and further behind.