update
This commit is contained in:
142
NPM/get_data_v2.py
Normal file
142
NPM/get_data_v2.py
Normal file
@@ -0,0 +1,142 @@
|
||||
'''
|
||||
_ _ ____ __ __
|
||||
| \ | | _ \| \/ |
|
||||
| \| | |_) | |\/| |
|
||||
| |\ | __/| | | |
|
||||
|_| \_|_| |_| |_|
|
||||
|
||||
Script to get NPM values
|
||||
And store them inside sqlite database
|
||||
Uses RTC module for timing
|
||||
/usr/bin/python3 /var/www/nebuleair_pro_4g/NPM/get_data_v2.py
|
||||
'''
|
||||
|
||||
import serial
|
||||
import requests
|
||||
import json
|
||||
import sys
|
||||
import sqlite3
|
||||
import smbus2
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
# Connect to the SQLite database
|
||||
conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db")
|
||||
cursor = conn.cursor()
|
||||
|
||||
#RTC module
|
||||
DS3231_ADDR = 0x68
|
||||
REG_TIME = 0x00
|
||||
|
||||
def bcd_to_dec(bcd):
|
||||
return (bcd // 16 * 10) + (bcd % 16)
|
||||
|
||||
def read_time(bus):
|
||||
"""Try to read and decode time from the RTC module (DS3231)."""
|
||||
try:
|
||||
data = bus.read_i2c_block_data(DS3231_ADDR, REG_TIME, 7)
|
||||
seconds = bcd_to_dec(data[0] & 0x7F)
|
||||
minutes = bcd_to_dec(data[1])
|
||||
hours = bcd_to_dec(data[2] & 0x3F)
|
||||
day = bcd_to_dec(data[4])
|
||||
month = bcd_to_dec(data[5])
|
||||
year = bcd_to_dec(data[6]) + 2000
|
||||
return datetime(year, month, day, hours, minutes, seconds)
|
||||
except OSError:
|
||||
return None # RTC module not connected
|
||||
|
||||
def load_config(config_file):
|
||||
try:
|
||||
with open(config_file, 'r') as file:
|
||||
config_data = json.load(file)
|
||||
return config_data
|
||||
except Exception as e:
|
||||
print(f"Error loading config file: {e}")
|
||||
return {}
|
||||
|
||||
# Load the configuration data
|
||||
config_file = '/var/www/nebuleair_pro_4g/config.json'
|
||||
config = load_config(config_file)
|
||||
npm_solo_port = config.get('NPM_solo_port', '') #port du NPM solo
|
||||
|
||||
ser = serial.Serial(
|
||||
port=npm_solo_port,
|
||||
baudrate=115200,
|
||||
parity=serial.PARITY_EVEN,
|
||||
stopbits=serial.STOPBITS_ONE,
|
||||
bytesize=serial.EIGHTBITS,
|
||||
timeout = 0.5
|
||||
)
|
||||
|
||||
#ser.write(b'\x81\x11\x6E') #data10s
|
||||
ser.write(b'\x81\x12\x6D') #data60s
|
||||
|
||||
while True:
|
||||
try:
|
||||
byte_data = ser.readline()
|
||||
#print(byte_data)
|
||||
stateByte = int.from_bytes(byte_data[2:3], byteorder='big')
|
||||
Statebits = [int(bit) for bit in bin(stateByte)[2:].zfill(8)]
|
||||
PM1 = int.from_bytes(byte_data[9:11], byteorder='big')/10
|
||||
PM25 = int.from_bytes(byte_data[11:13], byteorder='big')/10
|
||||
PM10 = int.from_bytes(byte_data[13:15], byteorder='big')/10
|
||||
#print(f"State: {Statebits}")
|
||||
#print(f"PM1: {PM1}")
|
||||
#print(f"PM25: {PM25}")
|
||||
#print(f"PM10: {PM10}")
|
||||
#create JSON
|
||||
data = {
|
||||
'capteurID': 'nebuleairpro1',
|
||||
'sondeID':'USB2',
|
||||
'PM1': PM1,
|
||||
'PM25': PM25,
|
||||
'PM10': PM10,
|
||||
'sleep' : Statebits[0],
|
||||
'degradedState' : Statebits[1],
|
||||
'notReady' : Statebits[2],
|
||||
'heatError' : Statebits[3],
|
||||
't_rhError' : Statebits[4],
|
||||
'fanError' : Statebits[5],
|
||||
'memoryError' : Statebits[6],
|
||||
'laserError' : Statebits[7]
|
||||
}
|
||||
json_data = json.dumps(data)
|
||||
print(json_data)
|
||||
|
||||
#GET RTC TIME
|
||||
# Read RTC time
|
||||
bus = smbus2.SMBus(1)
|
||||
# Try to read RTC time
|
||||
rtc_time = read_time(bus)
|
||||
|
||||
if rtc_time:
|
||||
rtc_time_str = rtc_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
print(rtc_time_str)
|
||||
else:
|
||||
print("Error! RTC module not connected")
|
||||
rtc_time_str = "1970-01-01 00:00:00" # Default fallback time
|
||||
|
||||
|
||||
#save to sqlite database
|
||||
cursor.execute('''
|
||||
INSERT INTO data (timestamp,PM1, PM25, PM10) VALUES (?,?,?,?)'''
|
||||
, (rtc_time_str,PM1,PM25,PM10))
|
||||
|
||||
# Commit and close the connection
|
||||
conn.commit()
|
||||
|
||||
print("Sensor data saved successfully!")
|
||||
|
||||
break # Exit loop after successful execution
|
||||
except KeyboardInterrupt:
|
||||
print("User interrupt encountered. Exiting...")
|
||||
time.sleep(3)
|
||||
exit()
|
||||
except Exception as e:
|
||||
print(f"Error: {e}") # Show actual error
|
||||
time.sleep(3)
|
||||
exit()
|
||||
|
||||
conn.close()
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ See `installation.sh`
|
||||
|
||||
```
|
||||
sudo apt update
|
||||
sudo apt install git gh apache2 php python3 python3-pip jq autossh i2c-tools python3-smbus -y
|
||||
sudo apt install git gh apache2 php php-sqlite3 python3 python3-pip jq autossh i2c-tools python3-smbus -y
|
||||
sudo pip3 install pyserial requests RPi.GPIO adafruit-circuitpython-bme280 crcmod --break-system-packages
|
||||
sudo mkdir -p /var/www/.ssh
|
||||
sudo ssh-keygen -t rsa -b 4096 -f /var/www/.ssh/id_rsa -N ""
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
'''
|
||||
____ _____ ____
|
||||
| _ \_ _/ ___|
|
||||
| |_) || || |
|
||||
| _ < | || |___
|
||||
|_| \_\|_| \____|
|
||||
|
||||
Script to read time from RTC module
|
||||
I2C connection
|
||||
Address 0x68
|
||||
@@ -9,7 +15,6 @@ import time
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
# DS3231 I2C address
|
||||
DS3231_ADDR = 0x68
|
||||
|
||||
@@ -52,7 +57,6 @@ def main():
|
||||
rtc_time_str = "not connected"
|
||||
time_difference = "N/A" # Not applicable
|
||||
|
||||
|
||||
# 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')}")
|
||||
|
||||
@@ -188,6 +188,11 @@ window.onload = function() {
|
||||
//get device Name
|
||||
const deviceName = data.deviceName;
|
||||
|
||||
console.log("Device Name: " + deviceName);
|
||||
console.log("Device ID: " + deviceID);
|
||||
|
||||
|
||||
|
||||
const elements = document.querySelectorAll('.sideBar_sensorName');
|
||||
elements.forEach((element) => {
|
||||
element.innerText = deviceName;
|
||||
@@ -204,6 +209,7 @@ window.onload = function() {
|
||||
//loop activation
|
||||
const flex_loop = document.getElementById("flex_loop");
|
||||
flex_loop.checked = data.loop_activation;
|
||||
console.log("Loop activation: " + data.loop_activation);
|
||||
|
||||
//loop logs
|
||||
const flex_loop_log = document.getElementById("flex_loop_log");
|
||||
|
||||
20
html/assets/js/chart.js
Normal file
20
html/assets/js/chart.js
Normal file
File diff suppressed because one or more lines are too long
@@ -5,6 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>NebuleAir</title>
|
||||
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
|
||||
<script src="assets/js/chart.js"></script> <!-- Local Chart.js -->
|
||||
|
||||
<style>
|
||||
body {
|
||||
overflow-x: hidden;
|
||||
@@ -53,22 +55,34 @@
|
||||
<p>Bienvenue sur votre interface de configuration de votre capteur.</p>
|
||||
<div class="row mb-3">
|
||||
|
||||
<!-- Card 1 Linux Stats -->
|
||||
<div class="col-sm-4">
|
||||
<div class="card">
|
||||
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Linux stats</h5>
|
||||
|
||||
<p class="card-text">Disk usage (total size <span id="disk_size"></span> Gb) </p>
|
||||
<div id="disk_space"></div>
|
||||
|
||||
<p class="card-text">Memory usage (total size <span id="memory_size"></span> Mb) </p>
|
||||
<div id="memory_space"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Card 2 NPM values -->
|
||||
<div class="col-sm-4">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Mesures PM</h5>
|
||||
<p class="card-text">Particules Fines </p>
|
||||
<canvas id="sensorPMChart" width="400" height="200"></canvas>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
@@ -210,8 +224,6 @@ window.onload = function() {
|
||||
console.log(usedMemory);
|
||||
console.log(percentageUsed);
|
||||
|
||||
|
||||
|
||||
// Create the outer div with class and attributes
|
||||
const progressDiv = document.createElement('div');
|
||||
progressDiv.className = 'progress mb-3';
|
||||
@@ -240,9 +252,62 @@ window.onload = function() {
|
||||
});
|
||||
|
||||
|
||||
// GET NPM SQLite values
|
||||
$.ajax({
|
||||
url: 'launcher.php?type=get_npm_sqlite_data',
|
||||
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);
|
||||
updatePMChart(response);
|
||||
},
|
||||
error: function(xhr, status, error) {
|
||||
console.error('AJAX request failed:', status, error);
|
||||
}
|
||||
});
|
||||
|
||||
let chart; // Store the Chart.js instance globally
|
||||
|
||||
function updatePMChart(data) {
|
||||
const labels = data.map(d => d.timestamp);
|
||||
const PM1 = data.map(d => d.PM1);
|
||||
const PM25 = data.map(d => d.PM25);
|
||||
const PM10 = data.map(d => d.PM10);
|
||||
|
||||
const ctx = document.getElementById('sensorPMChart').getContext('2d');
|
||||
|
||||
if (!chart) {
|
||||
chart = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [
|
||||
{ label: "PM1", data: PM1, borderColor: "red", fill: false },
|
||||
{ label: "PM2.5", data: PM25, borderColor: "blue", fill: false },
|
||||
{ label: "PM10", data: PM10, borderColor: "green", fill: false }
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false
|
||||
}
|
||||
});
|
||||
} else {
|
||||
chart.data.labels = labels;
|
||||
chart.data.datasets[0].data = PM1;
|
||||
chart.data.datasets[1].data = PM25;
|
||||
chart.data.datasets[2].data = PM10;
|
||||
chart.update();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//end fetch config
|
||||
})
|
||||
.catch(error => console.error('Error loading config.json:', error));
|
||||
//end windows on load
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
@@ -6,6 +6,23 @@ header("Pragma: no-cache");
|
||||
|
||||
$type=$_GET['type'];
|
||||
|
||||
if ($type == "get_npm_sqlite_data") {
|
||||
$database_path = "/var/www/nebuleair_pro_4g/sqlite/sensors.db";
|
||||
//echo "Getting data from sqlite database";
|
||||
try {
|
||||
$db = new PDO("sqlite:$database_path");
|
||||
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
// Fetch the last 10 records
|
||||
$stmt = $db->query("SELECT timestamp, PM1, PM25, PM10 FROM data ORDER BY timestamp DESC LIMIT 10");
|
||||
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
echo json_encode($data);
|
||||
} catch (PDOException $e) {
|
||||
echo json_encode(["error" => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($type == "update_config") {
|
||||
echo "updating....";
|
||||
$param=$_GET['param'];
|
||||
|
||||
@@ -52,7 +52,7 @@ import json
|
||||
import os
|
||||
|
||||
# Base directory where scripts are stored
|
||||
SCRIPT_DIR = "/var/www/nebuleair_pro_4g/tests/"
|
||||
SCRIPT_DIR = "/var/www/nebuleair_pro_4g/"
|
||||
CONFIG_FILE = "/var/www/nebuleair_pro_4g/config.json"
|
||||
|
||||
def load_config():
|
||||
@@ -71,9 +71,9 @@ def run_script(script_name, interval):
|
||||
|
||||
# Define scripts and their execution intervals (seconds)
|
||||
SCRIPTS = [
|
||||
("script1.py", 60), # Runs every 60 seconds
|
||||
("script2.py", 10), # Runs every 10 seconds
|
||||
("script3.py", 10), # Runs every 10 seconds
|
||||
("NPM/get_data_v2.py", 60), # Runs every 60 seconds
|
||||
("tests/script2.py", 10), # Runs every 10 seconds
|
||||
("tests/script3.py", 10), # Runs every 10 seconds
|
||||
]
|
||||
|
||||
# Start threads for enabled scripts
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
'''
|
||||
____ ___ _ _ _
|
||||
/ ___| / _ \| | (_) |_ ___
|
||||
\___ \| | | | | | | __/ _ \
|
||||
___) | |_| | |___| | || __/
|
||||
|____/ \__\_\_____|_|\__\___|
|
||||
|
||||
Script to create a sqlite database
|
||||
/usr/bin/python3 /var/www/nebuleair_pro_4g/sqlite/create_db.py
|
||||
|
||||
|
||||
|
||||
'''
|
||||
|
||||
import sqlite3
|
||||
@@ -16,7 +19,6 @@ cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS data (
|
||||
timestamp TEXT,
|
||||
sensor_id TEXT,
|
||||
PM1 REAL,
|
||||
PM25 REAL,
|
||||
PM10 REAL,
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
'''
|
||||
____ ___ _ _ _
|
||||
/ ___| / _ \| | (_) |_ ___
|
||||
\___ \| | | | | | | __/ _ \
|
||||
___) | |_| | |___| | || __/
|
||||
|____/ \__\_\_____|_|\__\___|
|
||||
|
||||
Script to read data from a sqlite database
|
||||
/usr/bin/python3 /var/www/nebuleair_pro_4g/sqlite/read.py
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
'''
|
||||
____ ___ _ _ _
|
||||
/ ___| / _ \| | (_) |_ ___
|
||||
\___ \| | | | | | | __/ _ \
|
||||
___) | |_| | |___| | || __/
|
||||
|____/ \__\_\_____|_|\__\___|
|
||||
|
||||
Script to write data to a sqlite database
|
||||
/usr/bin/python3 /var/www/nebuleair_pro_4g/sqlite/write.py
|
||||
|
||||
@@ -12,14 +18,13 @@ cursor = conn.cursor()
|
||||
|
||||
# Insert a sample temperature reading
|
||||
timestamp = "2025-10-11"
|
||||
sensor_name = "NebuleAir-pro020"
|
||||
PM1 = 25.3
|
||||
PM25 = 18.3
|
||||
PM10 = 9.3
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO data (timestamp, sensor_id, PM1, PM25, PM10) VALUES (?,?,?,?,?)'''
|
||||
, (timestamp, sensor_name,PM1,PM25,PM10))
|
||||
INSERT INTO data (timestamp, PM1, PM25, PM10) VALUES (?,?,?,?,?)'''
|
||||
, (timestamp,PM1,PM25,PM10))
|
||||
|
||||
# Commit and close the connection
|
||||
conn.commit()
|
||||
|
||||
Reference in New Issue
Block a user