2025-04-14 17:12:02 +02:00

58 lines
2.2 KiB
Python

import pygame
class Xbox:
def __init__(self, controllerLogger):
self.logger = controllerLogger
self.mode_count = 2
self.mode = 0
pygame.init()
self.controllers = []
for i in range(0, pygame.joystick.get_count()):
self.controllers.append(pygame.joystick.Joystick(i))
self.controllers[-1].init()
self.logger.info(f"Detected controller {self.controllers[-1].get_name()}")
if len(self.controllers) == 0:
self.logger.critical("No controllers detected. Can't initialize remote control.")
self.initialized = True
else:
self.initialized = False
self.data = {"x1": 0, "x2": 0, "y1": 0, "y2": 0, "up": 0, "down": 0, "left": 0, "right": 0, "r1": 0, "r2": 0,
"r3": 0,
"l1": 0, "l2": 0, "l3": 0}
def get_data(self):
for event in pygame.event.get():
event = dict(event.dict)
keys = event.keys()
try:
if "axis" in keys:
axis = event["axis"]
if axis in [1, 4]:
value = -event["value"]
if abs(value) < 0.2:
value = 0
self.data[{0: "x1", 1: "y1", 4: "y2", 3: "x2", 5: "r2", 2: "l2"}[event["axis"]]] = value
else:
value = event["value"]
if abs(value) < 0.2:
value = 0
self.data[{0: "x1", 1: "y1", 4: "y2", 3: "x2", 5: "r2", 2: "l2"}[event["axis"]]] = value
elif "button" in keys:
pass
elif "joy" in keys: # To manage arrows
data = event["value"][0]
if data != 0:
self.mode += data
self.mode %= self.mode_count
self.logger.info(f"Switched mode ({data}). New mode: {self.mode}")
else:
print(event)
except Exception as e:
print(event)
print(e)
return self.data