', end="") print(response2) print("
", end="") #Here it's possible that the SARA do not repond at all or send a error message #-> send notification #-> hardware reboot #-> end loop, no need to continue #1. No answer at all form SARA if response2 is None or response2 == "": print("⚠️ATTENTION: No answer from SARA module") print('🛑STOP LOOP🛑') print("') #print(responseReconnect) #print("
", end="") print('🛑STOP LOOP🛑') print("➡️SEND TO MIOTIQ
', end="") binary_data = payload.get_bytes() print(f"Binary payload: {len(binary_data)} bytes") #print(f"Binary payload: {binary_data}") #create UDP socket (will return socket number) -> 17 is UDP protocol and 6 is TCP protocol # IF ERROR -> need to create the PDP connection print("Create Socket:", end="") 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", "+CME ERROR", "ERROR"], debug=False) print('', end="") print(response_SARA_1) print("
", end="") if "+CME ERROR" in response_SARA_1 or "ERROR" in response_SARA_1: print('⚠️ATTENTION: need to reset PDP connection⚠️') psd_csd_resets = reset_PSD_CSD_connection() if psd_csd_resets: print("✅PSD CSD connection reset successfully") else: print("⛔There were issues with the modem CSD PSD reinitialize process") # Clignotement LED rouge en cas d'erreur led_thread = Thread(target=blink_led, args=(24, 5, 0.5)) led_thread.start() #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}", end="") else: print("Failed to extract socket ID") #Connect to UDP server (USOCO) print("Connect to server:", end="") 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('', end="") print(response_SARA_2) print("
", end="") # Write data and send print(f"Write data: {len(binary_data)} bytes", end="") command = f'AT+USOWR={socket_id},{len(binary_data)}\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('', end="") print(response_SARA_2) print("
", end="") # Send the raw payload bytes (already prepared) ser_sara.write(binary_data) response_SARA_2 = read_complete_response(ser_sara, wait_for_lines=["@","OK", "+CME ERROR", "ERROR"], debug=False) print('', end="") print(response_SARA_2) print("
", end="") #Read reply from server (USORD) #print("Read reply:", end="") #command = f'AT+USORD=0,100\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('') #print(response_SARA_2) #print("
", end="") #Close socket print("Close socket:", end="") 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) #blink green LEDs led_thread = Thread(target=blink_led, args=(23, 5, 0.5)) led_thread.start() print('', end="") print(response_SARA_2) print("
", end="") ''' ____ _____ _ _ ____ _ ___ ____ ____ _ ____ _____ ___ / ___|| ____| \ | | _ \ / \ |_ _| _ \ / ___| / \ | _ \_ _/ _ \ \___ \| _| | \| | | | | / _ \ | || |_) | | / _ \ | |_) || || | | | ___) | |___| |\ | |_| | / ___ \ | || _ <| |___ / ___ \| _ < | || |_| | |____/|_____|_| \_|____/ /_/ \_\___|_| \_\\____/_/ \_\_| \_\|_| \___/ ''' if send_aircarto: print('➡️SEND TO AIRCARTO SERVERS
', end="") # Write Data to saraR4 # 1. Open sensordata_csv.json (with correct data size) csv_string = ','.join(str(value) if value is not None else '' for value in payload_csv) size_of_string = len(csv_string) print("Open JSON:") command = f'AT+UDWNFILE="sensordata_csv.json",{size_of_string}\r' ser_sara.write(command.encode('utf-8')) response_SARA_1 = read_complete_response(ser_sara, wait_for_lines=[">"], debug=False) print('') print(response_SARA_1) print("
", end="") time.sleep(1) #2. Write to shell print("Write data to memory:") ser_sara.write(csv_string.encode()) response_SARA_2 = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) print(f'{response_SARA_2.strip()}
', end="") #3. Send to endpoint (with device ID) print("Send data (POST REQUEST):") command= f'AT+UHTTPC={aircarto_profile_id},4,"/pro_4G/data.php?sensor_id={device_id}&lat={device_latitude_raw}&long={device_longitude_raw}&datetime={influx_timestamp}","aircarto_server_response.txt","sensordata_csv.json",4\r' #print("sending:") #print('') #print(command) #print("
", end="") ser_sara.write(command.encode('utf-8')) response_SARA_3 = read_complete_response(ser_sara, timeout=5, end_of_response_timeout=120, wait_for_lines=["+UUHTTPCR", "+CME ERROR", "ERROR"], debug=True) #print("receiving:") print('') print(response_SARA_3) print("
", end="") # si on recoit la réponse UHTTPCR if "+UUHTTPCR" in response_SARA_3: print("✅ Received +UUHTTPCR response.") # Les types de réponse # 1.La commande n'a pas fonctionné # +CME ERROR: No connection to phone # +CME ERROR: Operation not allowed # 2.La commande fonctionne: elle renvoie un code # +UUHTTPCR:') print(response_SARA_9) print("
", end="") # Extract just the error code error_code = extract_error_code(response_SARA_9) if error_code is not None: # Display interpretation based on error code if error_code == 0: print('No error detected
') # INVALID SERVER HOSTNAME elif error_code == 4: print('Error 4: AirCarto - Invalid server Hostname
') send_error_notification(device_id, "UHTTPER (error n°4) -> AirCarto Invalid Server Hostname") server_hostname_resets = reset_server_hostname(aircarto_profile_id) if server_hostname_resets: print("✅server hostname reset successfully") else: print("⛔There were issues with the modem server hostname reinitialize process") # SERVER CONNECTION ERROR elif error_code == 11: print('Error 11: Server connection error
') hardware_reboot_success = modem_hardware_reboot() if hardware_reboot_success: print("✅Modem successfully rebooted and reinitialized") else: print("⛔There were issues with the modem reboot/reinitialize process") # PSD OR CSD ERROR elif error_code == 22: print('⚠️Error 22: PSD or CSD connection not established (SARA-R5 need to reset PDP conection)⚠️
') send_error_notification(device_id, "UHTTPER (error n°22) -> PSD or CSD connection not established") psd_csd_resets = reset_PSD_CSD_connection() if psd_csd_resets: print("✅PSD CSD connection reset successfully") else: print("⛔There were issues with the modem CSD PSD reinitialize process") # CONNECTION TIMED OUT elif error_code == 26: print('Error 26: Connection timed out
') send_error_notification(device_id, "UHTTPER (error n°26) -> Connection timed out") # CONNECTION LOST elif error_code == 44: print('Error 44: Connection lost
') send_error_notification(device_id, "UHTTPER (error n°44) -> Connection lost") # SECURE SOCKET ERROR elif error_code == 73: print('Error 73: Secure socket connect error
') else: print(f'Unknown error code: {error_code}
') else: print('Could not extract error code from response
') # 2.2 code 1 (✅✅HHTP / UUHTTPCR succeded✅✅) else: print('✅✅HTTP operation successful.') print("Blink blue LED") led_thread = Thread(target=blink_led, args=(23, 5, 0.5)) led_thread.start() #4. Read reply from server print("Reply from server:") command = f'AT+URDFILE="aircarto_server_response.txt""\r' ser_sara.write((command + '\r').encode('utf-8')) response_SARA_4 = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) print('') print(response_SARA_4) print("
", end="") #Parse the server datetime # Extract just the date from the response date_string = None server_datetime = "" date_start = response_SARA_4.find("Date: ") if date_start != -1: date_end = response_SARA_4.find("\n", date_start) date_string = response_SARA_4[date_start + 6:date_end].strip() print(f'Parsed datetime: {server_datetime}
') except Exception as e: print(f'Error parsing date: {e}
') # Get RTC time from SQLite cursor.execute("SELECT * FROM timestamp_table LIMIT 1") row = cursor.fetchone() rtc_time_str = row[1] # '2025-02-07 12:30:45' or '2000-01-01 00:55:21' or 'not connected' print(f'Error comparing times: {e}
') #Si non ne recoit pas de réponse UHTTPCR #on a peut être une ERROR de type "+CME ERROR: No connection to phone" ou "Operation not allowed" ou "ERROR" else: print('No UUHTTPCR response') print("Blink red LED") # Run LED blinking in a separate thread led_thread = Thread(target=blink_led, args=(24, 5, 0.5)) led_thread.start() #Vérification de l'erreur print("Getting type of error") # Split the response into lines and search for "+CME ERROR:" lines2 = response_SARA_3.strip().splitlines() for line in lines2: if "+CME ERROR" in line: error_message = line.split("+CME ERROR:")[1].strip() print("*****") print('⚠️ATTENTION: CME ERROR⚠️') print(f"Error type: {error_message}") print("*****") # Handle "No connection to phone" error if error_message == "No connection to phone": print('📞Try reconnect to network📞') #IMPORTANT! # Reconnexion au réseau (AT+COPS) command = f'AT+COPS=1,2,{selected_networkID}\r' #command = f'AT+COPS=0\r' ser_sara.write(command.encode('utf-8')) responseReconnect = read_complete_response(ser_sara, timeout=5, end_of_response_timeout=120, wait_for_lines=["OK", "+CME ERROR"], debug=True) print('') print(responseReconnect) print("
", end="") # Handle "Operation not allowed" error if error_message == "Operation not allowed": print('❓Try Resetting the HTTP Profile❓') command = f'AT+UHTTP={aircarto_profile_id},1,"data.nebuleair.fr"\r' ser_sara.write(command.encode('utf-8')) responseResetHTTP_profile = read_complete_response(ser_sara, timeout=5, end_of_response_timeout=5, wait_for_lines=["OK", "+CME ERROR"], debug=True) print('') print(responseResetHTTP_profile) print("
", end="") check_lines = responseResetHTTP_profile.strip().splitlines() for line in check_lines: if "+CME ERROR: Operation not allowed" in line: print('⚠️ATTENTION: CME ERROR⚠️') print('❓Try Reboot the module❓') #Software Reboot if "ERROR" in line: print("⛔Attention ERROR!⛔") #Send notification (WIFI) send_error_notification(device_id, "SARA CME ERROR") #Hardware Reboot hardware_reboot_success = modem_hardware_reboot() if hardware_reboot_success: print("✅Modem successfully rebooted and reinitialized") else: print("⛔There were issues with the modem reboot/reinitialize process") #5. empty json print("Empty SARA memory:") command = f'AT+UDELFILE="sensordata_csv.json"\r' ser_sara.write((command + '\r').encode('utf-8')) response_SARA_5 = read_complete_response(ser_sara, wait_for_lines=["OK","+CME ERROR"], debug=True) print('') print(response_SARA_5) print("
", end="") if "+CME ERROR" in response_SARA_5: print("⛔ Attention CME ERROR ⛔") ''' _ ____ _ ___ ___ _ __ __| | _ _/ ___| _ __ ___ | |_ / __|/ _ \ '_ \ / _` | | | | \___ \| '_ \ / _ \| __| \__ \ __/ | | | (_| | | |_| |___) | |_) | (_) | |_ |___/\___|_| |_|\__,_| \__,_|____/| .__/ \___/ \__| |_| ''' if send_uSpot: print('➡️SEND TO uSPOT SERVERS
', end="") # 1. Open sensordata_json.json (with correct data size) print("Open JSON:") payload_string = json.dumps(payload_json) # Convert dict to JSON string size_of_string = len(payload_string) command = f'AT+UDWNFILE="sensordata_json.json",{size_of_string}\r' ser_sara.write((command + '\r').encode('utf-8')) response_SARA_6 = read_complete_response(ser_sara, wait_for_lines=[">"], debug=False) print(response_SARA_6) time.sleep(1) #2. Write to shell print("Write to memory:") ser_sara.write(payload_string.encode()) response_SARA_7 = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) print(response_SARA_7) #step 4: trigger the request (http_command=1 for GET and http_command=1 for POST) print("****") print("Trigger POST REQUEST") command = f'AT+UHTTPC={uSpot_profile_id},4,"/nebuleair?token=2AFF6dQk68daFZ","uSpot_server_response.txt","sensordata_json.json",4\r' ser_sara.write(command.encode('utf-8')) response_SARA_8 = read_complete_response(ser_sara, timeout=5, end_of_response_timeout=120, wait_for_lines=["+UUHTTPCR", "+CME ERROR"], debug=True) print('') print(response_SARA_8) print("
", end="") # si on recoit la réponse UHTTPCR if "+UUHTTPCR" in response_SARA_8: print("✅ Received +UUHTTPCR response.") lines = response_SARA_8.strip().splitlines() # 1.Vérifier si la réponse contient un message d'erreur CME if "+CME ERROR" in lines[-1]: print("*****") print('⛔ATTENTION: CME ERROR') print("error:", lines[-1]) print("*****") #update status # Gestion de l'erreur spécifique if "No connection to phone" in lines[-1]: print("No connection to the phone.") elif "Operation not allowed" in lines[-1]: print("Operation not allowed. This may require a different configuration.") # Actions spécifiques pour ce type d'erreur # Clignotement LED rouge en cas d'erreur led_thread = Thread(target=blink_led, args=(24, 5, 0.5)) led_thread.start() else: # 2.Si la réponse contient une réponse HTTP valide # Extract HTTP response code from the last line # ATTENTION: lines[-1] renvoie l'avant dernière ligne et il peut y avoir un soucis avec le OK # rechercher plutot http_response = lines[-1] # "+UUHTTPCR: 0,4,0" parts = http_response.split(',') # 2.1 code 0 (HTTP failed) if len(parts) == 3 and parts[-1] == '0': # The third value indicates success print("*****") print('⛔ATTENTION: HTTP operation failed') print("*****") print("Blink red LED") # Run LED blinking in a separate thread led_thread = Thread(target=blink_led, args=(24, 5, 0.5)) led_thread.start() # Get error code print("Getting error code", end="") command = f'AT+UHTTPER={uSpot_profile_id}\r' ser_sara.write(command.encode('utf-8')) response_SARA_9b = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) print('') print(response_SARA_9b) print("
", end="") # Extract just the error code error_code = extract_error_code(response_SARA_9b) if error_code is not None: # Display interpretation based on error code if error_code == 0: print('No error detected
') # INVALID SERVER HOSTNAME elif error_code == 4: print('Error 4: uSpot - Invalid server Hostname
', end="") send_error_notification(device_id, "UHTTPER (4) uSpot Invalid server Hostname") server_hostname_resets = reset_server_hostname_https(uSpot_profile_id) if server_hostname_resets: print("✅ uSpot - server hostname reset successfully") else: print("⛔There were issues with the modem server hostname reinitialize process") # SERVER CONNECTION ERROR elif error_code == 11: print('Error 11: Server connection error
', end="") elif error_code == 22: print('Error 22: PSD or CSD connection not established
', end="") elif error_code == 26: print('Error 26: Connection timed out
') elif error_code == 44: print('Error 44: Connection lost
') elif error_code == 73: print('Error 73: uSpot - Secure socket connect error
', end="") send_error_notification(device_id, "uSpot - Secure socket connect error") server_hostname_resets = reset_server_hostname_https(uSpot_profile_id) if server_hostname_resets: print("✅ uSpot - server hostname reset successfully") else: print("⛔There were issues with the modem server hostname reinitialize process") else: print(f'Unknown error code: {error_code}
',end="") else: print('Could not extract error code from response
', end="") #Pas forcément un moyen de résoudre le soucis # 2.2 code 1 (✅✅HHTP / UUHTTPCR succeded✅✅) else: # Si la commande HTTP a réussi print('✅✅HTTP operation successful.') print("Blink blue LED") led_thread = Thread(target=blink_led, args=(23, 5, 0.5)) led_thread.start() #4. Read reply from server print("Reply from server:") command = f'AT+URDFILE="uSpot_server_response.txt"\r' ser_sara.write((command + '\r').encode('utf-8')) response_SARA_4b = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) print('') print(response_SARA_4b) print("
", end="") # Initialize http_response_code to 0 as a default value http_response_code = 0 # Safely extract HTTP code try: http_prefix = "HTTP/" # response_SARA_4b is a string, not a function - use .find() method http_pos = response_SARA_4b.find(http_prefix) if http_pos != -1: # Find the space after the HTTP version space_pos = response_SARA_4b.find(" ", http_pos) if space_pos != -1: # Extract the code after the space code_start = space_pos + 1 code_end = response_SARA_4b.find(" ", code_start) if code_end != -1: # Extract and convert to integer http_code_str = response_SARA_4b[code_start:code_end] http_response_code = int(http_code_str) print(f"HTTP response code: {http_response_code}") if http_response_code == 201: print('✅✅HTTP 201 ressource created.') elif http_response_code == 308: print(' ⚠️⚠️HTTP 308 Redirect, need to set up HTTPS.') server_hostname_resets = reset_server_hostname_https(uSpot_profile_id) if server_hostname_resets: print("✅server hostname reset successfully") else: print("⛔There were issues with the modem server hostname reinitialize process") except Exception as e: # If any error occurs during parsing, keep the default value print(f"Error parsing HTTP code: {e}") #5. empty json print("Empty SARA memory:") command = f'AT+UDELFILE="sensordata_json.json"\r' ser_sara.write((command + '\r').encode('utf-8')) response_SARA_9t = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) print(response_SARA_9t) # Calculate and print the elapsed time elapsed_time = time.time() - start_time_script print(f"Elapsed time: {elapsed_time:.2f} seconds") print("