diff --git a/SARA/reboot/start.py b/SARA/reboot/start.py new file mode 100644 index 0000000..eb2e2ef --- /dev/null +++ b/SARA/reboot/start.py @@ -0,0 +1,163 @@ +''' + ____ _ ____ _ + / ___| / \ | _ \ / \ + \___ \ / _ \ | |_) | / _ \ + ___) / ___ \| _ < / ___ \ + |____/_/ \_\_| \_\/_/ \_\ + +Script that starts at the boot of the RPI + +/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/reboot/start.py + +''' +import serial +import time +import sys +import json +import re + +#get data from config +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 {} + +#Fonction pour mettre à jour le JSON de configuration +def update_json_key(file_path, key, value): + """ + Updates a specific key in a JSON file with a new value. + + :param file_path: Path to the JSON file. + :param key: The key to update in the JSON file. + :param value: The new value to assign to the key. + """ + try: + # Load the existing data + with open(file_path, "r") as file: + data = json.load(file) + + # Check if the key exists in the JSON file + if key in data: + data[key] = value # Update the key with the new value + else: + print(f"Key '{key}' not found in the JSON file.") + return + + # Write the updated data back to the file + with open(file_path, "w") as file: + json.dump(data, file, indent=2) # Use indent for pretty printing + + print(f"💾 updating '{key}' to '{value}'.") + except Exception as e: + print(f"Error updating the JSON file: {e}") + +# Define the config file path +config_file = '/var/www/nebuleair_pro_4g/config.json' +# Load the configuration data +config = load_config(config_file) +baudrate = config.get('SaraR4_baudrate', 115200) #baudrate du sara R4 +device_id = config.get('deviceID', '').upper() #device ID en maj + +ser_sara = serial.Serial( + port='/dev/ttyAMA2', + baudrate=baudrate, #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'[ALERT] ⚠️{total_elapsed_time:.2f}s⚠️') + + return response.decode('utf-8', errors='replace') # Return the full response if no target line is found + +try: + print('

Start reboot python script

