'''
Script to add the SSL certificate
ex: 
python3 /var/www/nebuleair_pro_4g/SARA/SSL/sara_add_certif.py ttyAMA2 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
timeout = float(parameter[1])  # ex:2

#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)

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
)
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')

try:
    certificate='00:ad:e8:24:73:f4:14:37:f3:9b:9e:2b:57:28:1c:87:be:dc:b7:df:38:90:8c:6e:3c:e6:57:a0:78:f7:75:c2:a2:fe:f5:6a:6e:f6:00:4f:28:db:de:68:86:6c:44:93:b6:b1:63:fd:14:12:6b:bf:1f:d2:ea:31:9b:21:7e:d1:33:3c:ba:48:f5:dd:79:df:b3:b8:ff:12:f1:21:9a:4b:c1:8a:86:71:69:4a:66:66:6c:8f:7e:3c:70:bf:ad:29:22:06:f3:e4:c0:e6:80:ae:e2:4b:8f:b7:99:7e:94:03:9f:d3:47:97:7c:99:48:23:53:e8:38:ae:4f:0a:6f:83:2e:d1:49:57:8c:80:74:b6:da:2f:d0:38:8d:7b:03:70:21:1b:75:f2:30:3c:fa:8f:ae:dd:da:63:ab:eb:16:4f:c2:8e:11:4b:7e:cf:0b:e8:ff:b5:77:2e:f4:b2:7b:4a:e0:4c:12:25:0c:70:8d:03:29:a0:e1:53:24:ec:13:d9:ee:19:bf:10:b3:4a:8c:3f:89:a3:61:51:de:ac:87:07:94:f4:63:71:ec:2e:e2:6f:5b:98:81:e1:89:5c:34:79:6c:76:ef:3b:90:62:79:e6:db:a4:9a:2f:26:c5:d0:10:e1:0e:de:d9:10:8e:16:fb:b7:f7:a8:f7:c7:e5:02:07:98:8f:36:08:95:e7:e2:37:96:0d:36:75:9e:fb:0e:72:b1:1d:9b:bc:03:f9:49:05:d8:81:dd:05:b4:2a:d6:41:e9:ac:01:76:95:0a:0f:d8:df:d5:bd:12:1f:35:2f:28:17:6c:d2:98:c1:a8:09:64:77:6e:47:37:ba:ce:ac:59:5e:68:9d:7f:72:d6:89:c5:06:41:29:3e:59:3e:dd:26:f5:24:c9:11:a7:5a:a3:4c:40:1f:46:a1:99:b5:a7:3a:51:6e:86:3b:9e:7d:72:a7:12:05:78:59:ed:3e:51:78:15:0b:03:8f:8d:d0:2f:05:b2:3e:7b:4a:1c:4b:73:05:12:fc:c6:ea:e0:50:13:7c:43:93:74:b3:ca:74:e7:8e:1f:01:08:d0:30:d4:5b:71:36:b4:07:ba:c1:30:30:5c:48:b7:82:3b:98:a6:7d:60:8a:a2:a3:29:82:cc:ba:bd:83:04:1b:a2:83:03:41:a1:d6:05:f1:1b:c2:b6:f0:a8:7c:86:3b:46:a8:48:2a:88:dc:76:9a:76:bf:1f:6a:a5:3d:19:8f:eb:38:f3:64:de:c8:2b:0d:0a:28:ff:f7:db:e2:15:42:d4:22:d0:27:5d:e1:79:fe:18:e7:70:88:ad:4e:e6:d9:8b:3a:c6:dd:27:51:6e:ff:bc:64:f5:33:43:4f'
    size_of_string = len(certificate)

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

    time.sleep(1)

    ser.write(certificate.encode())
    response_SARA_2 = read_complete_response(ser)
    print("Write to memory:")
    print(response_SARA_2)

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

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

