This commit is contained in:
Your Name
2025-03-04 10:06:26 +01:00
parent 709cad6981
commit cd030a9e14
3 changed files with 85 additions and 39 deletions

View File

@@ -9,6 +9,35 @@ Script to read time from RTC module and save it to DB
I2C connection
Address 0x68
/usr/bin/python3 /var/www/nebuleair_pro_4g/RTC/save_to_db.py
This need to be run as a system service
--> sudo nano /etc/systemd/system/rtc_save_to_db.service
⬇️
[Unit]
Description=RTC Save to DB Script
After=network.target
[Service]
ExecStart=/usr/bin/python3 /var/www/nebuleair_pro_4g/RTC/save_to_db.py
Restart=always
RestartSec=1
User=root
WorkingDirectory=/var/www/nebuleair_pro_4g
StandardOutput=append:/var/www/nebuleair_pro_4g/logs/rtc_save_to_db.log
StandardError=append:/var/www/nebuleair_pro_4g/logs/rtc_save_to_db_errors.log
[Install]
WantedBy=multi-user.target
⬆️
sudo systemctl daemon-reload
sudo systemctl start rtc_save_to_db.service
sudo systemctl status rtc_save_to_db.service
'''
import smbus2
import time
@@ -16,16 +45,15 @@ import json
from datetime import datetime
import sqlite3
# Connect to (or create if not existent) the database
conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db")
cursor = conn.cursor()
# DS3231 I2C address
DS3231_ADDR = 0x68
# Registers for DS3231
REG_TIME = 0x00
# Connect to (or create if not existent) the database
DB_PATH = "/var/www/nebuleair_pro_4g/sqlite/sensors.db"
def bcd_to_dec(bcd):
return (bcd // 16 * 10) + (bcd % 16)
@@ -46,44 +74,53 @@ def read_time(bus):
def main():
# Read RTC time
bus = smbus2.SMBus(1)
# Try to read RTC time
rtc_time = read_time(bus)
# Get current system time
system_time = datetime.now() #local
utc_time = datetime.utcnow() #UTC
# If RTC is not connected, set default message
# Calculate time difference (in seconds) if RTC is connected
if rtc_time:
rtc_time_str = rtc_time.strftime('%Y-%m-%d %H:%M:%S')
time_difference = int((utc_time - rtc_time).total_seconds()) # Convert to int
else:
rtc_time_str = "not connected"
time_difference = "N/A" # Not applicable
while True:
# Open a new database connection inside the loop to prevent connection loss
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Print both times
#print(f"RTC module Time: {rtc_time.strftime('%Y-%m-%d %H:%M:%S')}")
#print(f"Sys local Time: {system_time.strftime('%Y-%m-%d %H:%M:%S')}")
#print(f"Sys UTC Time: {utc_time.strftime('%Y-%m-%d %H:%M:%S')}")
# Try to read RTC time
rtc_time = read_time(bus)
# Get current system time
system_time = datetime.now() #local
utc_time = datetime.utcnow() #UTC
# Create JSON output
time_data = {
"rtc_module_time":rtc_time_str,
"system_local_time": system_time.strftime('%Y-%m-%d %H:%M:%S'),
"system_utc_time": utc_time.strftime('%Y-%m-%d %H:%M:%S'),
"time_difference_seconds": time_difference
}
# If RTC is not connected, set default message
# Calculate time difference (in seconds) if RTC is connected
if rtc_time:
rtc_time_str = rtc_time.strftime('%Y-%m-%d %H:%M:%S')
time_difference = int((utc_time - rtc_time).total_seconds()) # Convert to int
else:
rtc_time_str = "not connected"
time_difference = "N/A" # Not applicable
#print(json.dumps(time_data, indent=4))
# Print both times
#print(f"RTC module Time: {rtc_time.strftime('%Y-%m-%d %H:%M:%S')}")
#print(f"Sys local Time: {system_time.strftime('%Y-%m-%d %H:%M:%S')}")
#print(f"Sys UTC Time: {utc_time.strftime('%Y-%m-%d %H:%M:%S')}")
cursor.execute("UPDATE timestamp_table SET last_updated = ? WHERE id = 1", (rtc_time_str,))
# Create JSON output
time_data = {
"rtc_module_time":rtc_time_str,
"system_local_time": system_time.strftime('%Y-%m-%d %H:%M:%S'),
"system_utc_time": utc_time.strftime('%Y-%m-%d %H:%M:%S'),
"time_difference_seconds": time_difference
}
# Commit and close the connection
conn.commit()
conn.close()
#print(json.dumps(time_data, indent=4))
#print("Sensor data saved successfully!")
# Save to database
try:
cursor.execute("UPDATE timestamp_table SET last_updated = ? WHERE id = 1", (rtc_time_str,))
conn.commit()
#print("Sensor data saved successfully!")
except sqlite3.Error as e:
print(f"Database error: {e}")
conn.close() # Close connection to avoid database locking issues
time.sleep(1) # Wait for 1 second before reading again
if __name__ == "__main__":

View File

@@ -54,7 +54,7 @@
<div class="row mb-3">
<div class="col-sm-4">
<div class="col-sm-5">
<div class="card text-dark bg-light">
<div class="card-body">
<h5 class="card-title">Consulter la base de donnée</h5>
@@ -71,12 +71,13 @@
<button class="btn btn-primary" onclick="get_data_sqlite('data_BME280',getSelectedLimit(),false)">Mesures Temp/Hum</button>
<button class="btn btn-primary" onclick="get_data_sqlite('data_NPM_5channels',getSelectedLimit(),false)">Mesures PM (5 canaux)</button>
<button class="btn btn-primary" onclick="get_data_sqlite('data_envea',getSelectedLimit(),false)">Sonde Cairsens</button>
<button class="btn btn-warning" onclick="get_data_sqlite('timestamp_table',getSelectedLimit(),false)">Timestamp Table</button>
</div>
</div>
</div>
<div class="col-sm-8">
<div class="col-sm-5">
<div class="card text-dark bg-light">
<div class="card-body">
<h5 class="card-title">Télécharger les données</h5>
@@ -255,6 +256,10 @@ function get_data_sqlite(table, limit, download , startDate = "", endDate = "")
<th>O3</th>
`;
}else if (table === "timestamp_table") {
tableHTML += `
<th>Timestamp</th>
`;
}
tableHTML += `</tr></thead><tbody>`;
@@ -301,6 +306,10 @@ function get_data_sqlite(table, limit, download , startDate = "", endDate = "")
<td>${columns[5]}</td>
`;
}else if (table === "timestamp_table") {
tableHTML += `
<td>${columns[1]}</td>
`;
}
tableHTML += "</tr>";

View File

@@ -13,7 +13,7 @@ Attention:
First time: need to create the service file
-->sudo nano /etc/systemd/system/master_nebuleair.service
--> sudo nano /etc/systemd/system/master_nebuleair.service
⬇️
[Unit]
@@ -81,7 +81,7 @@ def run_script(script_name, interval, delay=0):
# Define scripts and their execution intervals (seconds)
SCRIPTS = [
("RTC/save_to_db.py", 1, 0), # SAVE RTC time every 1 second, no delay
#("RTC/save_to_db.py", 1, 0), # SAVE RTC time every 1 second, no delay
("NPM/get_data_modbus_v3.py", 10, 0), # Get NPM data (modbus 5 channels) every 10s, with 2s delay
("envea/read_value_v2.py", 10, 0), # Get NPM data (modbus 5 channels) every 10s, with 2s delay
("loop/SARA_send_data_v2.py", 60, 1), # Send data every 60 seconds, with 2s delay