') print(response2) print("
", end="") #Here it's possible that the SARA do not repond at all or send a error message #-> TO DO : harware reboot #-> send notification #-> 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 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(response_SARA_1) 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(response_SARA_2) #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}&datetime={influx_timestamp}","server_response.txt","sensordata_csv.json",4\r' 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('') 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
') elif error_code == 4: print('Error 4: Invalid server Hostname
') send_error_notification(device_id, "UHTTPER (error n°4) -> 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") elif error_code == 11: print('Error 11: Server connection 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") elif error_code == 26: print('Error 26: Connection timed out
') send_error_notification(device_id, "UHTTPER (error n°26) -> Connection timed out") elif error_code == 44: print('Error 44: Connection lost
') send_error_notification(device_id, "UHTTPER (error n°44) -> Connection lost") 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
') #Software Reboot #software_reboot_success = modem_complete_reboot_and_reinitialize(modem_version, aircarto_profile_id) #if software_reboot_success: # print("Modem successfully rebooted and reinitialized") #else: # print("There were issues with the modem reboot/reinitialize process") # 2.2 code 1 (✅✅HHTP / UUHTTPCR succeded✅✅) else: # Si la commande HTTP a réussi print('✅✅HTTP operation successful.') #update SARA_network_status update_config_sqlite('SARA_network_status', 'connected') #4. Read reply from server print("Reply from server:") ser_sara.write(b'AT+URDFILE="server_response.txt"\r') 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 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 etre une ERROR de type "+CME ERROR: No connection to phone" else: print('No UUHTTPCR response') #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.moduleair.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="") if "ERROR" in line: print("⛔Attention ERROR!⛔") #Send notification (WIFI) send_error_notification(device_id, "sara_error") #Software Reboot #software_reboot_success = modem_complete_reboot_and_reinitialize(modem_version, aircarto_profile_id) #if software_reboot_success: # print("Modem successfully rebooted and reinitialized") #else: # print("There were issues with the modem reboot/reinitialize process") #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:") ser_sara.write(b'AT+UDELFILE="sensordata_csv.json"\r') response_SARA_5 = read_complete_response(ser_sara, wait_for_lines=["OK"], debug=False) 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,"/moduleair?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: 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("✅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: Secure socket connect error
', end="") send_error_notification(device_id, "uSpot - Secure socket connect error") #Software Reboot ?? 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("