'''
Script to see get the SARA R4 MQTT config
ex: 
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/MQTT/login_logout.py ttyAMA2 1 2
'''

import serial
import time
import sys
import json

parameter = sys.argv[1:]  # Exclude the script name
#print("Parameters received:")
port='/dev/'+parameter[0] # ex: ttyAMA2
login_logout = int(parameter[1])  # ex:1
timeout = float(parameter[2])  # ex:2


yellow_color = "\033[33m"  # ANSI escape code for yellow
red_color = "\033[31m"     # ANSI escape code for red
reset_color = "\033[0m"   # Reset color to default
green_color = "\033[32m"   # Green

#get baudrate
def load_config(config_file):
    try:
        with open(config_file, 'r') as file:
            config_data = json.load(file)
        return config_data
    except Exception as e:
        print(f"Error loading config file: {e}")
        return {}

def read_complete_response(serial_connection, timeout=2, end_of_response_timeout=2):
    response = bytearray()
    serial_connection.timeout = timeout
    end_time = time.time() + end_of_response_timeout

    while True:
        if serial_connection.in_waiting > 0:
            data = serial_connection.read(serial_connection.in_waiting)
            response.extend(data)
            end_time = time.time() + end_of_response_timeout  # Reset timeout on new data
        elif time.time() > end_time:
            break
        time.sleep(0.1)  # Short sleep to prevent busy waiting

    # Decode the response and filter out empty lines
    decoded_response = response.decode('utf-8')
    non_empty_lines = "\n".join(line for line in decoded_response.splitlines() if line.strip())     

    # Add yellow color to the output
    
    colored_output = f"{yellow_color}{non_empty_lines}\n{reset_color}"

    return colored_output


# Define the config file path
config_file = '/var/www/nebuleair_pro_4g/config.json'
# Load the configuration data
config = load_config(config_file)
# Access the shared variables
baudrate = config.get('SaraR4_baudrate', 115200)

ser = serial.Serial(
    port=port,  #USB0 or ttyS0
    baudrate=baudrate, #115200 ou 9600
    parity=serial.PARITY_NONE, #PARITY_NONE, PARITY_EVEN or PARITY_ODD
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout = timeout
)

command = f'AT+UMQTTC={login_logout}\r'
ser.write((command + '\r').encode('utf-8'))


try:
    response_SARA_1 = read_complete_response(ser)
    print(response_SARA_1) 

except serial.SerialException as e:
    print(f"Error: {e}")

finally:
    if ser.is_open:
        ser.close()
        #print("Serial closed")

