This commit is contained in:
Your Name
2025-05-26 17:42:29 +02:00
parent 4fc06ccce0
commit cd8cf349dd
9 changed files with 1207 additions and 295 deletions

View File

@@ -105,15 +105,6 @@ from datetime import datetime
# Record the start time of the script
start_time_script = time.time()
# Check system uptime
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
# Skip execution if uptime is less than 2 minutes (120 seconds)
if uptime_seconds < 120:
print(f"System just booted ({uptime_seconds:.2f} seconds uptime), skipping execution.")
sys.exit()
#Payload CSV to be sent to data.moduleair.fr
payload_csv = [None] * 25
#Payload JSON to be sent to uSpot
@@ -131,6 +122,50 @@ uSpot_profile_id = 1
conn = sqlite3.connect("/var/www/moduleair_pro_4g/sqlite/sensors.db")
cursor = conn.cursor()
def update_config_sqlite(key, value, value_type=None):
"""
Update or insert a configuration value in SQLite config table
Args:
key (str): Configuration key
value: Configuration value (any type)
value_type (str, optional): Force specific type ('str', 'int', 'float', 'bool')
If None, auto-detect from value type
Returns:
bool: True if successful, False otherwise
"""
try:
# Auto-detect type if not specified
if value_type is None:
if isinstance(value, bool):
value_type = 'bool'
elif isinstance(value, int):
value_type = 'int'
elif isinstance(value, float):
value_type = 'float'
else:
value_type = 'str'
# Convert value to string for storage
if value_type == 'bool':
str_value = '1' if value else '0'
else:
str_value = str(value)
# Use INSERT OR REPLACE to update existing or create new
cursor.execute("""
INSERT OR REPLACE INTO config_table (key, value, type)
VALUES (?, ?, ?)
""", (key, str_value, value_type))
conn.commit()
print(f"✓ Config updated: {key} = {value} ({value_type})")
return True
except Exception as e:
print(f"✗ Error updating config {key}: {e}")
return False
#get config data from SQLite table
def load_config_sqlite():
@@ -165,32 +200,7 @@ def load_config_sqlite():
print(f"Error loading config from SQLite: {e}")
return {}
def load_config_scripts_sqlite():
"""
Load script configuration data from SQLite config_scripts_table
Returns:
dict: Script paths as keys and enabled status as boolean values
"""
try:
# Query the config_scripts_table
cursor.execute("SELECT script_path, enabled FROM config_scripts_table")
rows = cursor.fetchall()
# Create config dictionary with script paths as keys and enabled status as boolean values
scripts_config = {}
for script_path, enabled in rows:
# Convert integer enabled value (0/1) to boolean
scripts_config[script_path] = bool(enabled)
return scripts_config
except Exception as e:
print(f"Error loading scripts config from SQLite: {e}")
return {}
# Define the config file path
config_file = '/var/www/moduleair_pro_4g/config.json'
#Load config
config = load_config_sqlite()
@@ -205,16 +215,12 @@ Sara_baudrate = config.get('SaraR4_baudrate', 115200)
npm_5channel = config.get('npm_5channel', False) #5 canaux du NPM
selected_networkID = int(config.get('SARA_R4_neworkID', 0))
send_uSpot = config.get('send_uSpot', False) #envoi sur MicroSpot ()
bme_280_config = config.get('BME280', False)
co2_mhz19= config.get('MH-Z19', False)
sensirion_sfa30= config.get('SFA30', False)
reset_uSpot_url = False
#config_scripts
config_scripts = load_config_scripts_sqlite()
bme_280_config = config_scripts.get('BME280/get_data_v2.py', False)
envea_cairsens= config_scripts.get('envea/read_value_v2.py', False)
co2_mhz19= config_scripts.get('MH-Z19/write_data.py', False)
sensirion_sfa30= config_scripts.get('sensirion/SFA30_read.py', False)
#update device id in the payload json
payload_json["moduleairid"] = device_id
@@ -461,6 +467,16 @@ try:
'''
print('<h3>START LOOP</h3>')
# Check system uptime
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
# Skip execution if uptime is less than 2 minutes (120 seconds)
if uptime_seconds < 120:
print(f"System just booted ({uptime_seconds:.2f} seconds uptime), skipping execution.")
update_config_sqlite('SARA_network_status', 'booting')
sys.exit()
#Local timestamp
cursor.execute("SELECT * FROM timestamp_table LIMIT 1")
row = cursor.fetchone() # Get the first (and only) row
@@ -561,34 +577,7 @@ try:
else:
print("No data available in the database.")
#envea
if envea_cairsens:
print("Getting envea cairsens values")
cursor.execute("SELECT * FROM data_envea ORDER BY timestamp DESC LIMIT 6")
rows = cursor.fetchall()
# Exclude the timestamp column (assuming first column is timestamp)
data_values = [row[1:] for row in rows] # Exclude timestamp
# Compute column-wise average, ignoring 0 values
averages = []
for col in zip(*data_values): # Iterate column-wise
filtered_values = [val for val in col if val != 0] # Remove zeros
if filtered_values:
avg = round(sum(filtered_values) / len(filtered_values)) # Compute average
else:
avg = 0 # If all values were zero, store 0
averages.append(avg)
# Store averages in specific indices
payload_csv[9] = averages[0] # envea_no2
payload_csv[10] = averages[1] # envea_h2s
payload_csv[11] = averages[2] # envea_nh3
#Add data to payload JSON
payload_json["sensordatavalues"].append({"value_type": "CAIRSENS_NO2", "value": str(averages[0])})
payload_json["sensordatavalues"].append({"value_type": "CAIRSENS_NO2", "value": str(averages[1])})
payload_json["sensordatavalues"].append({"value_type": "CAIRSENS_NH3", "value": str(averages[2])})
#print("Verify SARA R4 connection")
# Getting the LTE Signal
@@ -662,6 +651,9 @@ try:
# On vérifie si le signal n'est pas à 99 pour déconnexion
# si c'est le cas on essaie de se reconnecter
if signal_quality == 99:
update_config_sqlite('SARA_network_status', 'disconnected')
update_config_sqlite('SARA_signal_quality', '99')
print('<span style="color: red;font-weight: bold;">⚠ATTENTION: Signal Quality indicates no signal (99)⚠️</span>')
print("TRY TO RECONNECT:")
command = f'AT+COPS=1,2,"{selected_networkID}"\r'
@@ -678,6 +670,8 @@ try:
sys.exit()
else:
print("Signal Quality:", signal_quality)
update_config_sqlite('SARA_signal_quality', signal_quality)
'''
@@ -776,7 +770,8 @@ try:
print("*****")
print('<span style="color: red;font-weight: bold;">ATTENTION: HTTP operation failed</span>')
print("*****")
update_config_sqlite('SARA_network_status', 'error')
# Get error code
print("Getting error code")
@@ -838,6 +833,8 @@ try:
# Si la commande HTTP a réussi
print('<span class="badge text-bg-success">✅✅HTTP operation successful.</span>')
#update SARA_network_status
update_config_sqlite('SARA_network_status', 'connected')
#4. Read reply from server
print("Reply from server:")