'''
  ____  _____ _    _____  ___  
 / ___||  ___/ \  |___ / / _ \ 
 \___ \| |_ / _ \   |_ \| | | |
  ___) |  _/ ___ \ ___) | |_| |
 |____/|_|/_/   \_\____/ \___/ 
                               
Read data from sensor (only once)
/usr/bin/python3 /var/www/moduleair_pro_4g/sensirion/SFA30_read.py
'''

import time
import json
import sqlite3

from sensirion_shdlc_driver import ShdlcSerialPort, ShdlcConnection
from sensirion_shdlc_sfa3x import Sfa3xShdlcDevice

# Connect to the SQLite database
DB_PATH = "/var/www/moduleair_pro_4g/sqlite/sensors.db"
SERIAL_PORT = '/dev/ttyAMA5'


try:
    # Connect to the SQLite database
    #print("Connecting to database...")
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    # Connect to the device with default settings:
    #  - baudrate:      115200
    #  - slave address: 0
    #print(f"Connecting to Sensirion SFA3X on {SERIAL_PORT}...")
    with ShdlcSerialPort(port=SERIAL_PORT, baudrate=115200) as port:
        device = Sfa3xShdlcDevice(ShdlcConnection(port), slave_address=0)
        device.device_reset()

        # Print device information
        #print("Device Marking: {}".format(device.get_device_marking()))

        # Start measurement
        device.start_measurement()
        #print("Measurement started... ")
        
        time.sleep(5.)
        hcho, humidity, temperature = device.read_measured_values()

        # Prepare data as a JSON object
        data = {
            "formaldehyde_ppb": hcho.ppb,
            "humidity_percent": humidity.percent_rh,
            "temperature_celsius": temperature.degrees_celsius,
        }
            
        # Convert the dictionary to a JSON string
        json_output = json.dumps(data, indent=4)
        #print(json_output)

        #print("Getting RTC time...")
        cursor.execute("SELECT * FROM timestamp_table LIMIT 1")
        row = cursor.fetchone()
        rtc_time_str = row[1] if row else time.strftime("%Y-%m-%d %H:%M:%S")

        # Save to database
        #print(f"Saving readings to database: HCHO={hcho.ppb} ppb, Time={rtc_time_str}")
        cursor.execute('''
        INSERT INTO data_sensirionSFA30 (timestamp, CH2O) VALUES (?, ?)
        ''', (rtc_time_str, hcho.ppb))
        conn.commit()


except Exception as e:
    print(f"Error: {e}")
finally:
    # Close database connection if it exists
    if 'conn' in locals():
        conn.close()
        #print("Database connection closed")