') + + # 1. Set AIRCARTO URL + print('Set aircarto URL') + aircarto_profile_id = 0 + aircarto_url="data.nebuleair.fr" + command = f'AT+UHTTP={aircarto_profile_id},1,"{aircarto_url}"\r' + ser_sara.write(command.encode('utf-8')) + response_SARA_1 = read_complete_response(ser_sara, wait_for_lines=["OK"]) + print(response_SARA_1) + time.sleep(1) + + #2. Set uSpot URL (TODO) + uSpot_profile_id = 1 + uSpot_url="api-prod.uspot.probesys.net" + time.sleep(1) + + #3. Get localisation (CellLocate) + mode = 2 + sensor = 2 + response_type = 0 + timeout_s = 2 + accuracy_m = 1 + command = f'AT+ULOC={mode},{sensor},{response_type},{timeout_s},{accuracy_m}\r' + ser_sara.write((command + '\r').encode('utf-8')) + response_SARA_3 = read_complete_response(ser_sara, wait_for_lines=["+UULOC"]) + print(response_SARA_3) + + match = re.search(r"\+UULOC: \d{2}/\d{2}/\d{4},\d{2}:\d{2}:\d{2}\.\d{3},([-+]?\d+\.\d+),([-+]?\d+\.\d+)", response_SARA_3) + if match: + latitude = match.group(1) + longitude = match.group(2) + print(f"📍 Latitude: {latitude}, Longitude: {longitude}") + else: + print("❌ Failed to extract coordinates.") + + #update config.json + update_json_key(config_file, "latitude_raw", float(latitude)) + update_json_key(config_file, "longitude_raw", float(longitude)) + + time.sleep(1) + +except Exception as e: + print("An error occurred:", e) + traceback.print_exc() # This prints the full traceback \ No newline at end of file diff --git a/boot_hotspot.sh b/boot_hotspot.sh index f64dcb4..8dac2f8 100755 --- a/boot_hotspot.sh +++ b/boot_hotspot.sh @@ -2,11 +2,11 @@ # Script to check if wifi is connected and start hotspot if not # will also retreive unique RPi ID and store it to deviceID.txt + OUTPUT_FILE="/var/www/nebuleair_pro_4g/wifi_list.csv" JSON_FILE="/var/www/nebuleair_pro_4g/config.json" - echo "-------------------" echo "-------------------" @@ -28,10 +28,10 @@ done echo "getting SARA R4 serial number" # Get the last 8 characters of the serial number and write to text file serial_number=$(cat /proc/cpuinfo | grep Serial | awk '{print substr($3, length($3) - 7)}') -# Define the JSON file path # Use jq to update the "deviceID" in the JSON file jq --arg serial_number "$serial_number" '.deviceID = $serial_number' "$JSON_FILE" > temp.json && mv temp.json "$JSON_FILE" echo "id: $serial_number" + #get the SSH port for tunneling SSH_TUNNEL_PORT=$(jq -r '.sshTunnel_port' "$JSON_FILE") @@ -56,7 +56,7 @@ if [ "$STATE" == "30 (disconnected)" ]; then else - echo "Success: wlan0 is connected!" + echo "🛜Success: wlan0 is connected!🛜" CONN_SSID=$(nmcli -g GENERAL.CONNECTION device show wlan0) echo "Connection: $CONN_SSID" @@ -66,27 +66,27 @@ else sudo chmod 777 "$JSON_FILE" # Lancer le tunnel SSH - echo "Démarrage du tunnel SSH sur le port $SSH_TUNNEL_PORT..." + #echo "Démarrage du tunnel SSH sur le port $SSH_TUNNEL_PORT..." # Start the SSH agent if it's not already running - eval "$(ssh-agent -s)" + #eval "$(ssh-agent -s)" # Add your SSH private key - ssh-add /home/airlab/.ssh/id_rsa + #ssh-add /home/airlab/.ssh/id_rsa #connections details - REMOTE_USER="airlab_server1" # Remplacez par votre nom d'utilisateur distant - REMOTE_SERVER="aircarto.fr" # Remplacez par l'adresse de votre serveur - LOCAL_PORT=22 # Port local à rediriger - MONITOR_PORT=0 # Désactive la surveillance de connexion autossh + #REMOTE_USER="airlab_server1" # Remplacez par votre nom d'utilisateur distant + #REMOTE_SERVER="aircarto.fr" # Remplacez par l'adresse de votre serveur + #LOCAL_PORT=22 # Port local à rediriger + #MONITOR_PORT=0 # Désactive la surveillance de connexion autossh #autossh -M "$MONITOR_PORT" -f -N -R "$SSH_TUNNEL_PORT:localhost:$LOCAL_PORT" "$REMOTE_USER@$REMOTE_SERVER" -p 50221 # ssh -f -N -R 52221:localhost:22 -p 50221 airlab_server1@aircarto.fr - ssh -i /var/www/.ssh/id_rsa -f -N -R "$SSH_TUNNEL_PORT:localhost:$LOCAL_PORT" -p 50221 -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_SERVER" + #ssh -i /var/www/.ssh/id_rsa -f -N -R "$SSH_TUNNEL_PORT:localhost:$LOCAL_PORT" -p 50221 -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_SERVER" #Check if the tunnel was created successfully - if [ $? -eq 0 ]; then - echo "Tunnel started successfully!" - else - echo "Error: Unable to start the tunnel!" - exit 1 - fi + #if [ $? -eq 0 ]; then + # echo "Tunnel started successfully!" + #else + # echo "Error: Unable to start the tunnel!" + # exit 1 + #fi fi echo "-------------------" diff --git a/cron_jobs b/cron_jobs index 68923c9..9b0ac33 100755 --- a/cron_jobs +++ b/cron_jobs @@ -2,12 +2,6 @@ @reboot /var/www/nebuleair_pro_4g/boot_hotspot.sh >> /var/www/nebuleair_pro_4g/logs/app.log 2>&1 -@reboot sleep 30 && /usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_setURL.py ttyAMA2 data.nebuleair.fr 0 >> /var/www/nebuleair_pro_4g/logs/app.log 2>&1 - -#@reboot sleep 45 && /usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/SSL/prepareUspotProfile.py ttyAMA2 api-prod.uspot.probesys.net >> /var/www/nebuleair_pro_4g/logs/app.log 2>&1 - -#* * * * * /usr/bin/python3 /var/www/nebuleair_pro_4g/loop/1_NPM/send_data.py >> /var/www/nebuleair_pro_4g/logs/loop.log 2>&1 - -#* * * * * flock -n /var/www/nebuleair_pro_4g/loop/1_NPM/send_data.lock /usr/bin/python3 /var/www/nebuleair_pro_4g/loop/1_NPM/send_data.py >> /var/www/nebuleair_pro_4g/logs/loop.log 2>&1 +@reboot sleep 30 && /usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/reboot/start.py >> /var/www/nebuleair_pro_4g/logs/app.log 2>&1 0 0 * * * > /var/www/nebuleair_pro_4g/logs/master.log diff --git a/html/map.html b/html/map.html index c52f861..93ad113 100755 --- a/html/map.html +++ b/html/map.html @@ -184,8 +184,8 @@ function loadConfigAndUpdateMap() { //add a circle var circle = L.circle([device_latitude_raw, device_longitude_raw], { color: 'blue', - fillColor: '#f03', - fillOpacity: 0.5, + fillColor: '#3399FF', + fillOpacity: 0.3, radius: 500 }).addTo(map); @@ -195,13 +195,13 @@ function loadConfigAndUpdateMap() { console.log("Marker moved to:", newLatLng.lat, newLatLng.lng); // Update the input fields with new values - document.getElementById("device_latitude").value = newLatLng.lat; - document.getElementById("device_longitude").value = newLatLng.lng; + document.getElementById("device_latitude_precision").value = newLatLng.lat; + document.getElementById("device_longitude_precision").value = newLatLng.lng; // Call update function to save new values - update_config('latitude', newLatLng.lat); + update_config('latitude_precision', newLatLng.lat); - setTimeout(() => { update_config('longitude', newLatLng.lng); }, 750); + setTimeout(() => { update_config('longitude_precision', newLatLng.lng); }, 750); }); } else { diff --git a/loop/SARA_send_data_v2.py b/loop/SARA_send_data_v2.py index 7d83c21..b7fa0b9 100755 --- a/loop/SARA_send_data_v2.py +++ b/loop/SARA_send_data_v2.py @@ -191,7 +191,7 @@ def update_json_key(file_path, key, value): with open(file_path, "w") as file: json.dump(data, file, indent=2) # Use indent for pretty printing - print(f"updating '{key}' to '{value}'.") + print(f"💾updating '{key}' to '{value}'.") except Exception as e: print(f"Error updating the JSON file: {e}") @@ -200,14 +200,17 @@ config_file = '/var/www/nebuleair_pro_4g/config.json' # Load the configuration data config = load_config(config_file) -baudrate = config.get('SaraR4_baudrate', 115200) #baudrate du sara R4 -device_id = config.get('deviceID', '').upper() #device ID en maj -bme_280_config = config.get('BME280/get_data_v2.py', False) #présence du BME280 +device_latitude_raw = config.get('latitude_raw', 0) +device_longitude_raw = config.get('longitude_raw', 0) + +baudrate = config.get('SaraR4_baudrate', 115200) #baudrate du sara R4 +device_id = config.get('deviceID', '').upper() #device ID en maj +bme_280_config = config.get('BME280/get_data_v2.py', False) #présence du BME280 envea_cairsens= config.get('envea/read_value_v2.py', False) -send_aircarto = config.get('send_aircarto', True) #envoi sur AirCarto (data.nebuleair.fr) -send_uSpot = config.get('send_uSpot', False) #envoi sur MicroSpot () +send_aircarto = config.get('send_aircarto', True) #envoi sur AirCarto (data.nebuleair.fr) +send_uSpot = config.get('send_uSpot', False) #envoi sur MicroSpot () selected_networkID = config.get('SARA_R4_neworkID', '') -npm_5channel = config.get('NextPM_5channels', False) #5 canaux du NPM +npm_5channel = config.get('NextPM_5channels', False) #5 canaux du NPM modem_config_mode = config.get('modem_config_mode', False) #modem 4G en mode configuration @@ -451,7 +454,7 @@ try: #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' + 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}","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"], debug=True)