auto ip configuration

This commit is contained in:
2025-10-06 11:33:38 +02:00
parent 6306cfc374
commit 296a8f5d51
2 changed files with 122 additions and 121 deletions

View File

@ -1,23 +1,9 @@
import socket
import threading
from datetime import datetime
from time import sleep
CONTROL_ADDR = ("127.0.0.1", 5001)
# TODO: Adjust the following addresses so they match the IP addresses of the
# VR headsets.
# In our case the IP addresses were:
# - for player 1: 10.42.0.38
# - for player 2: 10.42.0.72
#
# The ports are hardcoded to 5001 inside the Unity application, so you
# shouldn't change those.
#
# Note: For this to work the VR headsets must be connected to the same network
# as this server.
DEVICE1_ADDR = ("10.42.0.38", 5001)
DEVICE2_ADDR = ("10.42.0.72", 5001)
# Track connected devices dynamically
# No manual IP configuration needed!
connected_devices = {} # {ip: last_seen_timestamp}
sock_from_A = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_from_A.bind(("0.0.0.0", 5000))
@ -26,30 +12,36 @@ def forward(source_socket):
while True:
try:
data, addr = source_socket.recvfrom(1024 * 16)
target_ip = DEVICE1_ADDR[0] if addr[0] == DEVICE2_ADDR[0] else DEVICE2_ADDR[0]
label = "A→B" if addr == DEVICE1_ADDR else "B→A"
if addr != DEVICE1_ADDR and addr != DEVICE2_ADDR:
label = f"unknown {addr}"
source_ip = addr[0]
timestamp = datetime.now()
# Forward to other player
sock_from_A.sendto(data, (target_ip, 5000))
# Register this device
connected_devices[source_ip] = timestamp
# Get list of other active devices (excluding localhost and source)
other_devices = [ip for ip in connected_devices.keys()
if ip != source_ip and not ip.startswith("127.")]
# Forward to all other connected devices
for target_ip in other_devices:
sock_from_A.sendto(data, (target_ip, 5000))
# Also forward to app.py tracking listener on port 5002
# Prepend source IP so app.py can identify which player sent the data
source_ip = addr[0]
tagged_data = f"SOURCE_IP:{source_ip}|".encode('utf-8') + data
sock_from_A.sendto(tagged_data, ("127.0.0.1", 5002))
timestamp = datetime.now().strftime("%H:%M:%S")
# Logging
#if next(counter) % 20 == 0:
# if addr[0] != DEVICE2_ADDR[0]:
# print(f"[{timestamp}] {label}: {data.decode()}")
# print('sent to ', (target_ip, 5000))
if len(other_devices) > 0:
label = f"{source_ip}{', '.join(other_devices)}"
else:
label = f"{source_ip} (no other devices connected)"
# Uncomment for verbose logging:
# print(f"[{timestamp.strftime('%H:%M:%S')}] {label}")
except Exception as e:
print(f"Fehler {label}: {e}")
print(f"Error in relay: {e}")
print("UDP Relay läuft. Strg+C zum Beenden.")
try: