Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #1

Merged
merged 3 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .cache.sqlite
Binary file not shown.
347 changes: 347 additions & 0 deletions Images/sensors/sensor_mesh.drawio

Large diffs are not rendered by default.

48 changes: 48 additions & 0 deletions backend/Scripts/calc_achteck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
This script calculates the vertices of a regular octagon given its center and radius.
"""

import math


def octagon_vertices(center_x, center_y, radius):
"""Calculates the vertices of a regular octagon given its center and radius."""

# 360 degrees / 8 vertices = 45 degrees per vertex
angle_increment = 2 * math.pi / 8
vertices = []
for i in range(8):
angle = i * angle_increment
x = center_x + radius * math.cos(angle)
y = center_y + radius * math.sin(angle)
vertices.append((x, y))
return vertices


def main():
"""Prompts the user for center coordinates and radius, then prints the vertices."""

while True:
try:
center_input = input("Enter the center coordinates (x,y): ")
center_x, center_y = map(float, center_input.split(","))

radius = float(input("Enter the radius of the octagon: "))

if radius <= 0:
raise ValueError("Radius must be positive.")

break # Exit the loop if the input is valid
except ValueError:
print(
"Invalid input. Please enter coordinates in the format x,y and a positive radius.")

vertices = octagon_vertices(center_x, center_y, radius)

print("\nThe vertices of the octagon are:")
for vertex in vertices:
print(f"({vertex[0]:.2f}, {vertex[1]:.2f})")


if __name__ == "__main__":
main()
52 changes: 52 additions & 0 deletions backend/Scripts/rain_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import openmeteo_requests

import requests
import requests_cache
import pandas as pd
from retry_requests import retry
from urllib3.exceptions import InsecureRequestWarning

requests.urllib3.disable_warnings(
InsecureRequestWarning) # Warnungen deaktivieren

# Setup the Open-Meteo API client with cache and retry on error
cache_session = requests_cache.CachedSession('.cache', expire_after=3600)
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
openmeteo = openmeteo_requests.Client(session=retry_session)

# Make sure all required weather variables are listed here
# The order of variables in hourly or daily is important to assign them correctly below
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": 51.73929,
"longitude": 8.2509,
"hourly": ["rain", "wind_speed_10m", "wind_direction_10m"]
}
response = requests.get('https://api.open-meteo.com',
verify=False, timeout=10).json()

# Process first location. Add a for-loop for multiple locations or weather models
# response = responses[0]
print(f"Coordinates {response['latitude']}°N {response['longitude']}°E")
print(f"Elevation {response.Elevation()} m asl")
print(f"Timezone {response.Timezone()} {response.TimezoneAbbreviation()}")
print(f"Timezone difference to GMT+0 {response.UtcOffsetSeconds()} s")

# Process hourly data. The order of variables needs to be the same as requested.
hourly = response.Hourly()
hourly_rain = hourly.Variables(0).ValuesAsNumpy()
hourly_wind_speed_10m = hourly.Variables(1).ValuesAsNumpy()
hourly_wind_direction_10m = hourly.Variables(2).ValuesAsNumpy()

hourly_data = {"date": pd.date_range(
start=pd.to_datetime(hourly.Time(), unit="s", utc=True),
end=pd.to_datetime(hourly.TimeEnd(), unit="s", utc=True),
freq=pd.Timedelta(seconds=hourly.Interval()),
inclusive="left"
)}
hourly_data["rain"] = hourly_rain
hourly_data["wind_speed_10m"] = hourly_wind_speed_10m
hourly_data["wind_direction_10m"] = hourly_wind_direction_10m

hourly_dataframe = pd.DataFrame(data=hourly_data)
print(hourly_dataframe)
15 changes: 15 additions & 0 deletions backend/Scripts/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import wetteronline

# Definiere den Standort
location_name = "New York"

# Hole die URL für den Standort
location = wetteronline.location(location_name)
print(f"URL für den Standort: {location.url}")

# Hole die Wetterdaten für den Standort
weather = wetteronline.weather(location.url)

# Geben Sie alle verfügbaren Wetterdaten aus
weather_data = vars(weather)
print(f"Wetterdaten für {location_name}: {weather_data}")
Binary file modified backend/app/__pycache__/models.cpython-312.pyc
Binary file not shown.
Binary file modified backend/app/blueprints/__pycache__/api.cpython-312.pyc
Binary file not shown.
69 changes: 67 additions & 2 deletions backend/app/blueprints/api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,73 @@
from flask import Blueprint
"""
API Blueprint
-------------
This blueprint is used to define the API routes for the application.
The API blueprint is registered in the app factory in the app/__init__.py file.

Current Routes:
- /api
- /
- /test

