Update main.py

This commit is contained in:
2026-09-26 11:53:12 +02:00
parent f9a7ec9ce5
commit f8c77371a3
+59 -10
View File
@@ -1,3 +1,5 @@
# https://git.krzak.org/N0VA/ESharePy/raw/branch/main/main.py
import sys
import os
import socket
@@ -25,10 +27,35 @@ KEY_MAP = {
'p': (26, "POWER"),
}
def get_broadcast_addresses():
broadcasts = {'255.255.255.255'}
try:
with open('/proc/net/route') as f:
for line in f.readlines()[1:]:
fields = line.strip().split()
dest = fields[1]
mask = fields[7]
if dest == '00000000':
continue
d = int(dest, 16)
m = int(mask, 16)
b = (d & m) | (~m & 0xFFFFFFFF)
broadcasts.add(socket.inet_ntoa(struct.pack('<I', b)))
except Exception:
pass
return list(broadcasts)
def discover(timeout=2.5):
print("Searching for compatible TVs on the local network (UDP 48689)...")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
try:
sock.bind(('', 48689))
except Exception as e:
print(f"Warning: Could not bind to port 48689 ({e})")
sock.settimeout(timeout)
packet = bytearray(50)
@@ -36,22 +63,34 @@ def discover(timeout=2.5):
struct.pack_into(">IIIII", packet, 0, 0, 0, 0, len(magic), 0)
packet[20:20 + len(magic)] = magic
for bcast in get_broadcast_addresses():
try:
sock.sendto(packet, (bcast, 48689))
except Exception:
pass
t_end = time.time() + timeout
found_devices = []
while time.time() < t_end:
try:
sock.sendto(packet, ("255.255.255.255", 48689))
while True:
data, addr = sock.recvfrom(1024)
reply = data.decode("utf-8", errors="ignore")
if reply.startswith("ECloudBox"):
parts = reply.split(":")
name = parts[1] if len(parts) > 1 else "Unknown"
port = int(parts[2]) if len(parts) > 2 and parts[2].isdigit() else 8121
device = (addr[0], port, name)
if device not in found_devices:
found_devices.append(device)
print(f"Found TV: '{name}' at {addr[0]}:{port}")
return addr[0], port, name
except socket.timeout:
print("No TV responded to UDP broadcast.")
finally:
break
except Exception:
pass
sock.close()
return None
return found_devices
def connect(ip, port=8121):
print(f"Connecting to {ip}:{port}...")
@@ -127,11 +166,21 @@ def main():
if len(sys.argv) > 2:
tv_port = int(sys.argv[2])
else:
found = discover()
if found:
tv_ip, tv_port, _ = found
else:
devices = discover()
if not devices:
print("No TVs discovered.")
tv_ip = input("Enter TV IP address manually: ").strip()
elif len(devices) == 1:
tv_ip, tv_port, name = devices[0]
print(f"Auto-selected TV: '{name}' ({tv_ip}:{tv_port})")
else:
print(f"\nFound {len(devices)} TVs:")
for idx, (ip, port, name) in enumerate(devices, 1):
print(f" [{idx}] {name} ({ip}:{port})")
choice = input(f"Select TV [1-{len(devices)}] (default 1): ").strip()
idx = int(choice) - 1 if choice.isdigit() and 1 <= int(choice) <= len(devices) else 0
tv_ip, tv_port, name = devices[idx]
print(f"Selected TV: '{name}' ({tv_ip}:{tv_port})")
if not tv_ip:
print("No IP provided. Exiting.")