'''
Script to get CO2 values from MH-Z19 sensor and write to database
/usr/bin/python3 /var/www/nebuleair_pro_4g/MH-Z19/write_data.py
'''

import serial
import json
import sys
import time
import sqlite3

conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db")
cursor = conn.cursor()

mh_z19_port = "/dev/ttyAMA4"

ser = serial.Serial(
    port=mh_z19_port,
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)

READ_CO2_COMMAND = b'\xFF\x01\x86\x00\x00\x00\x00\x00\x79'


def read_co2():
    ser.write(READ_CO2_COMMAND)
    time.sleep(2)
    response = ser.read(9)
    if len(response) < 9:
        print("Error: No data or incomplete data received from CO2 sensor.")
        return None
    if response[0] == 0xFF:
        co2_concentration = response[2] * 256 + response[3]
        return co2_concentration
    else:
        print("Error reading data from CO2 sensor.")
        return None


def main():
    try:
        co2 = read_co2()
        if co2 is not None:
            # Get RTC time from SQLite
            cursor.execute("SELECT * FROM timestamp_table LIMIT 1")
            row = cursor.fetchone()
            rtc_time_str = row[1]
            # Save to SQLite
            cursor.execute('INSERT INTO data_MHZ19 (timestamp, CO2) VALUES (?, ?)', (rtc_time_str, co2))
            conn.commit()
            print(f"CO2: {co2} ppm (saved at {rtc_time_str})")
        else:
            print("Failed to get CO2 data.")
    except KeyboardInterrupt:
        print("Program terminated.")
    finally:
        ser.close()
        conn.close()


if __name__ == '__main__':
    main()
