"""
  _____ _   ___     _______    _    
 | ____| \ | \ \   / / ____|  / \   
 |  _| |  \| |\ \ / /|  _|   / _ \  
 | |___| |\  | \ V / | |___ / ___ \ 
 |_____|_| \_|  \_/  |_____/_/   \_\
                                    
Main loop to gather data from envea Sensors
Need to run every minutes

* * * * * /usr/bin/python3 /var/www/nebuleair_pro_4g/envea/read_value_loop.py

Save data to .txt file inside /var/www/nebuleair_pro_4g/envea/data/
"""
import json
import serial
import time
import traceback
from datetime import datetime

# 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 {}

# Function to save the mean to a file
def save_mean_to_file(filename, mean_value):
    try:
        with open(filename, 'w') as file:  # Append mode to keep a history
            file.write(f"{mean_value}\n")
    except Exception as e:
        print(f"Error saving to file {filename}: {e}")

# 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}")

# Function to gather data
def gather_data():
    global data_h2s, data_no2, data_o3
    data_h2s = 0
    data_no2 = 0
    data_o3 = 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()

# Main loop
if __name__ == "__main__":
    h2s_values = []
    no2_values = []
    o3_values = []

    for cycle in range(6):  # Run 6 times
        gather_data()
        h2s_values.append(data_h2s)
        no2_values.append(data_no2)
        o3_values.append(data_o3)

        print(f"Cycle {cycle + 1}:")
        print(f"  H2S: {data_h2s}, NO2: {data_no2}, O3: {data_o3}")
        time.sleep(2)  # Wait 10 seconds

    # Calculate the means
    mean_h2s = sum(h2s_values) / len(h2s_values) if h2s_values else 0
    mean_no2 = sum(no2_values) / len(no2_values) if no2_values else 0
    mean_o3 = sum(o3_values) / len(o3_values) if o3_values else 0

    print(f"Mean H2S: {mean_h2s}, Mean NO2: {mean_no2}, Mean O3: {mean_o3}")

    # Save the means to files
    save_mean_to_file('/var/www/nebuleair_pro_4g/envea/data/data_h2s.txt', mean_h2s)
    save_mean_to_file('/var/www/nebuleair_pro_4g/envea/data/data_no2.txt', mean_no2)
    save_mean_to_file('/var/www/nebuleair_pro_4g/envea/data/data_o3.txt', mean_o3)
