'''
   ____ ___ ____  
  / ___/ _ \___ \ 
 | |  | | | |__) |
 | |__| |_| / __/ 
  \____\___/_____|
                  
Script to get CO2 values
need parameter: CO2_port
/usr/bin/python3 /var/www/moduleair_pro_4g/MH-Z19/get_data.py ttyAMA4
'''

import serial
import requests
import json
import sys
import subprocess
import time

parameter = sys.argv[1:]  # Exclude the script name
#print("Parameters received:")
port='/dev/'+parameter[0]

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


# Command to read CO2 concentration
# Contains 9 bytes (byte 0 ~ 8) 
# FIRST byte:  fixed to 0xFF
# SECOND byte:  sensor number (factory default is 0 x01)
# THIRD byte:  0x86 Gas Concentration

# end with proof test value Checksum 
 

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


def read_co2():
    # Send the read command to the MH-Z19
    ser.write(READ_CO2_COMMAND)
    
    # Wait for the response from the sensor
    time.sleep(2)  # Wait for the sensor to respond
    
    # Read the response from the sensor (9 bytes expected)
    response = ser.read(9)

    # Print the response to debug
    # print(f"Response: {response}")

    # Check if the response is valid (the first byte should be 0xFF)
    if len(response) < 9:
        print("Error: No data or incomplete data received.")
        return None

    if response[0] == 0xFF:
        # Extract the CO2 concentration value (byte 2 and 3)
        co2_concentration = response[2] * 256 + response[3]
        return co2_concentration
    else:
        print("Error reading data from sensor.")
        return None

def main():
    try:
        co2 = read_co2()
        if co2 is not None:
           # Create a dictionary to store the data
            data = {
                "CO2": co2
            }
            
            # Convert the dictionary to a JSON string
            json_data = json.dumps(data)
            print(json_data)  # Output the JSON string
        else:
            print("Failed to get CO2 data.")

    except KeyboardInterrupt:
        print("Program terminated.")
    finally:
        ser.close()

if __name__ == '__main__':
    main()
