'''
Script to get CO2 values from MH-Z19 sensor
need parameter: CO2_port
/usr/bin/python3 /var/www/nebuleair_pro_4g/MH-Z19/get_data.py ttyAMA4
'''

import serial
import json
import sys
import time

parameter = sys.argv[1:]
port = '/dev/' + parameter[0]


def read_co2():
    try:
        ser = serial.Serial(
            port=port,
            baudrate=9600,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
        )
    except serial.SerialException as e:
        print(json.dumps({"error": f"Serial port error: {e}"}))
        return

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

    try:
        ser.write(READ_CO2_COMMAND)
        time.sleep(2)
        response = ser.read(9)

        if len(response) < 9:
            print(json.dumps({"error": "No data or incomplete data received from sensor"}))
            return

        if response[0] == 0xFF:
            co2_concentration = response[2] * 256 + response[3]
            print(json.dumps({"CO2": co2_concentration}))
        else:
            print(json.dumps({"error": "Invalid response from sensor"}))
    except Exception as e:
        print(json.dumps({"error": str(e)}))
    finally:
        ser.close()


if __name__ == '__main__':
    read_co2()
