diff --git a/SARA/reboot/start.py b/SARA/reboot/start.py
index 7655a7c..27e3e4c 100644
--- a/SARA/reboot/start.py
+++ b/SARA/reboot/start.py
@@ -17,15 +17,43 @@ import time
import sys
import json
import re
+import sqlite3
-#get data from config
-def load_config(config_file):
+# database connection
+conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db")
+cursor = conn.cursor()
+
+#get config data from SQLite table
+def load_config_sqlite():
+ """
+ Load configuration data from SQLite config table
+
+ Returns:
+ dict: Configuration data with proper type conversion
+ """
try:
- with open(config_file, 'r') as file:
- config_data = json.load(file)
+
+ # Query the config table
+ cursor.execute("SELECT key, value, type FROM config_table")
+ rows = cursor.fetchall()
+
+ # Create config dictionary
+ config_data = {}
+ for key, value, type_name in rows:
+ # Convert value based on its type
+ if type_name == 'bool':
+ config_data[key] = value == '1' or value == 'true'
+ elif type_name == 'int':
+ config_data[key] = int(value)
+ elif type_name == 'float':
+ config_data[key] = float(value)
+ else:
+ config_data[key] = value
+
return config_data
+
except Exception as e:
- print(f"Error loading config file: {e}")
+ print(f"Error loading config from SQLite: {e}")
return {}
#Fonction pour mettre à jour le JSON de configuration
@@ -57,10 +85,55 @@ def update_json_key(file_path, key, value):
except Exception as e:
print(f"Error updating the JSON file: {e}")
-# Define the config file path
-config_file = '/var/www/nebuleair_pro_4g/config.json'
-# Load the configuration data
-config = load_config(config_file)
+
+def update_sqlite_config(key, value):
+ """
+ Updates a specific key in the SQLite config_table with a new value.
+
+ :param key: The key to update in the config_table.
+ :param value: The new value to assign to the key.
+ """
+ try:
+
+ # Check if the key exists and get its type
+ cursor.execute("SELECT type FROM config_table WHERE key = ?", (key,))
+ result = cursor.fetchone()
+
+ if result is None:
+ print(f"Key '{key}' not found in the config_table.")
+ conn.close()
+ return
+
+ # Get the type of the value from the database
+ value_type = result[0]
+
+ # Convert the value to the appropriate string representation based on its type
+ if value_type == 'bool':
+ # Convert Python boolean or string 'true'/'false' to '1'/'0'
+ if isinstance(value, bool):
+ str_value = '1' if value else '0'
+ else:
+ str_value = '1' if str(value).lower() in ('true', '1', 'yes', 'y') else '0'
+ elif value_type == 'int':
+ str_value = str(int(value))
+ elif value_type == 'float':
+ str_value = str(float(value))
+ else:
+ str_value = str(value)
+
+ # Update the value in the database
+ cursor.execute("UPDATE config_table SET value = ? WHERE key = ?", (str_value, key))
+
+ # Commit the changes and close the connection
+ conn.commit()
+
+ print(f"💾 Updated '{key}' to '{value}' in database.")
+ except Exception as e:
+ print(f"Error updating the SQLite database: {e}")
+
+#Load config
+config = load_config_sqlite()
+#config
baudrate = config.get('SaraR4_baudrate', 115200) #baudrate du sara R4
device_id = config.get('deviceID', '').upper() #device ID en maj
@@ -151,7 +224,7 @@ try:
print("⚠️ Could not identify modem model")
print(f"🔍 Model: {model}")
- update_json_key(config_file, "modem_version", model)
+ update_sqlite_config("modem_version", model)
time.sleep(1)
'''
@@ -332,9 +405,9 @@ try:
else:
print("❌ Failed to extract coordinates.")
- #update config.json
- update_json_key(config_file, "latitude_raw", float(latitude))
- update_json_key(config_file, "longitude_raw", float(longitude))
+ #update sqlite table
+ update_sqlite_config("latitude_raw", float(latitude))
+ update_sqlite_config("longitude_raw", float(longitude))
time.sleep(1)
diff --git a/boot_hotspot.sh b/boot_hotspot.sh
index a75dba6..4bc85d8 100755
--- a/boot_hotspot.sh
+++ b/boot_hotspot.sh
@@ -2,6 +2,8 @@
# Script to check if wifi is connected and start hotspot if not
# will also retreive unique RPi ID and store it to deviceID.txt
+# script that starts at boot:
+# @reboot /var/www/nebuleair_pro_4g/boot_hotspot.sh >> /var/www/nebuleair_pro_4g/logs/app.log 2>&1
OUTPUT_FILE="/var/www/nebuleair_pro_4g/wifi_list.csv"
JSON_FILE="/var/www/nebuleair_pro_4g/config.json"
@@ -30,8 +32,7 @@ done
echo "getting RPI serial number"
# Get the last 8 characters of the serial number and write to text file
serial_number=$(cat /proc/cpuinfo | grep Serial | awk '{print substr($3, length($3) - 7)}')
-# Use jq to update the "deviceID" in the JSON file
-#jq --arg serial_number "$serial_number" '.deviceID = $serial_number' "$JSON_FILE" > temp.json && mv temp.json "$JSON_FILE"
+
# update Sqlite database
echo "Updating SQLite database with device ID: $serial_number"
sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='$serial_number' WHERE key='deviceID';"
@@ -39,8 +40,8 @@ sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET val
echo "id: $serial_number"
-#get the SSH port for tunneling
-SSH_TUNNEL_PORT=$(jq -r '.sshTunnel_port' "$JSON_FILE")
+# Get SSH tunnel port from SQLite config_table
+SSH_TUNNEL_PORT=$(sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "SELECT value FROM config_table WHERE key='sshTunnel_port'")
#need to wait for the network manager to be ready
sleep 20
@@ -58,17 +59,16 @@ if [ "$STATE" == "30 (disconnected)" ]; then
echo "Starting hotspot..."
sudo nmcli device wifi hotspot ifname wlan0 ssid nebuleair_pro password nebuleaircfg
- # Update JSON to reflect hotspot mode
- jq --arg status "hotspot" '.WIFI_status = $status' "$JSON_FILE" > temp.json && mv temp.json "$JSON_FILE"
-
+ # Update SQLite to reflect hotspot mode
+ sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='hotspot' WHERE key='WIFI_status'"
else
echo "🛜Success: wlan0 is connected!🛜"
CONN_SSID=$(nmcli -g GENERAL.CONNECTION device show wlan0)
echo "Connection: $CONN_SSID"
- #update config JSON file
- jq --arg status "connected" '.WIFI_status = $status' "$JSON_FILE" > temp.json && mv temp.json "$JSON_FILE"
+ # Update SQLite to reflect hotspot mode
+ sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='connected' WHERE key='WIFI_status'"
sudo chmod 777 "$JSON_FILE"
diff --git a/html/admin.html b/html/admin.html
index b643767..a237e92 100755
--- a/html/admin.html
+++ b/html/admin.html
@@ -114,6 +114,10 @@
+
+ ❌ Error: unable to get data from sensor.
+ ${status}: ${error}
+
+
+ `;
}
+ });
+}
+
function getNoise_values(){
console.log("Data from I2C Noise Sensor:");
@@ -261,143 +271,190 @@ function getBME280_values(){
window.onload = function() {
- fetch('../config.json') // Replace 'deviceID.txt' with 'config.json'
- .then(response => response.json()) // Parse response as JSON
- .then(data => {
- //get device ID
- const deviceID = data.deviceID.trim().toUpperCase();
- //document.getElementById('pageTitle_plus_ID').innerText = 'token: ' + deviceID;
- //get device Name
- const deviceName = data.deviceName;
-
- const elements = document.querySelectorAll('.sideBar_sensorName');
- elements.forEach((element) => {
- element.innerText = deviceName;
- });
+
+ //NEW way to get config (SQLite)
+$.ajax({
+ url: 'launcher.php?type=get_config_sqlite',
+ dataType:'json',
+ //dataType: 'json', // Specify that you expect a JSON response
+ method: 'GET', // Use GET or POST depending on your needs
+ success: function(response) {
+ console.log("Getting SQLite config table:");
+ console.log(response);
+
+
+ //device name_side bar
+ const elements = document.querySelectorAll('.sideBar_sensorName');
+ elements.forEach((element) => {
+ element.innerText = response.deviceName;
+ });
+
+ },
+error: function(xhr, status, error) {
+ console.error('AJAX request failed:', status, error);
+}
+ });//end AJAX
+
+ //getting config_scripts table
+ $.ajax({
+ url: 'launcher.php?type=get_config_scripts_sqlite',
+ dataType:'json',
+ //dataType: 'json', // Specify that you expect a JSON response
+ method: 'GET', // Use GET or POST depending on your needs
+ success: function(response) {
+ console.log("Getting SQLite config scripts table:");
+ console.log(response);
+
+ const container = document.getElementById('card-container'); // Conteneur des cartes
+
+ //creates NPM card
+ if (response["NPM/get_data_modbus_v3.py"]) {
+ const cardHTML = `
+
+
+
+ Port UART
+
+
+
NextPM
+
Capteur particules fines.
+
+
+
+
+
+
+
+
+
`;
+
+ container.innerHTML += cardHTML; // Add the I2C card if condition is met
+ }
+
+ //creates i2c BME280 card
+ if (response["BME280/get_data_v2.py"]) {
+ const i2C_BME_HTML = `
+
+
+
+ Port I2C
+
+
+
BME280 Temp/Hum sensor
+
Capteur température et humidité sur le port I2C.
+
+
+
+
+
+
+
+
+
`;
+
+ container.innerHTML += i2C_BME_HTML; // Add the I2C card if condition is met
+ }
+
+ //creates i2c sound card
+ if (response.i2C_sound) {
+ const i2C_HTML = `
+
+
+
+ Port I2C
+
+
+
Decibel Meter
+
Capteur bruit sur le port I2C.
+
+
+
+
+
+
+
+
+
+
+
`;
+
+ container.innerHTML += i2C_HTML; // Add the I2C card if condition is met
+ }
+
+ //Si on a des SONDES ENVEA connectée il faut faire un deuxième call dans la table envea_sondes_table
+ //creates ENVEA cards
+ if (response["envea/read_value_v2.py"]) {
+ console.log("Need to display ENVEA sondes");
+ //getting config_scripts table
+ $.ajax({
+ url: 'launcher.php?type=get_envea_sondes_table_sqlite',
+ dataType:'json',
+ //dataType: 'json', // Specify that you expect a JSON response
+ method: 'GET', // Use GET or POST depending on your needs
+ success: function(sondes) {
+ console.log("Getting SQLite envea sondes table:");
+ console.log(sondes);
+ const ENVEA_sensors = sondes.filter(sonde => sonde.connected); // Filter only connected sondes
+
+ ENVEA_sensors.forEach((sensor, index) => {
+ const port = sensor.port; // Port from the sensor object
+ const name = sensor.name; // Port from the sensor object
+ const coefficient = sensor.coefficient;
+ const cardHTML = `
+
+
+
+ Port UART ${port.replace('ttyAMA', '')}
+
+
+
Sonde Envea ${name}
+
Capteur gas.
+
+
+
+
+
+
+
+
`;
+ container.innerHTML += cardHTML; // Ajouter la carte au conteneur
+ });
+
+ },
+ error: function(xhr, status, error) {
+ console.error('AJAX request failed:', status, error);
+ }
+ });//end AJAX envea Sondes
- //get local RTC
- $.ajax({
- url: 'launcher.php?type=RTC_time',
- dataType: 'text', // Specify that you expect a JSON response
- method: 'GET', // Use GET or POST depending on your needs
- success: function(response) {
- console.log("Local RTC: " + response);
- const RTC_Element = document.getElementById("RTC_time");
- RTC_Element.textContent = response;
- },
- error: function(xhr, status, error) {
- console.error('AJAX request failed:', status, error);
- }
- });
+ }//end if
+
- const container = document.getElementById('card-container'); // Conteneur des cartes
-
- //creates NPM cards
- const NPM_ports = data.NextPM_ports; // Récupère les ports
- NPM_ports.forEach((port, index) => {
- const cardHTML = `
-
-
-
- Port UART ${port.replace('ttyAMA', '')}
-
-
-
NextPM ${String.fromCharCode(65 + index)}
-
Capteur particules fines.
-
-
-
-
-
-
-
-
`;
- container.innerHTML += cardHTML; // Ajouter la carte au conteneur
- });
+},
+ error: function(xhr, status, error) {
+ console.error('AJAX request failed:', status, error);
+ }
+ });//end AJAX (config_scripts)
- //creates ENVEA cards
- const ENVEA_sensors = data.envea_sondes.filter(sonde => sonde.connected); // Filter only connected sondes
+ //get local RTC
+ $.ajax({
+ url: 'launcher.php?type=RTC_time',
+ dataType: 'text', // Specify that you expect a JSON response
+ method: 'GET', // Use GET or POST depending on your needs
+ success: function(response) {
+ console.log("Local RTC: " + response);
+ const RTC_Element = document.getElementById("RTC_time");
+ RTC_Element.textContent = response;
- ENVEA_sensors.forEach((sensor, index) => {
- const port = sensor.port; // Port from the sensor object
- const name = sensor.name; // Port from the sensor object
- const coefficient = sensor.coefficient;
- const cardHTML = `
-