import hid
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import time
import struct
# Joy-Con constants
VENDOR_ID = 0x057E # Nintendo
LEFT_PRODUCT_ID = 0x2006 # Left Joy-Con
REPORT_LENGTH = 64 # Typical report size
# 3D Rectangle position (initial)
rect_pos = [0.0, 0.0, -5.0] # X, Y, Z (Z is depth)
def init_joycon(device):
"""Initialize the Joy-Con by sending setup commands."""
# Disable vibration (subcommand 0x48)
buf = [0x01] + [0x00] * 9 # Output report 0x01 with subcommand
buf[1] = 0x48 # Subcommand: Set vibration enabled (0 to disable)
buf[2] = 0x00
device.write(bytes(buf))
time.sleep(0.1)
# Set input report mode to 0x30 (standard full mode with IMU)
buf = [0x01] + [0x00] * 9
buf[1] = 0x03 # Subcommand: Set input report mode
buf[2] = 0x30 # Mode 0x30
device.write(bytes(buf))
time.sleep(0.1)
# Enable IMU (subcommand 0x40)
buf = [0x01] + [0x00] * 9
buf[1] = 0x40 # Subcommand: Enable IMU
buf[2] = 0x01 # Enable
device.write(bytes(buf))
time.sleep(0.1)
def parse_left_stick(report):
"""Parse left analog stick from input report (assuming report ID 0x30)."""
if len(report) < 12 or report[0] != 0x30:
return 0, 0 # Invalid report
# Left stick: bytes 6-7 (X low/high), 8-9 (Y low/high) - 12-bit values
stick_x = report[7] << 8 | report[6]
stick_y = report[9] << 8 | report[8]
# Normalize to -1.0 to 1.0 (center is ~2048)
stick_x = (stick_x - 2048) / 2048.0
stick_y = (stick_y - 2048) / 2048.0
return stick_x, stick_y
def parse_buttons(report):
"""Parse button presses from input report."""
if len(report) < 5 or report[0] != 0x30:
return 0
# Button status is in bytes 3-4
buttons = (report[3] << 8) | report[4]
return buttons
def draw_rectangle():
"""Draw a simple 3D rectangle (cube) with position indicators."""
# Draw a cube instead of a flat rectangle for better 3D visualization
vertices = [
# Front face
(-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1),
# Back face
(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1)
]
edges = [
(0, 1), (1, 2), (2, 3), (3, 0), # Front face
(4, 5), (5, 6), (6, 7), (7, 4), # Back face
(0, 4), (1, 5), (2, 6), (3, 7) # Connecting edges
]
# Draw edges
glBegin(GL_LINES)
glColor3f(1.0, 0.0, 0.0) # Red
for edge in edges:
for vertex in edge:
glVertex3fv(vertices[vertex])
glEnd()
# Draw faces
glBegin(GL_QUADS)
# Front face (red)
glColor3f(1.0, 0.0, 0.0)
glVertex3fv(vertices[0])
glVertex3fv(vertices[1])
glVertex3fv(vertices[2])
glVertex3fv(vertices[3])
# Back face (green)
glColor3f(0.0, 1.0, 0.0)
glVertex3fv(vertices[4])
glVertex3fv(vertices[5])
glVertex3fv(vertices[6])
glVertex3fv(vertices[7])
# Top face (blue)
glColor3f(0.0, 0.0, 1.0)
glVertex3fv(vertices[3])
glVertex3fv(vertices[2])
glVertex3fv(vertices[6])
glVertex3fv(vertices[7])
# Bottom face (yellow)
glColor3f(1.0, 1.0, 0.0)
glVertex3fv(vertices[0])
glVertex3fv(vertices[1])
glVertex3fv(vertices[5])
glVertex3fv(vertices[4])
glEnd()
def draw_coordinate_system():
"""Draw X, Y, Z axes to help visualize position."""
glBegin(GL_LINES)
# X axis (red)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(0, 0, 0)
glVertex3f(2, 0, 0)
# Y axis (green)
glColor3f(0.0, 1.0, 0.0)
glVertex3f(0, 0, 0)
glVertex3f(0, 2, 0)
# Z axis (blue)
glColor3f(0.0, 0.0, 1.0)
glVertex3f(0, 0, 0)
glVertex3f(0, 0, 2)
glEnd()
def main():
# Find and open Left Joy-Con
device = hid.device()
found = False
for dev in hid.enumerate(VENDOR_ID, LEFT_PRODUCT_ID):
print(f"Found Left Joy-Con: {dev['product_string']}")
device.open_path(dev['path'])
found = True
break
if not found:
print("Left Joy-Con not found. Ensure it's paired via Bluetooth.")
return
init_joycon(device)
print("Left Joy-Con initialized.")
# Initialize Pygame and OpenGL
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)
# Enable depth testing
glEnable(GL_DEPTH_TEST)
# Initial camera position
glTranslatef(0.0, 0.0, -10)
# Button press states
button_down_pressed = False
button_up_pressed = False
# Position movement speed
movement_speed = 0.1
clock = pygame.time.Clock()
print("Controls:")
print("- Left stick: Move X/Y position")
print("- Up button: Move closer (Z+)")
print("- Down button: Move away (Z-)")
print("- Left button: Reset position")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
device.close()
return
# Read HID report (non-blocking)
try:
report = device.read(REPORT_LENGTH, timeout_ms=10)
if report:
# Parse analog stick
stick_x, stick_y = parse_left_stick(report)
# Update X/Y position based on left stick
rect_pos[0] += stick_x * movement_speed
rect_pos[1] += stick_y * movement_speed
# Keep position within reasonable bounds
rect_pos[0] = max(-5, min(5, rect_pos[0]))
rect_pos[1] = max(-5, min(5, rect_pos[1]))
rect_pos[2] = max(-15, min(-1, rect_pos[2]))
# Parse buttons for Z movement and reset
buttons = parse_buttons(report)
# Button mapping (for left Joy-Con)
# Down button (0x0100)
if buttons & 0x0100 and not button_down_pressed:
rect_pos[2] -= movement_speed * 5 # Move away (Z-)
button_down_pressed = True
elif not (buttons & 0x0100):
button_down_pressed = False
# Up button (0x0200)
if buttons & 0x0200 and not button_up_pressed:
rect_pos[2] += movement_speed * 5 # Move closer (Z+)
button_up_pressed = True
elif not (buttons & 0x0200):
button_up_pressed = False
# Left button (0x0800) - Reset position
if buttons & 0x0800:
rect_pos = [0.0, 0.0, -5.0]
except:
# Handle potential HID read errors
pass
# Render 3D scene
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Draw fixed coordinate system at origin
glLoadIdentity()
glTranslatef(0.0, 0.0, -10)
draw_coordinate_system()
# Draw our movable cube
glLoadIdentity()
glTranslatef(0.0, 0.0, -10) # Base position
glTranslatef(rect_pos[0], rect_pos[1], rect_pos[2]) # Apply object position
draw_rectangle()
# Display position information
pygame.display.set_caption(f"Cube Position: X={rect_pos[0]:.2f}, Y={rect_pos[1]:.2f}, Z={rect_pos[2]:.2f}")
pygame.display.flip()
clock.tick(60) # 60 FPS
if __name__ == "__main__":
main()