r'''
  ____    _    ____      _    
 / ___|  / \  |  _ \    / \   
 \___ \ / _ \ | |_) |  / _ \  
  ___) / ___ \|  _ <  / ___ \ 
 |____/_/   \_\_| \_\/_/   \_\

Script to connect SARA-R410 to network SARA-R410
python3 /var/www/nebuleair_pro_4g/SARA/sara_connectNetwork.py ttyAMA2 20801 10

AT+COPS=1,2,20801
mode->1 pour manual
format->2 pour numeric
operator->20801 pour orange, 20810 pour SFR

'''

import serial
import time
import sys
import json

parameter = sys.argv[1:]  # Exclude the script name
port='/dev/'+parameter[0] # ex: ttyAMA2
networkID = parameter[1]  # ex: 20801
timeout = float(parameter[2])  # ex:2




def read_complete_response(serial_connection, timeout=2, end_of_response_timeout=2, wait_for_lines=None, debug=True):
    '''
    Fonction très importante !!!
    Reads the complete response from a serial connection and waits for specific lines.
    '''
    if wait_for_lines is None:
        wait_for_lines = []  # Default to an empty list if not provided

    response = bytearray()
    serial_connection.timeout = timeout
    end_time = time.time() + end_of_response_timeout
    start_time = time.time()

    while True:
        elapsed_time = time.time() - start_time  # Time since function start
        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

            # Decode and check for any target line
            decoded_response = response.decode('utf-8', errors='replace')
            for target_line in wait_for_lines:
                if target_line in decoded_response:
                    if debug:
                        print(f"[DEBUG] 🔎 Found target line: {target_line} (in {elapsed_time:.2f}s)")
                    return decoded_response  # Return response immediately if a target line is found
        elif time.time() > end_time:
            if debug:
                print(f"[DEBUG] Timeout reached. No more data received.")
            break
        time.sleep(0.1)  # Short sleep to prevent busy waiting

    # Final response and debug output
    total_elapsed_time = time.time() - start_time
    if debug:
        print(f"[DEBUG] ⏱️ elapsed time: {total_elapsed_time:.2f}s. ⏱️")
    # Check if the elapsed time exceeded 10 seconds
    if total_elapsed_time > 10 and debug:
        print(f"[ALERT] 🚨 The operation took too long 🚨")
        print(f'<span style="color: red;font-weight: bold;">[ALERT] ⚠️{total_elapsed_time:.2f}s⚠️</span>')

    return response.decode('utf-8', errors='replace')  # Return the full response if no target line is found


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+COPS=1,2,"{networkID}"\r'
ser.write((command + '\r').encode('utf-8'))


try:
    response = read_complete_response(ser, wait_for_lines=["OK", "ERROR"],timeout=5, end_of_response_timeout=120, debug=True)
    
    print('<p class="text-danger-emphasis">')
    print(response)
    print("</p>", end="")

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

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

