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
from env import *
from flask import Flask, render_template, request
from flask import Flask, redirect, render_template, request
import sqlite3
from database import *
app = Flask(__name__)
@ -38,15 +38,17 @@ def fetch_outdoor_temperature():
# Appel de la fonction pour obtenir la température
temperature = fetch_outdoor_temperature()
print(temperature)
#temperature = fetch_outdoor_temperature()
#print(temperature)
# Route to display the database contents
@app.route('/')
def dashboard():
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
@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])
@app.route('/adm', methods=['GET', 'POST'])
@app.route('/adm', methods=['GET'])
def admin():
if request.method == 'POST':
# Get form data
# Fetch sensor data
data = fetch_all_sensor()
# 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 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()
update_sensor_settings(new_name, old_name)
data = fetch_all_sensor()
print(data)
return render_template('admin.html', data=data, sensors=data)
return redirect("/adm")
def run_flask():
app.run()

View File

@ -3,7 +3,7 @@ import sqlite3
from os import path
import time
from env import SENSORS, DBFILE
from env import *
# Function to create the database and tables if they don't exist
def create_database(db_name):
@ -14,7 +14,9 @@ def create_database(db_name):
c.execute('''CREATE TABLE IF NOT EXISTS Sensors
(Mac TEXT PRIMARY KEY,
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
c.execute('''CREATE TABLE IF NOT EXISTS SensorData
(Id INTEGER PRIMARY KEY AUTOINCREMENT,
@ -25,14 +27,15 @@ def create_database(db_name):
Bat INT,
FOREIGN KEY (Sensor) REFERENCES Sensors(Name))''')
c.execute('''CREATE TABLE IF NOT EXISTS Settings
(Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT,
Value TEXT''')
c.execute('''CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY,
smtp_id 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()
@ -87,3 +90,54 @@ def fetch_all_sensor():
conn.close()
data.reverse()
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
import sqlite3
import threading
import schedule
from env import *
from database import fetch_email_settings
MESSAGE_TEMP = """
@ -33,10 +32,13 @@ def email(recipient_email, message, ReachedVal, Sensor, TimeStamp):
- The sensor on wich the values are maxed out
- the time stamp
"""
port = SMTP_PORT # For SSL
""" port = SMTP_PORT # For SSL
smtp_server = SMTP
sender_email = SMTP_ID # Enter your address
password = SMTP_PWD
password = SMTP_PWD """
print(fetch_email_settings())
sender_email, password, smtp_server, port, recipient_email = fetch_email_settings()
# Create a MIME message
msg = MIMEMultipart()
msg['From'] = sender_email
@ -49,7 +51,7 @@ def email(recipient_email, message, ReachedVal, Sensor, TimeStamp):
try:
# Start a TLS encrypted connection
server = smtplib.SMTP(smtp_server, port)
server = smtplib.SMTP(smtp_server, int(port))
server.starttls()
# Login to the SMTP server

View File

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

View File

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

View File

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

View File

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