""" _____ _ ___ _______ _ | ____| \ | \ \ / / ____| / \ | _| | \| |\ \ / /| _| / _ \ | |___| |\ | \ V / | |___ / ___ \ |_____|_| \_| \_/ |_____/_/ \_\ Gather data from envea Sensors and store them to the SQlite table Use the RTC time for the timestamp /usr/bin/python3 /var/www/nebuleair_pro_4g/envea/read_value_v2.py """ import json import serial import time import traceback import sqlite3 from datetime import datetime # Connect to the SQLite database conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db") cursor = conn.cursor() #GET RTC TIME from SQlite cursor.execute("SELECT * FROM timestamp_table LIMIT 1") row = cursor.fetchone() # Get the first (and only) row rtc_time_str = row[1] # '2025-02-07 12:30:45' # Function to load config data 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 {} # Define the config file path config_file = '/var/www/nebuleair_pro_4g/config.json' # Load the configuration data config = load_config(config_file) # Initialize sensors and serial connections envea_sondes = config.get('envea_sondes', []) connected_envea_sondes = [sonde for sonde in envea_sondes if sonde.get('connected', False)] serial_connections = {} if connected_envea_sondes: for device in connected_envea_sondes: port = device.get('port', 'Unknown') name = device.get('name', 'Unknown') try: serial_connections[name] = serial.Serial( port=f'/dev/{port}', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) except serial.SerialException as e: print(f"Error opening serial port for {name}: {e}") global data_h2s, data_no2, data_o3 data_h2s = 0 data_no2 = 0 data_o3 = 0 data_co = 0 data_nh3 = 0 try: if connected_envea_sondes: for device in connected_envea_sondes: name = device.get('name', 'Unknown') coefficient = device.get('coefficient', 1) if name in serial_connections: serial_connection = serial_connections[name] try: serial_connection.write( b"\xFF\x02\x13\x30\x01\x02\x03\x04\x05\x06\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x12\xAF\x88\x03" ) data_envea = serial_connection.readline() if len(data_envea) >= 20: byte_20 = data_envea[19] * coefficient if name == "h2s": data_h2s = byte_20 elif name == "no2": data_no2 = byte_20 elif name == "o3": data_o3 = byte_20 except serial.SerialException as e: print(f"Error communicating with {name}: {e}") except Exception as e: print("An error occurred while gathering data:", e) traceback.print_exc() #print(f" H2S: {data_h2s}, NO2: {data_no2}, O3: {data_o3}") #save to sqlite database try: cursor.execute(''' INSERT INTO data_envea (timestamp,h2s, no2, o3, co, nh3) VALUES (?,?,?,?,?,?)''' , (rtc_time_str,data_h2s,data_no2,data_o3,data_co,data_nh3 )) # Commit and close the connection conn.commit() #print("Sensor data saved successfully!") except Exception as e: print(f"Database error: {e}") conn.close()