migrate repository again

This commit is contained in:
2025-11-17 22:06:13 +01:00
commit 50c0f46207
9 changed files with 573 additions and 0 deletions

178
.gitignore vendored Normal file
View File

@@ -0,0 +1,178 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
### CUSTOM GITIGNORES
db_creds.csv

2
README.md Normal file
View File

@@ -0,0 +1,2 @@
# sensordata

73
db_connect.py Normal file
View File

@@ -0,0 +1,73 @@
import mariadb
import logging
from typing import Generator
import datetime
# main database connector class
# permission validation is not performed on this class
# perform those higher on the call stack
class DatabaseConnect:
def __init__(self) -> None:
with open("db_creds.csv","r") as f:
credentials = f.read().split(",")
try:
conn = mariadb.connect(
user=credentials[0],
password=credentials[1],
host=credentials[2],
port=int(credentials[3]),
database=credentials[4]
)
except mariadb.Error as e:
logging.fatal(f"Error connecting to database: {e}")
return
self.cursor = conn.cursor()
super().__init__()
def create_user(self, username: str, pwd: int) -> None:
self.cursor.execute("INSERT INTO Users (username, pwd) VALUE (?,?)",(username, pwd))
logging.info(f"Created user {username}")
def delete_user(self, id) -> None:
self.cursor.execute("DELETE FROM Users WHERE ID = ?",(id))
logging.info(f"Deleted user {id}")
def display_users(self) -> tuple[tuple[int, str, int]]:
self.cursor.execute("SELECT * FROM Users")
return self.cursor.fetchall()
def view_valid_rooms(self, user_id) -> list[tuple[str, str]]:
self.cursor.execute(
"SELECT rooms.name, rooms.shortname from permissions INNER JOIN rooms ON permissions.`roomID` = rooms.`ID` WHERE permissions.`userID` = ? AND permissions.`view` = 1;",
(user_id,))
return self.cursor.fetchall()
def user_has_room_perms(self, user_id, room_shortname) -> bool:
self.cursor.execute("SELECT permissions.`view` FROM permissions LEFT JOIN rooms ON permissions.`roomID` = rooms.ID WHERE rooms.shortname = ? AND `userID` = ?;",(room_shortname, user_id))
res = self.cursor.fetchone()
if res is None:
return False
else:
return res[0] == 1
# def roomID_from_shortname(self, shortname):
# self.cursor.execute("SELECT rooms.`ID` from rooms WHERE rooms.shortname = ?;",(shortname,))
# return self.cursor.fetchone()
def get_sensors_in_room(self, shortname) -> list[int]:
self.cursor.execute("SELECT devices.`ID` from devices LEFT JOIN rooms ON devices.`roomID` = rooms.ID WHERE rooms.shortname = ?;",(shortname,))
return [x[0] for x in self.cursor.fetchall()]
def get_sensor_data(self, sensor_ID: int) -> Generator[tuple[datetime.datetime, float]]:
self.cursor.execute("SELECT Timestamp, reading FROM Readings WHERE `sensorID` = ? ORDER BY `Timestamp` DESC;",(sensor_ID,))
for row in self.cursor:
yield row
def get_sensor_type(self, sensor_ID):
self.cursor.execute("SELECT types.`type_desc` from types LEFT JOIN devices ON types.`ID` = devices.`type` WHERE devices.`ID` = ?;",(sensor_ID,))
return self.cursor.fetchone()[0]
if __name__ == "__main__":
a = DatabaseConnect()
print(a.get_sensor_type(1))

BIN
requirements.txt Normal file

Binary file not shown.

37
sql_startup.sql Normal file
View File

