""" Network connectivity and backup data handling """ import subprocess import time import requests import logging from config_settings import CONNECTIVITY_CHECK_HOST, CONNECTIVITY_CHECK_INTERVAL, TAG_FILE from logger_module import log_with_server def check_internet_connection(hostname, device_ip, on_connect_callback=None): """ Check internet connection periodically Args: hostname: Device hostname device_ip: Device IP on_connect_callback: Optional callback function when internet is restored """ log_with_server('Internet connection check loaded', hostname, device_ip) while True: try: # Check connection to the specified host response = subprocess.run( ["ping", "-c", "1", CONNECTIVITY_CHECK_HOST], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5 ) if response.returncode == 0: log_with_server(f"Internet is up! Waiting {CONNECTIVITY_CHECK_INTERVAL}s.", hostname, device_ip) # Call callback if internet restored if on_connect_callback: try: on_connect_callback() except Exception as e: log_with_server(f"Callback error: {e}", hostname, device_ip) time.sleep(CONNECTIVITY_CHECK_INTERVAL) else: log_with_server("Internet is down", hostname, device_ip) time.sleep(10) # Retry every 10 seconds when offline except subprocess.TimeoutExpired: log_with_server("Ping timeout", hostname, device_ip) time.sleep(10) except Exception as e: log_with_server(f"Connection check error: {e}", hostname, device_ip) time.sleep(10) def post_backup_data(hostname, device_ip): """ Post backup data to Harting server Reads URLs from tag.txt and attempts to POST to each one Args: hostname: Device hostname device_ip: Device IP """ try: with open(TAG_FILE, "r") as file: lines = file.readlines() remaining_lines = lines[:] for line in lines: line = line.strip() if line: try: response = requests.post(line, verify=False, timeout=3) response.raise_for_status() log_with_server(f"Data posted successfully to {line}", hostname, device_ip) remaining_lines.remove(line + "\n") except requests.exceptions.Timeout: log_with_server("Request timed out.", hostname, device_ip) break except requests.exceptions.RequestException as e: log_with_server(f"An error occurred posting data: {e}", hostname, device_ip) break # Update tag file with remaining lines with open(TAG_FILE, "w") as file: file.writelines(remaining_lines) except FileNotFoundError: log_with_server("No backup file found.", hostname, device_ip) except Exception as e: log_with_server(f"Error posting backup data: {e}", hostname, device_ip)