2024-05-02 17:31:38 +02:00
|
|
|
from fastapi import APIRouter
|
|
|
|
|
|
|
|
from datetime import datetime
|
2024-05-02 17:48:37 +02:00
|
|
|
import os
|
2024-05-02 17:31:38 +02:00
|
|
|
|
|
|
|
from fastapi.responses import HTMLResponse
|
|
|
|
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
|
file_path = "bettwaage.csv"
|
|
|
|
|
2024-05-02 17:48:37 +02:00
|
|
|
latest_values = None
|
|
|
|
zero_values = [0, 0, 0, 0]
|
|
|
|
scale_values = [1, 1, 1, 1]
|
|
|
|
|
2024-05-02 17:31:38 +02:00
|
|
|
|
|
|
|
def add_line_to_history(line: str) -> None:
|
|
|
|
with open(file_path, "+a", encoding="UTF-8") as fp:
|
2024-05-02 17:40:11 +02:00
|
|
|
fp.write(line)
|
2024-05-02 17:31:38 +02:00
|
|
|
|
|
|
|
|
2024-05-02 17:48:37 +02:00
|
|
|
def convert_to_weight(value: int, zero_value: int, scale: float) -> float:
|
|
|
|
return (value - zero_value) * scale
|
|
|
|
|
|
|
|
|
2024-05-02 17:31:38 +02:00
|
|
|
@router.get("/file")
|
|
|
|
async def get_file():
|
|
|
|
with open(file_path, "r", encoding="UTF-8") as fp:
|
|
|
|
return HTMLResponse("\n".join(fp.readlines()))
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/add")
|
|
|
|
async def add_weight(tl: int, tr: int, bl: int, br: int):
|
2024-05-02 17:48:37 +02:00
|
|
|
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])
|
|
|
|
|
2024-05-02 17:31:38 +02:00
|
|
|
sum = tl + tr + bl + br
|
2024-05-02 17:38:10 +02:00
|
|
|
add_line_to_history(f"{str(datetime.now())};{tl};{tr};{bl};{br};{sum};")
|
2024-05-02 17:31:38 +02:00
|
|
|
|
|
|
|
|
2024-05-02 17:48:37 +02:00
|
|
|
@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):
|
2024-05-02 17:31:38 +02:00
|
|
|
add_line_to_history("timestamp;tl;tr;bl;br;total;")
|