The routes are defined as follows:
- /api
- GET: Returns the string "API Blueprint"
- /api/test
- GET: Returns the string "Test"
"""

from typing import Union, Tuple
from flask import Blueprint, jsonify, request
from werkzeug.wrappers import Response

from app.models import Sensor

api_bp = Blueprint('api', __name__)


@api_bp.route('/test')
@api_bp.route('/', methods=['GET'])
def index():
"""Index route for the API blueprint"""
return "API Blueprint"


@api_bp.route('/test', methods=['GET'])
def test():
"""Test route for the API blueprint"""
return "Test"


@api_bp.route('/sensors', methods=['GET', 'POST'])
def sensors() -> Union[Response, Tuple[Response, int]]:
"""
Handles GET and POST requests to the /sensors route.
GET: Returns a list of all sensors in the database.
POST: Adds a new sensor to the database.
"""

print(f"Request method: {request.method}")

if request.method == 'GET':
sensors_list = [sensor.to_dict() for sensor in Sensor.query.all()]
return jsonify(sensors_list), 200

elif request.method == 'POST':
if not request.json:
return jsonify({"error": "Bad Request", "message": "Body cannot be empty"}), 400

required_fields = ['sensor_id', 'serial_number',
'sensor_name', 'latitude', 'longitude', 'owner_id']
if not all(field in request.json for field in required_fields):
return jsonify({"error": "Bad Request", "message": "Missing values"}), 400

if Sensor.query.filter_by(sensor_id=request.json['sensor_id']).first():
return jsonify({"error": "Bad Request", "message": "Sensor already exists"}), 400

# Hier die Logik zum Hinzufügen des Sensors zur Datenbank einfügen.
# Beispiel: new_sensor = Sensor(...)
# db.session.add(new_sensor)
# db.session.commit()

return jsonify({"message": "Sensor successfully added"}), 201

return jsonify({"error": "Method Not Allowed"}), 405
36 changes: 36 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,42 @@ class Sensor(db.Model):

owner = db.relationship('User', backref=db.backref('sensors', lazy=True))

def __init__(self, sensor_id, serial_number, sensor_name, latitude, longitude, owner_id):
"""Initializes the Sensor model."""
self.sensor_id = sensor_id
self.serial_number = serial_number
self.sensor_name = sensor_name
self.latitude = latitude
self.longitude = longitude
self.owner_id = owner_id

def set_sensor(self, sensor_id, serial_number, sensor_name, latitude, longitude, owner_id):
"""Sets a sensor in the database."""

sensor = Sensor(
sensor_id=sensor_id,
serial_number=serial_number,
sensor_name=sensor_name,
latitude=latitude,
longitude=longitude,
owner_id=owner_id
)

db.session.add(sensor)
db.session.commit()

return sensor

def to_dict(self):
return {
'sensor_id': self.sensor_id,
'serial_number': self.serial_number,
'sensor_name': self.sensor_name,
'latitude': self.latitude,
'longitude': self.longitude,
'owner_id': self.owner_id
}


class LocalizationData(db.Model):
__tablename__ = 'localizationdata'
Expand Down
29 changes: 29 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"next-redux-wrapper": "^8.1.0",
"next-transpile-modules": "^10.0.1",
"ol": "^9.2.4",
"openmeteo": "^1.1.4",
"react": "^18.3.1",
"react-chartjs-2": "^5.2.0",
"react-dnd": "^16.0.1",
Expand Down
34 changes: 34 additions & 0 deletions frontend/src/app/dashboard/radar/Radar.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,37 @@
height: 600px;
background: transparent; /* Ensure the background is transparent */
}

.legendBox {
display: flex;
flex-direction: column;
align-items: center;
width: 90%;
max-width: 1200px;
margin: auto;
margin-top: 20px;
padding: 1rem;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: 0 4px 8px rgba(0, 0, 0, 0.8);
color: black;
font-size: 1rem;
line-height: 1.5;
text-align: center;
box-sizing: border-box;
overflow: hidden;
transition: max-height 0.5s;
}

.legendTitle {
font-size: 1.5rem;
font-weight: bold;
margin-bottom: 0.5rem;
}

.legendContent {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
8 changes: 4 additions & 4 deletions frontend/src/app/dashboard/radar/WMSLayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { useEffect } from "react";
import { useMap } from "react-leaflet";
import L from "leaflet";

const WMSTileLayer = ({ url, layers }: { url: string; layers: string }) => {
const WMSLayer = ({ url, layerName }: { url: string; layerName: string }) => {
const map = useMap();

useEffect(() => {
const wmsLayer = L.tileLayer.wms(url, {
layers,
layers: layerName,
format: "image/png",
transparent: true,
attribution: "© DWD",
Expand All @@ -18,9 +18,9 @@ const WMSTileLayer = ({ url, layers }: { url: string; layers: string }) => {
return () => {
map.removeLayer(wmsLayer);
};
}, [url, layers, map]);
}, [url, layerName, map]);

return null;
};

export default WMSTileLayer;
export default WMSLayer;
Loading
Loading