'''
Script to set the URL for a HTTP request
Ex:
/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/prepareUspotProfile.py ttyAMA2 api-prod.uspot.probesys.net
To do: need to add profile id as parameter

First profile id:
    AT+UHTTP=0,1,"data.nebuleair.fr"
Second profile id:
    AT+UHTTP=1,1,"api-prod.uspot.probesys.net"
'''

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
url = parameter[1]  # ex: data.mobileair.fr


#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 {}

# 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)
send_uSpot = config.get('send_uSpot', False) 

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

    return response.decode('utf-8', errors='replace')

ser_sara = 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 = 2
)



try:
    #step 1: import the certificate
    print("****")
    print("Add certificate")
    with open("/var/www/nebuleair_pro_4g/SARA/SSL/isrgrootx1.der", "rb") as cert_file:
        certificate = cert_file.read()

    size_of_string = len(certificate)

    command = f'AT+USECMNG=0,0,"myCertificate2",{size_of_string}\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_1 = read_complete_response(ser_sara)
    print("Write certificate metadata")
    print(response_SARA_1)

    time.sleep(1)

    ser_sara.write(certificate)
    response_SARA_2 = read_complete_response(ser_sara)
    print("Write certificate data")
    print(response_SARA_2)

    time.sleep(1)

    #step 2: set the security profile 2 to trusted root

    print("****")
    print("SET security profile")
    command = f'AT+USECPRF=2,0,1\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_3 = read_complete_response(ser_sara)
    print(response_SARA_3)
    time.sleep(1)

    #step 3: set the security profile 2 to the imported certificate

    print("****")
    print("SET certificate")
    command = f'AT+USECPRF=2,3,"myCertificate2"\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_4 = read_complete_response(ser_sara)
    print(response_SARA_4)
    time.sleep(1)

    #step 4: set url
    print("****")
    print("SET URL")
    command = f'AT+UHTTP=1,1,"{url}"\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_5 = read_complete_response(ser_sara)
    print(response_SARA_5)
    time.sleep(1)

    #step 4: set url
    print("****")
    print("SET PORT")
    command = f'AT+UHTTP=1,5,443\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_55 = read_complete_response(ser_sara)
    print(response_SARA_55)
    time.sleep(1)


    #step 4: set url to SSL
    print("****")
    print("SET SSL")
    command = f'AT+UHTTP=1,6,1,2\r'
    ser_sara.write((command + '\r').encode('utf-8'))
    response_SARA_5 = read_complete_response(ser_sara)
    print(response_SARA_5)
    time.sleep(1)

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

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

