Skip to content

Instantly share code, notes, and snippets.

@Jim-Holmstroem
Created February 5, 2017 17:18
Show Gist options
  • Save Jim-Holmstroem/f41b7c9294cbdcf73dca06110aab6055 to your computer and use it in GitHub Desktop.
Save Jim-Holmstroem/f41b7c9294cbdcf73dca06110aab6055 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
from __future__ import print_function, division
"""
Made for: "PlayStation 3 Dual Shock Controller"
Based on:
https://gist.github.com/rdb/8864666
"""
import os, struct, array
from fcntl import ioctl
from operator import methodcaller
def get_devices():
devices = map(
"/dev/input/{}".format,
filter(
methodcaller('startswith', 'js'),
os.listdir("/dev/input")
)
)
return devices
devices = get_devices()
print("devices={}".format(devices))
def device_name(device):
with open(device, 'rb') as jsdev:
buf = array.array('c', ['\0', ] * 64)
ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf)
js_name = buf.tostring()
return js_name
print("name=\"{}\"".format(device_name(devices[0])))
def get_n_axes(device):
with open(device, 'rb') as jsdev:
buf = array.array('B', [0, ])
ioctl(jsdev, 0x80016a11, buf)
n_axes = buf[0]
return n_axes
print("n_axes={}".format(get_n_axes(devices[0])))
def get_n_buttons(device):
with open(device, 'rb') as jsdev:
buf = array.array('B', [0, ])
ioctl(jsdev, 0x80016a12, buf)
n_buttons = buf[0]
return n_buttons
print("n_buttons={}".format(get_n_buttons(devices[0])))
def get_axis_map(device):
n_axes = get_n_axes(device)
with open(device, 'rb') as jsdev:
buf = array.array('B', [0, ] * 0x40)
ioctl(jsdev, 0x80406a32, buf)
axes = buf[:n_axes]
axis_names = {
0x00: 'x',
0x01: 'y',
0x02: 'z',
0x03: 'u',
0x0c: 'L2',
0x0d: 'R2',
0x0e: 'L1',
0x0f: 'R1',
0x10: 'triangle',
0x11: 'circle',
0x12: 'cross',
0x13: 'square',
}
# TODO for axis in axes: axis_names.get(axis, 'unknown(0x%02x)' % axis)
return axis_names
axes = get_axis_map(devices[0])
print("axes={}".format(axes))
def get_button_map(device):
n_buttons = get_n_buttons(device)
with open(device, 'rb') as jsdev:
buf = array.array('H', [0, ] * 200)
ioctl(jsdev, 0x80406a34, buf)
buttons = buf[:n_buttons]
button_names = {
0x00: 'select',
0x01: 'L3',
0x02: 'R3',
0x03: 'start',
0x04: 'up',
0x05: 'right',
0x06: 'down',
0x07: 'left',
0x10: 'PS',
}
# TODO for axis in axes: axis_names.get(axis, 'unknown(0x%02x)' % axis)
return button_names
buttons = get_button_map(devices[0])
print("buttons={}".format(buttons))
def main(device):
print("Start listen to Joystick: {}".format(device))
with open(device, 'rb') as jsdev:
while True:
evbuf = jsdev.read(8)
if evbuf:
time, value, type_, number = struct.unpack('IhBB', evbuf)
print(time, value, type_, number)
if type_ & 0x01:
print(
"{}: {}".format(
number,
value,
)
)
if type_ & 0x02:
print(
"{}: {:.3f}".format(
number,
value / 32767,
)
)
main(devices[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment