add sqlite config management

This commit is contained in:
Your Name
2025-03-24 15:19:27 +01:00
parent 6b3329b9b8
commit b7a6f4c907
4 changed files with 573 additions and 141 deletions

View File

@@ -69,27 +69,51 @@
<input type="text" class="form-control" id="device_ID" disabled> <input type="text" class="form-control" id="device_ID" disabled>
</div> </div>
<!-- config_scripts_table -->
<div class="form-check mb-3"> <div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="" id="check_NPM_5channels" onchange="update_config('NextPM_5channels', this.checked)"> <input class="form-check-input" type="checkbox" value="" id="check_NPM" onchange="update_config_scripts_sqlite('NPM/get_data_modbus_v3.py', this.checked)">
<label class="form-check-label" for="check_NPM_5channels"> <label class="form-check-label" for="check_NPM">
Next PM 5 canaux Next PM
</label> </label>
</div> </div>
<div class="form-check mb-3"> <div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="" id="check_bme280" onchange="update_config('BME280/get_data_v2.py', this.checked)"> <input class="form-check-input" type="checkbox" value="" id="check_NPM_5channels" onchange="update_config_sqlite('npm_5channel', this.checked)">
<label class="form-check-label" for="check_NPM_5channels">
Next PM send 5 channels
</label>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="" id="check_bme280" onchange="update_config_scripts_sqlite('BME280/get_data_v2.py', this.checked)">
<label class="form-check-label" for="check_bme280"> <label class="form-check-label" for="check_bme280">
Sonde temp/hum (BME280) Sonde temp/hum (BME280)
</label> </label>
</div> </div>
<div class="form-check mb-3"> <div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="" id="check_envea" onchange="update_config('envea/read_value_v2.py', this.checked)"> <input class="form-check-input" type="checkbox" value="" id="check_envea" onchange="update_config_scripts_sqlite('envea/read_value_v2.py', this.checked)">
<label class="form-check-label" for="check_envea"> <label class="form-check-label" for="check_envea">
Sonde Envea Sonde Envea
</label> </label>
</div> </div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="" id="check_solarBattery" onchange="update_config_scripts_sqlite('MPPT/read.py', this.checked)">
<label class="form-check-label" for="check_solarBattery">
Solar / Battery MPPT
</label>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="" id="check_WindMeter" onchange="update_config_scripts_sqlite('windMeter/read.py', this.checked)">
<label class="form-check-label" for="check_WindMeter">
Wind Meter
</label>
</div>
<!--<button type="submit" class="btn btn-primary">Submit</button>--> <!--<button type="submit" class="btn btn-primary">Submit</button>-->
@@ -138,6 +162,22 @@
</div> </div>
</div> </div>
<!-- toast -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="liveToast" class="toast align-items-center text-bg-primary border-1" role="alert" aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div class="toast-body">
Hello, world! This is a toast message.
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
</div>
</div>
</main> </main>
</div> </div>
</div> </div>
@@ -170,117 +210,208 @@
}); });
}); });
//end document.addEventListener
window.onload = function() { window.onload = function() {
fetch('../config.json') // Replace 'deviceID.txt' with 'config.json' //NEW way to get config (SQLite)
.then(response => response.json()) // Parse response as JSON $.ajax({
.then(data => { url: 'launcher.php?type=get_config_sqlite',
console.log("Getting config file (onload)"); dataType:'json',
//get device ID //dataType: 'json', // Specify that you expect a JSON response
const deviceID = data.deviceID.trim().toUpperCase(); method: 'GET', // Use GET or POST depending on your needs
//document.getElementById('pageTitle_plus_ID').innerText = 'token: ' + deviceID; success: function(response) {
//get device Name console.log("Getting SQLite config table:");
const deviceName = data.deviceName; console.log(response);
//device name
const deviceName = document.getElementById("device_name");
deviceName.value = response.deviceName;
//device name_side bar
const elements = document.querySelectorAll('.sideBar_sensorName');
elements.forEach((element) => {
element.innerText = response.deviceName;
});
//device ID
const deviceID = response.deviceID.trim().toUpperCase();
const device_ID = document.getElementById("device_ID");
device_ID.value = response.deviceID.toUpperCase();
//nextPM send 5 channels
const checkbox_nmp5channels = document.getElementById("check_NPM_5channels");
checkbox_nmp5channels.checked = response.npm_5channel;
console.log("Device Name: " + deviceName);
console.log("Device ID: " + deviceID);
},
error: function(xhr, status, error) {
const elements = document.querySelectorAll('.sideBar_sensorName'); console.error('AJAX request failed:', status, error);
elements.forEach((element) => { }
element.innerText = deviceName; });//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);
//get BME check const checkbox_NPM = document.getElementById("check_NPM");
const checkbox = document.getElementById("check_bme280"); const checkbox_bme = document.getElementById("check_bme280");
checkbox.checked = data["BME280/get_data_v2.py"]; const checkbox_envea = document.getElementById("check_envea");
const checkbox_solar = document.getElementById("check_solarBattery");
const checkbox_wind = document.getElementById("check_WindMeter");
//get NPM-5channels check checkbox_NPM.checked = response["NPM/get_data_modbus_v3.py"];
const checkbox_NPM_5channels = document.getElementById("check_NPM_5channels"); checkbox_bme.checked = response["BME280/get_data_v2.py"];
checkbox_NPM_5channels.checked = data["NextPM_5channels"]; checkbox_envea.checked = response["envea/read_value_v2.py"];
checkbox_solar.checked = response["MPPT/read.py"];
checkbox_wind.checked = response["windMeter/read.py"];
},
error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error);
}
});//end AJAX
//get sonde Envea check //OLD way to get config (JSON)
const checkbox_envea = document.getElementById("check_envea"); /*
checkbox_envea.checked = data["envea/read_value_v2.py"]; fetch('../config.json') // Replace 'deviceID.txt' with 'config.json'
.then(response => response.json()) // Parse response as JSON
.then(data => {
console.log("Getting config file (onload)");
//get device ID
//document.getElementById('pageTitle_plus_ID').innerText = 'token: ' + deviceID;
//get device Name
//const deviceName = data.deviceName;
//device name //get BME check
const device_name = document.getElementById("device_name"); const checkbox = document.getElementById("check_bme280");
device_name.value = data.deviceName; checkbox.checked = data["BME280/get_data_v2.py"];
//device ID //get NPM-5channels check
const device_ID = document.getElementById("device_ID"); const checkbox_NPM_5channels = document.getElementById("check_NPM_5channels");
device_ID.value = data.deviceID.toUpperCase(); checkbox_NPM_5channels.checked = data["NextPM_5channels"];
//get system time and RTC module //get sonde Envea check
$.ajax({ const checkbox_envea = document.getElementById("check_envea");
url: 'launcher.php?type=sys_RTC_module_time', checkbox_envea.checked = data["envea/read_value_v2.py"];
dataType: 'json', // Specify that you expect a JSON response
method: 'GET', // Use GET or POST depending on your needs
success: function(response) {
console.log(response);
// Update the input fields with the received JSON data
document.getElementById("sys_local_time").value = response.system_local_time;
document.getElementById("sys_UTC_time").value = response.system_utc_time;
document.getElementById("RTC_utc_time").value = response.rtc_module_time;
// Get the time difference //device name
const timeDiff = response.time_difference_seconds; //const device_name = document.getElementById("device_name");
//device_name.value = data.deviceName;
// Reference to the alert container
const alertContainer = document.getElementById("alert_container"); })
.catch(error => console.error('Error loading config.json:', error));
*/
// Remove any previous alert
alertContainer.innerHTML = "";
// Add an alert based on time difference
if (typeof timeDiff === "number") {
if (timeDiff >= 0 && timeDiff <= 10) {
alertContainer.innerHTML = `
<div class="alert alert-success" role="alert">
RTC and system time are in sync (Difference: ${timeDiff} sec).
</div>`;
} else if (timeDiff > 10) {
alertContainer.innerHTML = `
<div class="alert alert-danger" role="alert">
RTC time is out of sync! (Difference: ${timeDiff} sec).
</div>`;
}
}
},
error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error);
}
});
//get local RTC //get system time and RTC module
$.ajax({ $.ajax({
url: 'launcher.php?type=RTC_time', url: 'launcher.php?type=sys_RTC_module_time',
dataType: 'text', // Specify that you expect a JSON response dataType: 'json', // Specify that you expect a JSON response
method: 'GET', // Use GET or POST depending on your needs method: 'GET', // Use GET or POST depending on your needs
success: function(response) { success: function(response) {
console.log("Local RTC: " + response); console.log("Getting RTC times");
const RTC_Element = document.getElementById("RTC_time");
RTC_Element.textContent = response; console.log(response);
}, // Update the input fields with the received JSON data
error: function(xhr, status, error) { document.getElementById("sys_local_time").value = response.system_local_time;
console.error('AJAX request failed:', status, error); document.getElementById("sys_UTC_time").value = response.system_utc_time;
} document.getElementById("RTC_utc_time").value = response.rtc_module_time;
});
}) // Get the time difference
.catch(error => console.error('Error loading config.json:', error)); const timeDiff = response.time_difference_seconds;
}
// Reference to the alert container
const alertContainer = document.getElementById("alert_container");
// Remove any previous alert
alertContainer.innerHTML = "";
// Add an alert based on time difference
if (typeof timeDiff === "number") {
if (timeDiff >= 0 && timeDiff <= 10) {
alertContainer.innerHTML = `
<div class="alert alert-success" role="alert">
RTC and system time are in sync (Difference: ${timeDiff} sec).
</div>`;
} else if (timeDiff > 10) {
alertContainer.innerHTML = `
<div class="alert alert-danger" role="alert">
RTC time is out of sync! (Difference: ${timeDiff} sec).
</div>`;
}
}
},
error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error);
}
});//end AJAX
//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 AJAx
} //end window.onload
function update_config_sqlite(param, value){ function update_config_sqlite(param, value){
console.log("Updating sqlite ",param," : ", value); console.log("Updating sqlite ",param," : ", value);
const toastLiveExample = document.getElementById('liveToast')
const toastBody = toastLiveExample.querySelector('.toast-body');
$.ajax({ $.ajax({
url: 'launcher.php?type=update_config_sqlite&param='+param+'&value='+value, url: 'launcher.php?type=update_config_sqlite&param='+param+'&value='+value,
dataType: 'text', // Specify that you expect a JSON response dataType: 'json', // Specify that you expect a JSON response
method: 'GET', // Use GET or POST depending on your needs method: 'GET', // Use GET or POST depending on your needs
cache: false, // Prevent AJAX from caching cache: false, // Prevent AJAX from caching
success: function(response) { success: function(response) {
console.log(response); console.log(response);
// Format the response nicely
let formattedMessage = '';
if (response.success) {
// Success message
toastLiveExample.classList.remove('text-bg-danger');
toastLiveExample.classList.add('text-bg-success');
formattedMessage = `
<strong>Success!</strong><br>
Parameter: ${response.param || param}<br>
Value: ${response.value || checked}<br>
${response.message || ''}
`;
} else {
// Error message
toastLiveExample.classList.remove('text-bg-success');
toastLiveExample.classList.add('text-bg-danger');
formattedMessage = `
<strong>Error!</strong><br>
${response.error || 'Unknown error'}<br>
Parameter: ${response.param || param}
`;
}
// Update the toast body with formatted content
toastBody.innerHTML = formattedMessage;
// Show the toast
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
toastBootstrap.show()
}, },
error: function(xhr, status, error) { error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error); console.error('AJAX request failed:', status, error);
@@ -288,6 +419,56 @@ function update_config_sqlite(param, value){
}); });
} }
function update_config_scripts_sqlite(param, value) {
console.log("Updating scripts sqlite ", param, " : ", value);
const toastLiveExample = document.getElementById('liveToast')
const toastBody = toastLiveExample.querySelector('.toast-body');
$.ajax({
url: 'launcher.php?type=update_config_scripts_sqlite&param=' + param + '&value=' + value,
dataType: 'json',
method: 'GET',
cache: false,
success: function(response) {
console.log(response);
// Format the response nicely
let formattedMessage = '';
if (response.success) {
// Success message
toastLiveExample.classList.remove('text-bg-danger');
toastLiveExample.classList.add('text-bg-success');
formattedMessage = `
<strong>Success!</strong><br>
Parameter: ${response.script_path || param}<br>
Value: ${response.enabled !== undefined ? response.enabled : value}<br>
${response.message || ''}
`;
} else {
// Error message
toastLiveExample.classList.remove('text-bg-success');
toastLiveExample.classList.add('text-bg-danger');
formattedMessage = `
<strong>Error!</strong><br>
${response.error || 'Unknown error'}<br>
Parameter: ${response.script_path || param}
`;
}
// Update the toast body with formatted content
toastBody.innerHTML = formattedMessage;
// Show the toast
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
toastBootstrap.show()
},
error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error);
}
});
}
function update_config(param, value){ function update_config(param, value){
console.log("Updating ",param," : ", value); console.log("Updating ",param," : ", value);
@@ -346,7 +527,7 @@ function set_RTC_withNTP(){
error: function(xhr, status, error) { error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error); console.error('AJAX request failed:', status, error);
} }
}); }); //end ajax
} }
function set_RTC_withBrowser(){ function set_RTC_withBrowser(){
@@ -374,7 +555,7 @@ function set_RTC_withBrowser(){
error: function(xhr, status, error) { error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error); console.error('AJAX request failed:', status, error);
} }
}); }); //end ajax
} }

View File

@@ -135,6 +135,30 @@
window.onload = function() { window.onload = function() {
//NEW way to get data from 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);
//get device Name (for the side bar)
const deviceName = response.deviceName;
const elements = document.querySelectorAll('.sideBar_sensorName');
elements.forEach((element) => {
element.innerText = deviceName;
});
},
error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error);
}
});
/* OLD way of getting config data
fetch('../config.json') // Replace 'deviceID.txt' with 'config.json' fetch('../config.json') // Replace 'deviceID.txt' with 'config.json'
.then(response => response.json()) // Parse response as JSON .then(response => response.json()) // Parse response as JSON
.then(data => { .then(data => {
@@ -151,7 +175,12 @@ window.onload = function() {
elements.forEach((element) => { elements.forEach((element) => {
element.innerText = deviceName; element.innerText = deviceName;
}); });
//end fetch config
})
.catch(error => console.error('Error loading config.json:', error));
//end windows on load
*/
//get local RTC //get local RTC
$.ajax({ $.ajax({
url: 'launcher.php?type=RTC_time', url: 'launcher.php?type=RTC_time',
@@ -421,10 +450,6 @@ window.onload = function() {
//end fetch config
})
.catch(error => console.error('Error loading config.json:', error));
//end windows on load
} }
</script> </script>

View File

@@ -1,13 +1,16 @@
<?php <?php
//Prevents caching → Adds headers to ensure fresh response. //Prevents caching → Adds headers to ensure fresh response.
// to test this page http://192.168.1.127/html/launcher.php?type=get_config_scripts_sqlite
header("Content-Type: application/json"); header("Content-Type: application/json");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache"); header("Pragma: no-cache");
$database_path = "/var/www/nebuleair_pro_4g/sqlite/sensors.db";
$type=$_GET['type']; $type=$_GET['type'];
if ($type == "get_npm_sqlite_data") { if ($type == "get_npm_sqlite_data") {
$database_path = "/var/www/nebuleair_pro_4g/sqlite/sensors.db";
//echo "Getting data from sqlite database"; //echo "Getting data from sqlite database";
try { try {
$db = new PDO("sqlite:$database_path"); $db = new PDO("sqlite:$database_path");
@@ -25,8 +28,88 @@ if ($type == "get_npm_sqlite_data") {
} }
} }
//GETING data from config_table (SQLite DB)
if ($type == "get_config_sqlite") {
try {
$db = new PDO("sqlite:$database_path");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Get all main configuration entries
$config_query = $db->query("SELECT key, value, type FROM config_table");
$config_data = $config_query->fetchAll(PDO::FETCH_ASSOC);
// Convert data types according to their 'type' field
$result = [];
foreach ($config_data as $item) {
$key = $item['key'];
$value = $item['value'];
$type = $item['type'];
// Convert value based on its type
switch ($type) {
case 'bool':
$parsed_value = ($value == '1' || $value == 'true') ? true : false;
break;
case 'int':
$parsed_value = intval($value);
break;
case 'float':
$parsed_value = floatval($value);
break;
default:
$parsed_value = $value;
}
$result[$key] = $parsed_value;
}
// Return JSON response
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
} catch (PDOException $e) {
// Return error as JSON
header('Content-Type: application/json');
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
}
//GETING data from config_scrips_table (SQLite DB)
if ($type == "get_config_scripts_sqlite") {
try {
$db = new PDO("sqlite:$database_path");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Get all main configuration entries
$config_query = $db->query("SELECT * FROM config_scripts_table");
$config_data = $config_query->fetchAll(PDO::FETCH_ASSOC);
// Convert data types according to their 'type' field
$result = [];
foreach ($config_data as $item) {
$script_path = $item['script_path'];
$enabled = $item['enabled'];
// Convert the enabled field to a proper boolean
$result[$script_path] = ($enabled == 1);
}
// Return JSON response
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} catch (PDOException $e) {
// Return error as JSON
header('Content-Type: application/json');
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
}
//UPDATING the config_table from SQLite DB
if ($type == "update_config_sqlite") { if ($type == "update_config_sqlite") {
echo "updating....";
$param = $_GET['param'] ?? null; $param = $_GET['param'] ?? null;
$value = $_GET['value'] ?? null; $value = $_GET['value'] ?? null;
@@ -35,7 +118,6 @@ if ($type == "update_config_sqlite") {
exit; exit;
} }
$database_path = "/var/www/nebuleair_pro_4g/sqlite/sensors.db";
try { try {
$db = new PDO("sqlite:$database_path"); $db = new PDO("sqlite:$database_path");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
@@ -85,9 +167,56 @@ if ($type == "update_config_sqlite") {
} }
} }
//UPDATING the config_scripts table from SQLite DB
if ($type == "update_config_scripts_sqlite") {
$script_path = $_GET['param'] ?? null;
$enabled = $_GET['value'] ?? null;
if ($script_path === null || $enabled === null) {
echo json_encode(["error" => "Missing parameter or value"]);
exit;
}
try {
$db = new PDO("sqlite:$database_path");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// First, check if parameter exists and get its type
$checkStmt = $db->prepare("SELECT enabled FROM config_scripts_table WHERE script_path = :script_path");
$checkStmt->bindParam(':script_path', $script_path);
$checkStmt->execute();
$result = $checkStmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
// Convert enabled value to 0 or 1
$enabledValue = (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) ? 1 : 0;
// Update the enabled status
$updateStmt = $db->prepare("UPDATE config_scripts_table SET enabled = :enabled WHERE script_path = :script_path");
$updateStmt->bindParam(':enabled', $enabledValue, PDO::PARAM_INT);
$updateStmt->bindParam(':script_path', $script_path);
$updateStmt->execute();
echo json_encode([
"success" => true,
"message" => "Script configuration updated successfully",
"script_path" => $script_path,
"enabled" => (bool)$enabledValue
], JSON_UNESCAPED_SLASHES); // Prevent escaping forward slashes
} else {
echo json_encode([
"error" => "Script path not found in configuration",
"script_path" => $script_path
], JSON_UNESCAPED_SLASHES); // Prevent escaping forward slashes
}
} catch (PDOException $e) {
echo json_encode(["error" => $e->getMessage()]);
}
}
//update the config (old JSON updating)
if ($type == "update_config") { if ($type == "update_config") {
echo "updating...."; echo "updating.... ";
$param=$_GET['param']; $param=$_GET['param'];
$value=$_GET['value']; $value=$_GET['value'];
$configFile = '../config.json'; $configFile = '../config.json';

View File

@@ -59,11 +59,12 @@
</div> </div>
<span id="modem_status_message"></span> <span id="modem_status_message"></span>
<!--
<h3> <h3>
Status Status
<span id="modem-status" class="badge">Loading...</span> <span id="modem-status" class="badge">Loading...</span>
</h3> </h3>
-->
<div class="row mb-3"> <div class="row mb-3">
<div class="col-sm-3"> <div class="col-sm-3">
@@ -71,7 +72,7 @@
<div class="card-body"> <div class="card-body">
<p class="card-text">General information. </p> <p class="card-text">General information. </p>
<button class="btn btn-primary" onclick="getData_saraR4('ttyAMA2', 'ATI', 2)">Get Data</button> <button class="btn btn-primary" onclick="getData_saraR4('ttyAMA2', 'ATI', 1)">Get Data</button>
<div id="loading_ttyAMA2_ATI" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div> <div id="loading_ttyAMA2_ATI" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div>
<div id="response_ttyAMA2_ATI"></div> <div id="response_ttyAMA2_ATI"></div>
@@ -84,7 +85,7 @@
<div class="card-body"> <div class="card-body">
<p class="card-text">SIM card information.</p> <p class="card-text">SIM card information.</p>
<button class="btn btn-primary" onclick="getData_saraR4('ttyAMA2', 'AT+CCID?', 2)">Get Data</button> <button class="btn btn-primary" onclick="getData_saraR4('ttyAMA2', 'AT+CCID?', 1)">Get Data</button>
<div id="loading_ttyAMA2_AT_CCID_" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div> <div id="loading_ttyAMA2_AT_CCID_" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div>
<div id="response_ttyAMA2_AT_CCID_"></div> <div id="response_ttyAMA2_AT_CCID_"></div>
</div> </div>
@@ -109,7 +110,7 @@
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<p class="card-text">Signal strength </p> <p class="card-text">Signal strength </p>
<button class="btn btn-primary" onclick="getData_saraR4('ttyAMA2', 'AT+CSQ', 2)">Get Data</button> <button class="btn btn-primary" onclick="getData_saraR4('ttyAMA2', 'AT+CSQ', 1)">Get Data</button>
<div id="loading_ttyAMA2_AT_CSQ" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div> <div id="loading_ttyAMA2_AT_CSQ" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div>
<div id="response_ttyAMA2_AT_CSQ"></div> <div id="response_ttyAMA2_AT_CSQ"></div>
</table> </table>
@@ -121,7 +122,7 @@
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<p class="card-text">Modem Reset </p> <p class="card-text">Modem Reset </p>
<button class="btn btn-danger" onclick="getData_saraR4('ttyAMA2', 'AT+CFUN=15', 2)">Reset</button> <button class="btn btn-danger" onclick="getData_saraR4('ttyAMA2', 'AT+CFUN=15', 1)">Reset</button>
<div id="loading_ttyAMA2_AT_CFUN_15" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div> <div id="loading_ttyAMA2_AT_CFUN_15" class="spinner-border spinner-border-sm" style="display: none;" role="status"></div>
<div id="response_ttyAMA2_AT_CFUN_15"></div> <div id="response_ttyAMA2_AT_CFUN_15"></div>
</table> </table>
@@ -304,7 +305,20 @@
</div> </div>
<!-- toast -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="liveToast" class="toast align-items-center text-bg-primary border-1" role="alert" aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div class="toast-body">
Hello, world! This is a toast message.
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
</div>
</div>
</main> </main>
</div> </div>
</div> </div>
@@ -317,35 +331,62 @@
<script src="assets/js/bootstrap.bundle.js"></script> <script src="assets/js/bootstrap.bundle.js"></script>
<script> <script>
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
const elementsToLoad = [ const elementsToLoad = [
{ id: 'topbar', file: 'topbar.html' }, { id: 'topbar', file: 'topbar.html' },
{ id: 'sidebar', file: 'sidebar.html' }, { id: 'sidebar', file: 'sidebar.html' },
{ id: 'sidebar_mobile', file: 'sidebar.html' } { id: 'sidebar_mobile', file: 'sidebar.html' }
]; ];
elementsToLoad.forEach(({ id, file }) => { elementsToLoad.forEach(({ id, file }) => {
fetch(file) fetch(file)
.then(response => response.text()) .then(response => response.text())
.then(data => { .then(data => {
const element = document.getElementById(id); const element = document.getElementById(id);
if (element) { if (element) {
element.innerHTML = data; element.innerHTML = data;
}
})
.catch(error => console.error(`Error loading ${file}:`, error));
});
//OLD way to retreive data from JSON
/*
fetch('../config.json') // Replace 'deviceID.txt' with 'config.json'
.then(response => response.json()) // Parse response as JSON
.then(data => {
console.log("Getting config file (onload)");
//modem config mode
const check_modem_configMode = document.getElementById("check_modem_configMode");
check_modem_configMode.checked = data.modem_config_mode;
console.log("Modem configuration: " + data.modem_config_mode);
})
*/
//NEW way to get data from 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);
// Set checkbox state based on the response data
const check_modem_configMode = document.getElementById("check_modem_configMode");
if (check_modem_configMode) {
check_modem_configMode.checked = response.modem_config_mode;
console.log("Modem configuration: " + response.modem_config_mode);
} else {
console.error("Checkbox element not found");
} }
})
.catch(error => console.error(`Error loading ${file}:`, error));
});
fetch('../config.json') // Replace 'deviceID.txt' with 'config.json' },
.then(response => response.json()) // Parse response as JSON error: function(xhr, status, error) {
.then(data => { console.error('AJAX request failed:', status, error);
console.log("Getting config file (onload)"); }
//modem config mode });
const check_modem_configMode = document.getElementById("check_modem_configMode");
check_modem_configMode.checked = data.modem_config_mode;
console.log("Modem configuration: " + data.modem_config_mode);
})
}); });
@@ -430,8 +471,10 @@ function getData_saraR4(port, command, timeout){
} else{ } else{
// si c'est une commande AT normale // si c'est une commande AT normale
// Replace newline characters with <br> tags // Replace newline characters with <br> tags
const formattedResponse = response.replace(/\n/g, "<br>"); const formattedResponse = response.replace(/\n/g, "<br>")
.replace(/\b(OK)\b/g, '<span style="color: green; font-weight: bold;">$1</span>');;
$("#response_"+port+"_"+safeCommand).html(formattedResponse); $("#response_"+port+"_"+safeCommand).html(formattedResponse);
} }
}, },
error: function(xhr, status, error) { error: function(xhr, status, error) {
@@ -700,17 +743,68 @@ function getModem_busy_status() {
} }
function update_modem_configMode(param, checked){ function update_modem_configMode(param, checked){
//change ('modem_config_mode', '0', 'bool') inside SQLITE db
// response type: {"success":true,"message":"Configuration updated successfully","param":"modem_config_mode","value":"0","type":"bool"}
const toastLiveExample = document.getElementById('liveToast')
const toastBody = toastLiveExample.querySelector('.toast-body');
console.log("updating modem config mode to :" + checked); console.log("updating modem config mode to :" + checked);
$.ajax({ $.ajax({
url: 'launcher.php?type=update_config&param='+param+'&value='+checked, url: 'launcher.php?type=update_config_sqlite&param='+param+'&value='+checked,
dataType: 'text', // Specify that you expect a JSON response dataType: 'json', // Specify that you expect a JSON response
method: 'GET', // Use GET or POST depending on your needs method: 'GET', // Use GET or POST depending on your needs
cache: false, // Prevent AJAX from caching cache: false, // Prevent AJAX from caching
success: function(response) { success: function(response) {
console.log(response);
console.log("AJAX success:");
console.log(response);
// Format the response nicely
let formattedMessage = '';
if (response.success) {
// Success message
toastLiveExample.classList.remove('text-bg-danger');
toastLiveExample.classList.add('text-bg-success');
formattedMessage = `
<strong>Success!</strong><br>
Parameter: ${response.param || param}<br>
Value: ${response.value || checked}<br>
${response.message || ''}
`;
} else {
// Error message
toastLiveExample.classList.remove('text-bg-success');
toastLiveExample.classList.add('text-bg-danger');
formattedMessage = `
<strong>Error!</strong><br>
${response.error || 'Unknown error'}<br>
Parameter: ${response.param || param}
`;
}
// Update the toast body with formatted content
toastBody.innerHTML = formattedMessage;
// Show the toast
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
toastBootstrap.show()
}, },
error: function(xhr, status, error) { error: function(xhr, status, error) {
console.error('AJAX request failed:', status, error); console.error('AJAX request failed:', status, error);
// Update toast with error message
toastBody.textContent = 'Error: ' + error;
// Set toast to danger color
toastLiveExample.classList.remove('text-bg-success');
toastLiveExample.classList.add('text-bg-danger');
// Show the toast for errors too
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);
toastBootstrap.show();
} }
}); });
} }
@@ -721,6 +815,7 @@ window.onload = function() {
getModem_busy_status(); getModem_busy_status();
setInterval(getModem_busy_status, 1000); setInterval(getModem_busy_status, 1000);
fetch('../config.json') // Replace 'deviceID.txt' with 'config.json' fetch('../config.json') // Replace 'deviceID.txt' with 'config.json'
.then(response => response.json()) // Parse response as JSON .then(response => response.json()) // Parse response as JSON
.then(data => { .then(data => {
@@ -744,6 +839,7 @@ window.onload = function() {
//get SARA_R4 connection status //get SARA_R4 connection status
/*
const SARA_statusElement = document.getElementById("modem-status"); const SARA_statusElement = document.getElementById("modem-status");
console.log("SARA R4 is: " + data.SARA_R4_network_status); console.log("SARA R4 is: " + data.SARA_R4_network_status);
@@ -757,7 +853,7 @@ window.onload = function() {
SARA_statusElement.textContent = "Unknown"; SARA_statusElement.textContent = "Unknown";
SARA_statusElement.className = "badge text-bg-secondary"; SARA_statusElement.className = "badge text-bg-secondary";
} }
*/
//get local RTC //get local RTC
$.ajax({ $.ajax({
url: 'launcher.php?type=RTC_time', url: 'launcher.php?type=RTC_time',
@@ -778,6 +874,7 @@ window.onload = function() {
}) })
.catch(error => console.error('Error loading config.json:', error)); .catch(error => console.error('Error loading config.json:', error));
} }
</script> </script>
</body> </body>