This commit is contained in:
jeanGaston 2024-05-02 02:54:48 +02:00
parent b424951980
commit a56ccaf14c
9 changed files with 135 additions and 46 deletions

View File

@ -4,7 +4,7 @@ import threading
import requests import requests
from env import * from env import *
from flask import Flask, render_template, request from flask import Flask, redirect, render_template, request
import sqlite3 import sqlite3
from database import * from database import *
app = Flask(__name__) app = Flask(__name__)
@ -38,15 +38,17 @@ def fetch_outdoor_temperature():
# Appel de la fonction pour obtenir la température # Appel de la fonction pour obtenir la température
temperature = fetch_outdoor_temperature() #temperature = fetch_outdoor_temperature()
print(temperature) #print(temperature)
# Route to display the database contents # Route to display the database contents
@app.route('/') @app.route('/')
def dashboard(): def dashboard():
data = fetch_all_data()[:5] data = fetch_all_data()[:5]
return render_template('index.html', data=data, temperature=temperature) return render_template('index.html', data=data, temperature=None)
#Route to display the sensor history #Route to display the sensor history
@app.route('/history') @app.route('/history')
@ -64,26 +66,40 @@ def history():
return render_template('history.html', S1=disp_data[0], S2=disp_data[1], S3=disp_data[2]) return render_template('history.html', S1=disp_data[0], S2=disp_data[1], S3=disp_data[2])
@app.route('/adm', methods=['GET', 'POST']) @app.route('/adm', methods=['GET'])
def admin(): def admin():
if request.method == 'POST':
# Get form data
old_name = request.form['old_name']
new_name = request.form['new_name']
# Update sensor name in the database
conn = sqlite3.connect(DBFILE)
c = conn.cursor()
print(old_name, new_name)
c.execute("UPDATE Sensors SET Name = ? WHERE mac = ?", (new_name, old_name))
print()
conn.commit()
conn.close()
# Fetch sensor data
data = fetch_all_sensor() data = fetch_all_sensor()
print(data)
return render_template('admin.html', data=data, sensors=data) # Fetch email settings
email_settings = fetch_email_settings()
return render_template('admin.html', data=data, sensors=data, email_settings=email_settings)
@app.route('/updateMail', methods=['POST'])
def update_mail():
# Process the form data here
smtp_id = request.form['smtp_id']
smtp_pwd = request.form['smtp_pwd']
smtp_server = request.form['smtp_server']
smtp_port = request.form['smtp_port']
recipient_email = request.form['recipient_email']
# Update email settings in the database or perform any other actions
update_email_settings(smtp_id, smtp_pwd, smtp_server, smtp_port, recipient_email)
# Redirect to a success page or render a template
return redirect("/adm")
@app.route('/updateSensor', methods=['POST'])
def updateSensor():
# Get sensor name form data
old_name = request.form['old_name']
new_name = request.form['new_name']
update_sensor_settings(new_name, old_name)
return redirect("/adm")
def run_flask(): def run_flask():
app.run() app.run()

View File

