'''
  _   _ ____  __  __ 
 | \ | |  _ \|  \/  |
 |  \| | |_) | |\/| |
 | |\  |  __/| |  | |
 |_| \_|_|   |_|  |_|
 
Script to get NPM values: ONLY temp and hum
need parameter: port
/usr/bin/python3 /var/www/moduleair_pro_4g/NPM/get_data_temp_hum.py ttyAMA5
'''

import serial
import requests
import json
import sys

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

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

ser.write(b'\x81\x14\x6B')  # Temp and humidity command

while True:
    try:
        byte_data_temp_hum = ser.readline()
        # Decode temperature and humidity values
        temperature = int.from_bytes(byte_data_temp_hum[3:5], byteorder='big') / 100.0
        humidity = int.from_bytes(byte_data_temp_hum[5:7], byteorder='big') / 100.0

        print(f"temp: {temperature}")
        print(f"hum: {humidity}")
        break
    except KeyboardInterrupt:
        print("User interrupt encountered. Exiting...")
        time.sleep(3)
        exit()
    except:
        # for all other kinds of error, but not specifying which one
        print("Unknown error...")
        time.sleep(3)
        exit()