@@ -0,0 +1,37 @@
CREATE DATABASE sensors;
GRANT ALL PRIVILEGES ON sensors.* TO SensorsAdmin;
USE sensors;
GO
CREATE TABLE Users (`ID` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` TEXT, `pwd` INT);
INSERT INTO Users (`ID`, `username`, `pwd`) VALUES (1,'nouser',NULL), (NULL,'Admin',1);
CREATE TABLE Permissions (`userID` INT, `roomID` INT, `view` BOOLEAN DEFAULT 0, `purge_data` BOOLEAN DEFAULT 0, `administer` BOOLEAN DEFAULT 0);
CREATE TABLE Rooms (`ID` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` TEXT, `shortname` TEXT UNIQUE);
CREATE TABLE Devices(`ID` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, `type` INT, `roomID` INT, `mqttTopic` TEXT);
CREATE TABLE Types(`ID` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, `type_desc` TEXT);
CREATE TABLE Readings(`sensorID` INT, `Timestamp` DATETIME, `reading` DOUBLE);
CREATE INDEX `sensor_index` ON Readings (`sensorID`);
INSERT INTO Rooms (`name`,`shortname`) VALUES ('101','101'),('102','102'),('210','210'),('211','211'),('215 - Studovna','215');
INSERT INTO Devices (`type`, `roomID`,`mqttTopic`) VALUES (1,1,"101/floortemp"),(1,1,"101/ceiltemp"),(2,1,"101/humidity"),(1,3,"210/temp"),(1,5,"215/temp"),(2,5,"215/humidity");
INSERT INTO Types (type_desc) VALUES ("Temperature"), ('Humidity');
INSERT INTO `readings`(`Timestamp`,`reading`,`sensorID`) VALUES
('2025-11-12 00:00:00',25.7,1),('2025-11-12 01:00:00',26.7,1),('2025-11-12 02:00:00',27.4,1),('2025-11-12 02:04:00',28.0,1),('2025-11-12 03:22:00',28.2,1),
('2025-11-12 00:00:00',22.7,2),('2025-11-12 01:00:00',23.4,2),('2025-11-12 02:00:00',23.9,2),('2025-11-12 02:05:00',25.5,2),('2025-11-12 03:20:00',27.7,2),
('2025-11-12 00:00:00',88.2,3),('2025-11-12 00:30:00',77.2,3),('2025-11-12 01:02:00',69.8,3),('2025-11-12 01:25:00',65.1,3),('2025-11-12 02:02:00',58.2,3);
INSERT INTO `permissions`(`userID`,`roomID`,`view`) VALUES (1,1,1),(1,2,1),(1,3,1);
# other useful queries
SELECT reading, Timestamp FROM Readings WHERE `sensorID` = 1 ORDER BY `Timestamp` DESC LIMIT 10000;
# SELECT roomID FROM permissions WHERE `userID` = 1 AND `view` = 1 INNER JOIN Rooms ON `permissions`.`roomID` = `Rooms`.`ID`;
SELECT rooms.name, rooms.shortname from permissions INNER JOIN rooms ON permissions.`roomID` = rooms.`ID` WHERE permissions.`userID` = 1 AND permissions.`view` = 1;
SELECT rooms.`ID` from rooms WHERE rooms.shortname = '101';
SELECT devices.`ID` from devices LEFT JOIN rooms ON devices.`roomID` = rooms.ID WHERE rooms.shortname = '101';
SELECT types.`type_desc` from types LEFT JOIN devices ON types.`ID` = devices.`type` WHERE devices.`ID` = 1;
SELECT permissions.`view` FROM permissions LEFT JOIN rooms ON permissions.`roomID` = rooms.ID WHERE rooms.shortname = '101' AND `userID` = 1;

50
web.py Normal file
View File

@@ -0,0 +1,50 @@
from db_connect import DatabaseConnect
from flask import Flask, abort, session
from jinja2 import Template
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import logging
from os import sep
app = Flask(__name__)
db = DatabaseConnect()
@app.route("/")
def index():
avail_rooms = db.view_valid_rooms(1)
outtext = "<h1>Available rooms</h1><ul>"
if len(avail_rooms) == 0:
outtext += "<li>You have no rooms you can view</li>"
else:
for room in avail_rooms:
outtext += f"<li><a href=/room/{room[1]}>{room[0]}</li>"
outtext += "</ul>"
return outtext
@app.route('/room/<room_name>')
def room_page(room_name=None):
if not db.user_has_room_perms(1,room_name):
abort(403)
sensor_list = db.get_sensors_in_room(room_name)
fig = make_subplots(rows=1, cols=len(sensor_list))
for idx, sensorID in enumerate(sensor_list):
lst = [x for x in db.get_sensor_data(sensorID)]
fig.add_trace(
go.Scatter(
x = [x[0] for x in lst],
y = [x[1] for x in lst],
name=db.get_sensor_type(sensorID)),
row = 1,
col = idx + 1
)
fig.update_layout(title_text=f"Available Devices in room {room_name}:")
template_path = f'web{sep}room_template.html'
px_jinja_data = {"fig":fig.to_html(full_html=False)}
with open(template_path,'r') as template_file:
j2_template = Template(template_file.read())
return j2_template.render(px_jinja_data)

118
web/index.html.jinja Normal file
View File

@@ -0,0 +1,118 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
<script>
function tableSearch(){
var table, input, tr, td, row_content;
table = document.getElementById("tableRooms");
input = document.getElementById("tableRoomSearch").value.toUpperCase();
tr = table.getElementsByTagName("tr");
for (let i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if(td){
row_content = td.textContent || td.innerText;
if (row_content.toUpperCase().indexOf(input) > -1) {
tr[i].style.display = "";
}
else{
tr[i].style.display ="none";
}
}
}
}
</script>
<title>{{ Pagetitle }}</title>
</head>
<body>
<div class="main">
<div class="navbar">
<div class="topbranding">{{ topbranding }}</div>
<div class="navbar-inner">
<b><a href="index.html">Home</a></b><br>
<i class="bi bi-arrow-down-square-fill">&nbsp;</i>Rooms<br>
<!--{%- for item in rooms %}
&emsp;<a href="{{ item[0] }}">{{ item[1] }}</a>{% if not loop.last %},{% endif %}
{%- endfor %}-->
<hr>
<!--{%- if user.device_privileges % and so on}-->
<a href="device.html">Device Management</a><br>
<a href="users.html">User Management</a>
</div>
</div>
<div class="content">
<div class="topline">
<div class="user section"> {{ user }}</div>
<div class="logout section"> <a href="logout">
Logout <i class="bi bi-power"></i>
</a></div>
</div>
<div class="main-content">
<p> {{ user_greeting }}</p>
<p> {{ ladning_information }}</p>
<div class="rooms-table">
<table>
<thead>
<tr class="table-header">
<th class="room-table-elem">Room name:</th>
<th>Temperature</th>
<th>Humidity</th>
</tr>
<tr class="searchbar">
<td colspan="255">
<i class="bi bi-search"></i>&nbsp;
<input type="text" id="tableRoomSearch" placeholder="Search by room name..." onkeyup="tableSearch()">
</td>
</tr>
</thead>
<tbody id="tableRooms">
<tr>
<!--
possible actual implementation of templating here:
<td><a href="./room/{{ room.shortlink }}>{{ room.name }}</a>"
{%- for data in room_data %}
<td class="
{%- if data.valid %}
data-valid
{%- elif data.late %}
data-late
{%- elif data.missing %}
data-missing
">
data.print()
</td>
{%- endfor %}
-->
<td class="room-table-elem"><a href="./room/101">Room 1</a></td>
<td>24°</td>
<td>52%</td>
</tr>
<tr>
<td class="room-table-elem"><a href="101">Room 2</a></td>
<td>27°</td>
<td>38%</td>
</tr>
<tr>
<td class="room-table-elem"><a href="101">Room 3</a></td>
<td>27°</td>
<td class="missing-data"></td>
</tr>
<tr>
<td class="room-table-elem"><a href="101">Room 4</a></td>
<td>27°</td>
<!--TODO: insert tooltip on late data-->
<td class="late-data"> 51%</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>

24
web/room_template.html Normal file
View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" /> <!--It is necessary to use the UTF-8 encoding with plotly graphics to get e.g. negative signs to render correctly -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<h1>Here's a Plotly graph!</h1>
{{ fig }}
<p>And here's some text after the graph.</p>
</body>
</html>

91
web/styles.css Normal file
View File

@@ -0,0 +1,91 @@
*{
font-family: sans-serif;
}
a{
text-decoration: none;
}
.main{
display: flex;
flex-direction: row;
}
.navbar{
flex: 1 10vw;
white-space: nowrap;
}
.topbranding, .navbar-inner, .topline{
font-weight: bold;
border: solid 0.2em;
padding-left: 0.5em;
padding-right: 0.5em;
padding-bottom: 0.25em;
padding-top: 0.25em;
}
.navbar-inner{
font-weight: normal;
}
.content{
flex: 1 60vw;
}
.topline{
display: flex;
}
.section{
flex: 1;
}
.logout{
text-align: right;
}
.main-content{
padding-left: 1em;
}
.rooms-table{
background-color: lightgray;
padding: 0.5em 1.5em;
width: min-content;
}
.rooms-table table{
width: 50vw;
background-color: inherit;
text-align: center;
border-color: darkgray;
border-collapse: collapse;
border-left: 10px;
}
.rooms-table tr{
padding-left: 1em;
}
.rooms-table td{
padding-bottom: 0.2em;
padding-top: 0.2em;
}
thead{
border-bottom: 0.25em darkgray solid;
}
tbody tr{
border-bottom: 0.1em darkgray solid;
}
.missing-data{
background-color: gray;
}
.late-data{
background-color: orange;
}
.room-table-elem, .searchbar{
font-weight: bold;
text-align: left;
}
.rooms-table input{
width: 90%;
}