@ -3,7 +3,7 @@ import sqlite3
from os import path from os import path
import time import time
from env import SENSORS, DBFILE from env import *
# Function to create the database and tables if they don't exist # Function to create the database and tables if they don't exist
def create_database(db_name): def create_database(db_name):
@ -14,7 +14,9 @@ def create_database(db_name):
c.execute('''CREATE TABLE IF NOT EXISTS Sensors c.execute('''CREATE TABLE IF NOT EXISTS Sensors
(Mac TEXT PRIMARY KEY, (Mac TEXT PRIMARY KEY,
Name TEXT)''') Name TEXT)''')
for mac, name in SENSORS.items():
# Use INSERT OR IGNORE to prevent duplicates based on primary key
c.execute("INSERT OR IGNORE INTO Sensors (Mac, Name) VALUES (?, ?)", (mac, name))
# Create SensorData table # Create SensorData table
c.execute('''CREATE TABLE IF NOT EXISTS SensorData c.execute('''CREATE TABLE IF NOT EXISTS SensorData
(Id INTEGER PRIMARY KEY AUTOINCREMENT, (Id INTEGER PRIMARY KEY AUTOINCREMENT,
@ -25,14 +27,15 @@ def create_database(db_name):
Bat INT, Bat INT,
FOREIGN KEY (Sensor) REFERENCES Sensors(Name))''') FOREIGN KEY (Sensor) REFERENCES Sensors(Name))''')
c.execute('''CREATE TABLE IF NOT EXISTS Settings c.execute('''CREATE TABLE IF NOT EXISTS settings (
(Id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY,
Name TEXT, smtp_id TEXT,
Value TEXT''') smtp_pwd TEXT,
smtp_server TEXT,
smtp_port INTEGER,
recipient_email TEXT);''')
c.execute("INSERT OR IGNORE INTO settings (smtp_id, smtp_pwd, smtp_server, smtp_port, recipient_email) VALUES (?, ?, ?, ?, ?)", (SMTP_ID, SMTP_PWD, SMTP, SMTP_PORT, RECIPIENT))
for mac, name in SENSORS.items():
# Use INSERT OR IGNORE to prevent duplicates based on primary key
c.execute("INSERT OR IGNORE INTO Sensors (Mac, Name) VALUES (?, ?)", (mac, name))
conn.commit() conn.commit()
@ -87,3 +90,54 @@ def fetch_all_sensor():
conn.close() conn.close()
data.reverse() data.reverse()
return data return data
def update_sensor_settings(new_name, old_name):
# Update sensor name in the database
conn = sqlite3.connect(DBFILE)
c = conn.cursor()
c.execute("UPDATE Sensors SET Name = ? WHERE mac = ?", (new_name, old_name))
conn.commit()
conn.close()
# Function to fetch email settings from the database
def fetch_email_settings():
conn = sqlite3.connect(DBFILE)
c = conn.cursor()
c.execute("SELECT smtp_id, smtp_pwd, smtp_server, smtp_port, recipient_email FROM settings")
settings = c.fetchone()
conn.close()
return settings
# Function to update email settings in the database
def update_email_settings(smtp_id, smtp_pwd, smtp_server, smtp_port, recipient_email):
conn = sqlite3.connect(DBFILE)
c = conn.cursor()
c.execute("UPDATE settings SET smtp_id = ?, smtp_pwd = ?, smtp_server = ?, smtp_port = ?, recipient_email = ? ", (smtp_id, smtp_pwd, smtp_server, smtp_port, recipient_email))
conn.commit()
print(f"[{datetime.now()}] Mail settings updated :")
print_email_settings()
conn.close()
def print_email_settings():
# Connect to the database
conn = sqlite3.connect(DBFILE)
c = conn.cursor()
# Fetch email settings
c.execute("SELECT * FROM settings")
settings = c.fetchone()
# Print settings
if settings:
print("Email Settings:")
print(f"Sender Email: {settings[1]}")
print(f"SMTP pwd:{settings[2]}")
print(f"SMTP Server: {settings[3]}")
print(f"SMTP Port: {settings[4]}")
print(f"Recipient Email: {settings[5]}")
else:
print("No email settings found in the database.")
# Close the connection
conn.close()

View File

@ -3,10 +3,9 @@ from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
import sqlite3 import sqlite3
import threading import threading
import schedule import schedule
from env import * from env import *
from database import fetch_email_settings
MESSAGE_TEMP = """ MESSAGE_TEMP = """
@ -33,11 +32,14 @@ def email(recipient_email, message, ReachedVal, Sensor, TimeStamp):
- The sensor on wich the values are maxed out - The sensor on wich the values are maxed out
- the time stamp - the time stamp
""" """
port = SMTP_PORT # For SSL """ port = SMTP_PORT # For SSL
smtp_server = SMTP smtp_server = SMTP
sender_email = SMTP_ID # Enter your address sender_email = SMTP_ID # Enter your address
password = SMTP_PWD password = SMTP_PWD """
# Create a MIME message print(fetch_email_settings())
sender_email, password, smtp_server, port, recipient_email = fetch_email_settings()
# Create a MIME message
msg = MIMEMultipart() msg = MIMEMultipart()
msg['From'] = sender_email msg['From'] = sender_email
msg['To'] = recipient_email msg['To'] = recipient_email
@ -49,7 +51,7 @@ def email(recipient_email, message, ReachedVal, Sensor, TimeStamp):
try: try:
# Start a TLS encrypted connection # Start a TLS encrypted connection
server = smtplib.SMTP(smtp_server, port) server = smtplib.SMTP(smtp_server, int(port))
server.starttls() server.starttls()
# Login to the SMTP server # Login to the SMTP server

View File

@ -9,6 +9,7 @@ check_database(DBFILE)
RunInThread_WebServer() RunInThread_WebServer()
ScheduleDataScrap() ScheduleDataScrap()
ScheduleMailAlerts() ScheduleMailAlerts()
#print_email_settings()
while True: while True:

View File

@ -75,8 +75,9 @@
</head> </head>
<body> <body>
<div class="btn-container"> <div class="btn-container">
<a href="/history" class="btn">View History</a>
<a href="/" class="btn">Dashboard</a> <a href="/" class="btn">Dashboard</a>
<a href="/history" class="btn">View History</a>
<a href="/adm" class="btn">Admin</a>
</div> </div>
<div class="container"> <div class="container">
<h1>Sensors</h1> <h1>Sensors</h1>
@ -98,7 +99,7 @@
</table> </table>
</div> </div>
<h1>Rename Sensor</h1> <h1>Rename Sensor</h1>
<form method="post"> <form action="/updateSensor" method="post">
<label for="old_name">Select sensor to rename:</label> <label for="old_name">Select sensor to rename:</label>
<select name="old_name" id="old_name"> <select name="old_name" id="old_name">
{% for sensor in sensors %} {% for sensor in sensors %}
@ -111,11 +112,24 @@
<br><br> <br><br>
<button type="submit">Rename Sensor</button> <button type="submit">Rename Sensor</button>
</form> </form>
<script> <h1>Email Settings</h1>
// Refresh the page every 10 seconds <form method="post" action="/updateMail">
setTimeout(function(){ <label for="smtp_id">Sender Email:</label>
location.reload(); <input type="email" id="smtp_id" name="smtp_id" value="{{ email_settings[0] }}">
}, 20000); <br><br>
</script> <label for="smtp_pwd">Sender Password:</label>
<input type="password" id="smtp_pwd" name="smtp_pwd" value="{{ email_settings[1] }}">
<br><br>
<label for="smtp_server">SMTP Server:</label>
<input type="text" id="smtp_server" name="smtp_server" value="{{ email_settings[2] }}">
<br><br>
<label for="smtp_port">SMTP Port:</label>
<input type="number" id="smtp_port" name="smtp_port" value="{{ email_settings[3] }}">
<br><br>
<label for="recipient_email">Recipient Email:</label>
<input type="email" id="recipient_email" name="recipient_email" value="{{ email_settings[4] }}">
<br><br>
<button type="submit">Save Settings</button>
</form>
</body> </body>
</html> </html>

View File

@ -55,8 +55,9 @@ tr:hover {
</head> </head>
<body> <body>
<div class="btn-container"> <div class="btn-container">
<a href="/adm" class="btn">Admin</a>
<a href="/" class="btn">Dashboard</a> <a href="/" class="btn">Dashboard</a>
<a href="/history" class="btn">View History</a>
<a href="/adm" class="btn">Admin</a>
</div> </div>
<h1>Database Contents</h1> <h1>Database Contents</h1>
<h2>Sensor 1</h2> <h2>Sensor 1</h2>

View File

@ -52,6 +52,7 @@
</head> </head>
<body> <body>
<div class="btn-container"> <div class="btn-container">
<a href="/" class="btn">Dashboard</a>
<a href="/history" class="btn">View History</a> <a href="/history" class="btn">View History</a>
<a href="/adm" class="btn">Admin</a> <a href="/adm" class="btn">Admin</a>
</div> </div>