|
9 | 9 | import yaml |
10 | 10 | from pathlib import Path |
11 | 11 | from delay_simulator import DelaySimulator |
| 12 | +import socket |
| 13 | +import ipaddress |
| 14 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
12 | 15 |
|
13 | 16 | # Get the directory where this script is located |
14 | 17 | SCRIPT_DIR = Path(__file__).resolve().parent |
|
22 | 25 | DEVICE_ID = config["client"]["device_id"] |
23 | 26 | SERVER_HOST = config["http"]["server_host"] |
24 | 27 | SERVER_PORT = config["http"]["server_port"] |
| 28 | + |
| 29 | +# Discovery functions |
| 30 | +def get_local_network(): |
| 31 | + """Get the local network IP range for scanning.""" |
| 32 | + try: |
| 33 | + # Get local IP address |
| 34 | + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 35 | + s.connect(("8.8.8.8", 80)) |
| 36 | + local_ip = s.getsockname()[0] |
| 37 | + s.close() |
| 38 | + |
| 39 | + # Convert to network/24 (assuming typical home network) |
| 40 | + network = ipaddress.IPv4Network(f"{local_ip}/24", strict=False) |
| 41 | + return network, local_ip |
| 42 | + except Exception as e: |
| 43 | + print(f"Error getting local network: {e}") |
| 44 | + return None, None |
| 45 | + |
| 46 | +def check_server_at_ip(ip, port, timeout=1.0): |
| 47 | + """Check if a server is responding at the given IP:port.""" |
| 48 | + try: |
| 49 | + # First try TCP connection |
| 50 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 51 | + sock.settimeout(timeout) |
| 52 | + result = sock.connect_ex((str(ip), port)) |
| 53 | + sock.close() |
| 54 | + |
| 55 | + if result == 0: |
| 56 | + # Port is open, verify it's our server by trying multiple methods |
| 57 | + try: |
| 58 | + # Try 1: POST to registration endpoint (proper way) |
| 59 | + test_url = f"http://{ip}:{port}{config['http']['endpoints']['registration']}" |
| 60 | + response = requests.post(test_url, json={"device_id": "discovery_test"}, timeout=2) |
| 61 | + if response.status_code in [200, 201, 400, 409]: # Any reasonable server response |
| 62 | + print(f" Found server at {ip}:{port} (registration: {response.status_code})") |
| 63 | + return str(ip) |
| 64 | + except requests.exceptions.RequestException: |
| 65 | + pass |
| 66 | + |
| 67 | + try: |
| 68 | + # Try 2: GET request to root or any endpoint |
| 69 | + response = requests.get(f"http://{ip}:{port}/", timeout=2) |
| 70 | + if response.status_code < 500: # Any response except server error |
| 71 | + print(f" Found server at {ip}:{port} (root: {response.status_code})") |
| 72 | + return str(ip) |
| 73 | + except requests.exceptions.RequestException: |
| 74 | + pass |
| 75 | + |
| 76 | + try: |
| 77 | + # Try 3: Check offloading_layer endpoint |
| 78 | + test_url = f"http://{ip}:{port}{config['http']['endpoints']['offloading_layer']}" |
| 79 | + response = requests.get(test_url, timeout=2) |
| 80 | + if response.status_code in [200, 400, 404, 405]: |
| 81 | + print(f" Found server at {ip}:{port} (offload endpoint: {response.status_code})") |
| 82 | + return str(ip) |
| 83 | + except requests.exceptions.RequestException: |
| 84 | + pass |
| 85 | + |
| 86 | + return None |
| 87 | + except Exception as e: |
| 88 | + return None |
| 89 | + |
| 90 | +def discover_server(port): |
| 91 | + """Scan local network to discover server.""" |
| 92 | + print("="*60) |
| 93 | + print("SERVER DISCOVERY MODE") |
| 94 | + print("="*60) |
| 95 | + |
| 96 | + # First, try common local addresses |
| 97 | + print(f"Checking localhost and common addresses on port {port}...\n") |
| 98 | + common_hosts = ["127.0.0.1", "localhost", "0.0.0.0"] |
| 99 | + |
| 100 | + for host in common_hosts: |
| 101 | + print(f" Trying {host}:{port}...") |
| 102 | + result = check_server_at_ip(host, port, timeout=2.0) |
| 103 | + if result: |
| 104 | + print(f"\nServer found at {result}:{port}") |
| 105 | + return result |
| 106 | + |
| 107 | + print("\nNo server on localhost, scanning local network...\n") |
| 108 | + |
| 109 | + network, local_ip = get_local_network() |
| 110 | + if not network: |
| 111 | + print("ERROR: Could not determine local network") |
| 112 | + return None |
| 113 | + |
| 114 | + print(f"Local IP: {local_ip}") |
| 115 | + print(f"Scanning network: {network}") |
| 116 | + print(f"This may take 10-30 seconds...\n") |
| 117 | + |
| 118 | + # Scan network with threading for speed |
| 119 | + found_servers = [] |
| 120 | + total_hosts = network.num_addresses - 2 # Exclude network and broadcast |
| 121 | + checked = 0 |
| 122 | + |
| 123 | + with ThreadPoolExecutor(max_workers=50) as executor: |
| 124 | + futures = {executor.submit(check_server_at_ip, ip, port): ip |
| 125 | + for ip in network.hosts() if str(ip) != local_ip} |
| 126 | + |
| 127 | + for future in as_completed(futures): |
| 128 | + checked += 1 |
| 129 | + if checked % 25 == 0: |
| 130 | + print(f"Progress: {checked}/{total_hosts} hosts checked...") |
| 131 | + |
| 132 | + result = future.result() |
| 133 | + if result: |
| 134 | + found_servers.append(result) |
| 135 | + print(f"\nSERVER FOUND: {result}:{port}") |
| 136 | + # Cancel remaining futures for faster completion |
| 137 | + for f in futures: |
| 138 | + f.cancel() |
| 139 | + break |
| 140 | + |
| 141 | + print(f"\nScan complete: {checked}/{total_hosts} hosts checked") |
| 142 | + |
| 143 | + if found_servers: |
| 144 | + selected = found_servers[0] |
| 145 | + print(f"\nSelected server: {selected}:{port}") |
| 146 | + return selected |
| 147 | + else: |
| 148 | + print("\nNo server found on local network") |
| 149 | + print(" Please check:") |
| 150 | + print(" 1. Server is running") |
| 151 | + print(" 2. Server is on the same network") |
| 152 | + print(f" 3. Server is listening on port {port}") |
| 153 | + return None |
| 154 | + |
| 155 | +# Run discovery if SERVER_HOST is None |
| 156 | +if SERVER_HOST is None or SERVER_HOST == "None" or SERVER_HOST == "": |
| 157 | + print("\nSERVER_HOST is not configured - starting discovery...\n") |
| 158 | + discovered_host = discover_server(SERVER_PORT) |
| 159 | + |
| 160 | + if discovered_host: |
| 161 | + SERVER_HOST = discovered_host |
| 162 | + print(f"\nUsing discovered server: {SERVER_HOST}:{SERVER_PORT}\n") |
| 163 | + else: |
| 164 | + print("\nWARNING: No server discovered - will run in LOCAL-ONLY mode") |
| 165 | + SERVER_HOST = "localhost" # Fallback to avoid errors |
| 166 | + |
25 | 167 | SERVER = f"http://{SERVER_HOST}:{SERVER_PORT}" |
26 | 168 |
|
27 | 169 | MODEL_CONFIG = config["model"] |
|
0 commit comments