Advertisement
rhandycan1

python_usb_dongle_controller

Jul 19th, 2025 (edited)
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | Source Code | 0 0
  1. from inputs import get_gamepad
  2. import socket
  3. import time
  4.  
  5. # 🧠 Replace with your ESP32's actual IP address
  6. ESP32_IP = '192.x.x.x' #replace with your ESP32 ip address printed in esp32 program
  7. PORT = 1234
  8.  
  9. def connect_socket():
  10.     while True:
  11.         try:
  12.             sock = socket.socket()
  13.             sock.connect((ESP32_IP, PORT))
  14.             print("✅ Connected to ESP32 over Wi-Fi")
  15.             return sock
  16.         except Exception as e:
  17.             print(f"🔌 Failed to connect: {e}")
  18.             print("🔄 Retrying in 3 seconds...")
  19.             time.sleep(3)
  20.  
  21. sock = connect_socket()
  22.  
  23. try:
  24.     while True:
  25.         events = get_gamepad()
  26.         for event in events:
  27.             # 🔍 Show all incoming gamepad signals (great for mapping new buttons)
  28.             print(f"Code: {event.code} | Type: {event.ev_type} | State: {event.state}")
  29.  
  30.             # 🎯 Only respond to key/button press events
  31.             if event.ev_type == 'Key' and event.state == 1:
  32.                 msg = f"BTN:{event.code}\n"
  33.                 try:
  34.                     sock.sendall(msg.encode())
  35.                     print(f"📤 Sent → {msg.strip()}")
  36.                     time.sleep(0.05)  # 💤 Prevent flooding the ESP32
  37.                 except Exception as e:
  38.                     print(f"⚠️ Connection lost: {e}")
  39.                     print("🔁 Reconnecting...")
  40.                     sock.close()
  41.                     sock = connect_socket()
  42.                     break  # Restart the loop after reconnect
  43. except KeyboardInterrupt:
  44.     print("👋 Bridge manually stopped.")
  45.     sock.close()
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement