'''
  ____    _    ____      _    
 / ___|  / \  |  _ \    / \   
 \___ \ / _ \ | |_) |  / _ \  
  ___) / ___ \|  _ <  / ___ \ 
 |____/_/   \_\_| \_\/_/   \_\
                              
Script to send UDP message

/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/UDP/sendUDP_message.py

'''
import serial
import time
import sys
import json
import re



ser_sara = serial.Serial(
    port='/dev/ttyAMA2',
    baudrate=115200, #115200 ou 9600
    parity=serial.PARITY_NONE, #PARITY_NONE, PARITY_EVEN or PARITY_ODD
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout = 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

try:
    print('Start script')

    # Increase verbosity
    command = f'AT+CMEE=2\r'
    ser_sara.write(command.encode('utf-8'))
    response_SARA_1 = read_complete_response(ser_sara, wait_for_lines=["OK", "ERROR"])
    print(response_SARA_1, end="")
    time.sleep(1)

    # 1. Create SOCKET
    print('➡️Create SOCKET')
    command = f'AT+USOCR=17\r'
    ser_sara.write(command.encode('utf-8'))
    response_SARA_1 = read_complete_response(ser_sara, wait_for_lines=["OK", "ERROR"])
    print(response_SARA_1, end="")
    time.sleep(1)

    # 2. Retreive Socket ID
    match = re.search(r'\+USOCR:\s*(\d+)', response_SARA_1)
    if match:
        socket_id = match.group(1)
        print(f"Socket ID: {socket_id}")
    else:
        print("Failed to extract socket ID")

            
    #3. Connect to UDP server
    print("Connect to server:")
    command = f'AT+USOCO={socket_id},"192.168.0.20",4242\r'
    ser_sara.write(command.encode('utf-8'))
    response_SARA_2 = read_complete_response(ser_sara, wait_for_lines=["OK", "+CME ERROR", "ERROR"], debug=False)
    print(response_SARA_2)

    # 4. Write data and send
    print("Write data:")
    command = f'AT+USOWR={socket_id},10\r'
    ser_sara.write(command.encode('utf-8'))
    response_SARA_2 = read_complete_response(ser_sara, wait_for_lines=["@","OK", "+CME ERROR", "ERROR"], debug=False)
    print(response_SARA_2)

    ser_sara.write("1234567890".encode())
    response_SARA_2 = read_complete_response(ser_sara, wait_for_lines=["@","OK", "+CME ERROR", "ERROR"], debug=False)
    print(response_SARA_2)

    #Close socket
    print("Close socket:")
    command = f'AT+USOCL={socket_id}\r'
    ser_sara.write(command.encode('utf-8'))
    response_SARA_2 = read_complete_response(ser_sara, wait_for_lines=["OK", "+CME ERROR", "ERROR"], debug=False)
    print(response_SARA_2)
       

except Exception as e:
    print("An error occurred:", e)
    traceback.print_exc()  # This prints the full traceback