Added calibration endpoints

This commit is contained in:
Maximilian Giller 2024-05-02 17:48:37 +02:00
parent 918a0fa04c
commit 8916835654
2 changed files with 40 additions and 3 deletions

View file

@ -1,7 +1,7 @@
from fastapi import APIRouter from fastapi import APIRouter
from datetime import datetime from datetime import datetime
from os.path import exists import os
from fastapi.responses import HTMLResponse from fastapi.responses import HTMLResponse
@ -9,12 +9,20 @@ router = APIRouter()
file_path = "bettwaage.csv" file_path = "bettwaage.csv"
latest_values = None
zero_values = [0, 0, 0, 0]
scale_values = [1, 1, 1, 1]
def add_line_to_history(line: str) -> None: def add_line_to_history(line: str) -> None:
with open(file_path, "+a", encoding="UTF-8") as fp: with open(file_path, "+a", encoding="UTF-8") as fp:
fp.write(line) fp.write(line)
def convert_to_weight(value: int, zero_value: int, scale: float) -> float:
return (value - zero_value) * scale
@router.get("/file") @router.get("/file")
async def get_file(): async def get_file():
with open(file_path, "r", encoding="UTF-8") as fp: with open(file_path, "r", encoding="UTF-8") as fp:
@ -23,9 +31,38 @@ async def get_file():
@router.post("/add") @router.post("/add")
async def add_weight(tl: int, tr: int, bl: int, br: int): async def add_weight(tl: int, tr: int, bl: int, br: int):
global latest_values
latest_values = [tl, tr, bl, br]
tl = convert_to_weight(tl, zero_values[0], scale_values[0])
tr = convert_to_weight(tl, zero_values[1], scale_values[1])
bl = convert_to_weight(tl, zero_values[2], scale_values[2])
br = convert_to_weight(tl, zero_values[3], scale_values[3])
sum = tl + tr + bl + br sum = tl + tr + bl + br
add_line_to_history(f"{str(datetime.now())};{tl};{tr};{bl};{br};{sum};") add_line_to_history(f"{str(datetime.now())};{tl};{tr};{bl};{br};{sum};")
if not exists(file_path): @router.post("/delete")
async def delete_file():
os.remove(file_path)
@router.post("/zero")
async def set_zero():
if latest_values is None:
return HTMLResponse(
status_code=400, content="Requiring data before setting zeros."
)
global zero_values
zero_values = latest_values
@router.post("/scales")
async def set_scales(tl: float, tr: float, bl: float, br: float):
global scale_values
scale_values = [tl, tr, bl, br]
if not os.path.exists(file_path):
add_line_to_history("timestamp;tl;tr;bl;br;total;") add_line_to_history("timestamp;tl;tr;bl;br;total;")

View file

@ -5,7 +5,7 @@ from endpoints.bettwaage import router as bettwaage_router
app = FastAPI() app = FastAPI()
app.include_router(hue_router, prefix="/hue", tags=["hue"]) app.include_router(hue_router, prefix="/hue", tags=["hue"])
app.include_router(bettwaage_router, prefix="/bettwaage") app.include_router(bettwaage_router, prefix="/bettwaage", tags=["bett"])
if __name__ == "__main__": if __name__ == "__main__":
app.run() app.run()