""" Device information management Handles hostname, IP address, and device configuration """ import socket import os from config_settings import DEVICE_INFO_FILE def get_device_info(): """ Get hostname and device IP with file-based fallback Returns tuple: (hostname, device_ip) """ hostname = None device_ip = None # Try to get current hostname and IP try: hostname = socket.gethostname() device_ip = socket.gethostbyname(hostname) print(f"Successfully resolved - Hostname: {hostname}, IP: {device_ip}") # Save the working values to file for future fallback try: os.makedirs(os.path.dirname(DEVICE_INFO_FILE), exist_ok=True) with open(DEVICE_INFO_FILE, "w") as f: f.write(f"{hostname}\n{device_ip}\n") print(f"Saved device info to {DEVICE_INFO_FILE}") except Exception as e: print(f"Warning: Could not save device info to file: {e}") return hostname, device_ip except socket.gaierror as e: print(f"Socket error occurred: {e}") print("Attempting to load device info from file...") # Try to load from file try: with open(DEVICE_INFO_FILE, "r") as f: lines = f.read().strip().split('\n') if len(lines) >= 2: hostname = lines[0].strip() device_ip = lines[1].strip() print(f"Loaded from file - Hostname: {hostname}, IP: {device_ip}") return hostname, device_ip else: print("File exists but doesn't contain valid data") except FileNotFoundError: print(f"No fallback file found at {DEVICE_INFO_FILE}") except Exception as e: print(f"Error reading fallback file: {e}") except Exception as e: print(f"Unexpected error getting device info: {e}") # Try to load from file as fallback try: with open(DEVICE_INFO_FILE, "r") as f: lines = f.read().strip().split('\n') if len(lines) >= 2: hostname = lines[0].strip() device_ip = lines[1].strip() print(f"Loaded from file after error - Hostname: {hostname}, IP: {device_ip}") return hostname, device_ip except Exception as file_error: print(f"Could not load from file: {file_error}") # Final fallback if everything fails print("All methods failed - Using default values") hostname = hostname or "unknown-device" device_ip = "127.0.0.1" # Try to save these default values for next time try: os.makedirs(os.path.dirname(DEVICE_INFO_FILE), exist_ok=True) with open(DEVICE_INFO_FILE, "w") as f: f.write(f"{hostname}\n{device_ip}\n") print(f"Saved fallback values to {DEVICE_INFO_FILE}") except Exception as e: print(f"Could not save fallback values: {e}") return hostname, device_ip