Refactor: Skip socket resolution, load device hostname/IP directly from file

- Remove socket.gethostname() and socket.gethostbyname() calls
- Device info now loads exclusively from device_info.txt
- Device hostname and IP are independent of server hostname
- Resolves DNS/socket errors on startup
- Device info file is primary config source for device identity
This commit is contained in:
Developer
2025-12-18 14:14:52 +02:00
parent b12c47d01f
commit a50197a9d6
2 changed files with 29 additions and 61 deletions

View File

@@ -1,2 +1,2 @@
TestLinux RPI-Device
127.0.1.1 192.168.1.100

View File

@@ -1,85 +1,53 @@
""" """
Device information management Device information management
Handles hostname, IP address, and device configuration Handles hostname and IP address of the device
Uses file-based configuration for reliability
""" """
import socket
import os import os
from config_settings import DEVICE_INFO_FILE from config_settings import DEVICE_INFO_FILE
def get_device_info(): def get_device_info():
""" """
Get hostname and device IP with file-based fallback Get device hostname and IP from configuration file
Returns tuple: (hostname, device_ip) Returns tuple: (hostname, device_ip)
The hostname and IP are read from device_info.txt which should be
configured with the device's own hostname and IP address.
""" """
hostname = None hostname = None
device_ip = None device_ip = None
# Try to get current hostname and IP # Load device info from file (primary method - no socket resolution)
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: try:
os.makedirs(os.path.dirname(DEVICE_INFO_FILE), exist_ok=True) 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: with open(DEVICE_INFO_FILE, "r") as f:
lines = f.read().strip().split('\n') lines = f.read().strip().split('\n')
if len(lines) >= 2: if len(lines) >= 2:
hostname = lines[0].strip() hostname = lines[0].strip()
device_ip = lines[1].strip() device_ip = lines[1].strip()
print(f"Loaded from file - Hostname: {hostname}, IP: {device_ip}") print(f"Device Info - Hostname: {hostname}, IP: {device_ip}")
return hostname, device_ip return hostname, device_ip
else: else:
print("File exists but doesn't contain valid data") print(f"Warning: {DEVICE_INFO_FILE} exists but lacks valid data")
except FileNotFoundError: except FileNotFoundError:
print(f"No fallback file found at {DEVICE_INFO_FILE}") print(f"Device info file not found at {DEVICE_INFO_FILE}")
except Exception as e: except Exception as e:
print(f"Error reading fallback file: {e}") print(f"Error reading device info file: {e}")
except Exception as e: # Fallback if file doesn't exist or has issues
print(f"Unexpected error getting device info: {e}") print("Using default device values")
hostname = "prezenta-device"
device_ip = "192.168.1.100"
# Try to load from file as fallback # Create file with default values for future use
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: try:
os.makedirs(os.path.dirname(DEVICE_INFO_FILE), exist_ok=True) os.makedirs(os.path.dirname(DEVICE_INFO_FILE), exist_ok=True)
with open(DEVICE_INFO_FILE, "w") as f: with open(DEVICE_INFO_FILE, "w") as f:
f.write(f"{hostname}\n{device_ip}\n") f.write(f"{hostname}\n{device_ip}\n")
print(f"Saved fallback values to {DEVICE_INFO_FILE}") print(f"Created device info file with defaults: {hostname}, {device_ip}")
except Exception as e: except Exception as e:
print(f"Could not save fallback values: {e}") print(f"Warning: Could not create device info file: {e}")
return hostname, device_ip return hostname, device_ip