1

I am using an optical sensor on my energy meter. At the moment I am calling a python script fetching new values through optical sensor every 10 seconds. The raspberry pi zero takes a while to start the python script (over 5 seconds).

I like to fetch sensor data every second now.

What I want:

  • start script once, use while loop to fetch new sensor data and sleep 1 second after fetch
  • offer a rest API endpoint with latest value (uvicorn and fastapi?!)

Maybe I can get some help to get me started. Thanks.

S. Gissel
  • 1,788
  • 2
  • 15
  • 32

1 Answers1

1

What you could do is have a variable for the last sensor read, and use the async nature of FastAPI to run an asyncio background task which updates the variable every second. asyncio.create_task can be used for this, and you can use FastAPI's startup event to start reading.

Something along the lines of

import asyncio
from fastapi import FastAPI

app = FastAPI()
sensor_data = None

async def read_optical_sensor():
    global sensor_data
    while True:
        sensor_data = ... # Read your sensor here, preferably in an async way
        await asyncio.sleep(1)

@app.on_event("startup")
async def startup():
    asyncio.create_task(read_optical_sensor())
    
@app.get("/read")
async def get_sensor_data():
    return {"data": sensor_data}
M.O.
  • 1,712
  • 1
  • 6
  • 18
  • This answer is just what I was looking for. To read the sensor_data non blocking I use `await run_in_threadpool(lambda: read_meter())` – S. Gissel Jul 06 '22 at 12:01