162 lines
5.9 KiB
Python
162 lines
5.9 KiB
Python
from fastapi import FastAPI, Form, File, Request
|
|
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
|
|
from jinja2 import Template
|
|
import os
|
|
from typing import Annotated
|
|
from pydantic import BaseModel
|
|
import tempfile
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.templating import Jinja2Templates
|
|
import ipaddress
|
|
import psycopg2
|
|
from dateutil.parser import parse
|
|
from datetime import datetime
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import PlainTextResponse, JSONResponse
|
|
from fastapi.exception_handlers import (
|
|
http_exception_handler,
|
|
request_validation_exception_handler,
|
|
)
|
|
import threading
|
|
import socket
|
|
import struct
|
|
from zoneinfo import ZoneInfo
|
|
|
|
temp_dir = r"/home/td/WebTemp"
|
|
tempfile.tempdir = temp_dir
|
|
|
|
app = FastAPI(title="user manager", description="User session management.", version="0.0.0.1",
|
|
docs_url="/server/docs", redoc_url="/server/redoc", openapi_url="/server/openapi.json")
|
|
|
|
app.mount("/server/static", StaticFiles(directory="static"), name="static")
|
|
templates = Jinja2Templates(directory="templates")
|
|
distance_value = 0.0
|
|
last_updated = None
|
|
distance_value_rev = 0.0
|
|
|
|
def get_udp_water_value():
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
count = 0
|
|
while True:
|
|
try:
|
|
sock.bind(('', 8176))
|
|
sock.settimeout(5.0)
|
|
break
|
|
except Exception as e:
|
|
count+=1
|
|
print("Exception: e", e)
|
|
time.sleep(5)
|
|
if count >= 100:
|
|
raise e
|
|
zone = ZoneInfo("Asia/Kolkata");
|
|
print("Bound to address: 8176")
|
|
global distance_value
|
|
global last_updated
|
|
global distance_value_rev
|
|
while True:
|
|
try:
|
|
data, addr = sock.recvfrom(4)
|
|
print(f"Got data: {data.hex()}")
|
|
distance_value = struct.unpack('>f', data)
|
|
distance_value_rev = struct.unpack('<f', data)
|
|
print(f"Updated distance_value to: {distance_value}")
|
|
last_updated = datetime.now(zone).strftime("%d/%m/%y %H:%M:%S");
|
|
except Exception as e:
|
|
print("Did not get any data in 5 seconds: ", e)
|
|
|
|
thread = threading.Thread(target=get_udp_water_value)
|
|
thread.start();
|
|
|
|
|
|
@app.get("/server/waterlevel", response_class=JSONResponse)
|
|
async def get_water_level(request: Request):
|
|
global distance_value
|
|
global last_updated
|
|
global distance_value_rev
|
|
return {"water_level": distance_value, "water_level_rev": distance_value_rev, "updated_on": last_updated}
|
|
|
|
|
|
# @app.post("/api/users/create", response_class=RedirectResponse)
|
|
# async def root(username: Annotated[str, Form()], password: Annotated[str, Form()],
|
|
# new_user: Annotated[str, Form()], new_password: Annotated[str, Form()]):
|
|
# global internal_status
|
|
# val = helper.validate_credentials(username, password)
|
|
# print("Validation result: ", val)
|
|
# if val == "valid":
|
|
# print("Valid creds")
|
|
# helper.status_type = 'success'
|
|
# helper.internal_status = "Created New User"
|
|
# helper.create_new_user(new_user, new_password)
|
|
# return RedirectResponse(url=f"/api/users/", status_code=303)
|
|
# elif val == "invalid":
|
|
# print("Invalid creds")
|
|
# helper.status_type = 'danger'
|
|
# helper.internal_status = "Invalid Credentials"
|
|
# return RedirectResponse(url=f"/api/users/", status_code=303)
|
|
# else:
|
|
# print("Validation issue: ", val)
|
|
# helper.status_type = 'danger'
|
|
# helper.internal_status = val
|
|
# return RedirectResponse(url="/api/users/", status_code=303)
|
|
|
|
# @app.post("/api/users/login")
|
|
# async def root(user: User, request: Request):
|
|
# ip = request.headers['X-Real-IP']
|
|
# if ipaddress.ip_address(ip) not in ipaddress.ip_network('192.168.0.0/16'):
|
|
# return {"message": "unknown user"}
|
|
# val = helper.validate_credentials(user.username, user.password)
|
|
# if val == 'valid':
|
|
# print("Valid creds generating session key")
|
|
# (session_key, expiry_date) = helper.create_new_session_key(user.username)
|
|
# return {"message": "credentials validated", "session_key": session_key, "expiry_date": expiry_date}
|
|
# elif val == 'invalid':
|
|
# print("Invalid creds.")
|
|
# return {"message": "invalid credentials"}
|
|
# elif val == 'session_active':
|
|
# print("session is active.")
|
|
# return {"message": "active session"}
|
|
|
|
|
|
# @app.post("/api/users/logout")
|
|
# async def root(user: User, request: Request):
|
|
# ip = request.headers['X-Real-IP']
|
|
# if ipaddress.ip_address(ip) not in ipaddress.ip_network('192.168.0.0/16'):
|
|
# return {"message": "unknown user"}
|
|
# val = helper.validate_credentials(user.username, user.password)
|
|
# if val == 'valid':
|
|
# print(f"User {user.username} is not active.")
|
|
# return {"message", "user not active"}
|
|
# elif val == 'session_active':
|
|
# print(f"Logging out user: {user.username}, bye!")
|
|
# ret = helper.logout_user(user.username)
|
|
# return {"message": f"logout status: {str(ret)}"}
|
|
# else:
|
|
# print(f"invalid credentials.")
|
|
# return {"message": "invalid credentials"}
|
|
|
|
|
|
|
|
|
|
|
|
# @app.exception_handler(RequestValidationError)
|
|
# async def validation_exception_handler(request, exc):
|
|
# print(exc)
|
|
# return PlainTextResponse(str(exc), status_code=400)
|
|
|
|
|
|
# @app.exception_handler(StarletteHTTPException)
|
|
# async def custom_http_exception_handler(request, exc):
|
|
# print(f"OMG! An HTTP error!: {repr(exc)}")
|
|
# return await http_exception_handler(request, exc)
|
|
|
|
|
|
# @app.exception_handler(RequestValidationError)
|
|
# async def validation_exception_handler(request, exc):
|
|
# print(f"OMG! The client sent invalid data!: {exc}")
|
|
# return await request_validation_exception_handler(request, exc)
|
|
|
|
|
|
|