-
Notifications
You must be signed in to change notification settings - Fork 1
/
joystick.rb
49 lines (44 loc) · 1.83 KB
/
joystick.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'fcntl'
class Joystick
attr_accessor :state
def initialize(device = "/dev/input/js0")
@device = device
@fd = IO::sysopen(@device, Fcntl::O_RDONLY)
work
end
def reset
@state = 0
end
def actions
actions = Array.new
actions << Proc.new { |state| @state = :left if state[7] == 0x00 && state[5] == 0x80 }
actions << Proc.new { |state| @state = :right if state[7] == 0x00 && state[5] == 0x7F }
actions << Proc.new { |state| @state = :up if state[7] == 0x01 && state[5] == 0x80 }
actions << Proc.new { |state| @state = :down if state[7] == 0x01 && state[5] == 0x7F }
actions << Proc.new { |state| @state = :red if state[7] == 0x01 && state[6] == 0x01}
actions << Proc.new { |state| @state = :yellow if state[7] == 0x02 && state[6] == 0x01 }
actions << Proc.new { |state| @state = :green if state[7] == 0x03 && state[6] == 0x01 }
actions << Proc.new { |state| @state = :blue if state[7] == 0x00 && state[6] == 0x01 }
actions << Proc.new { |state| @state = :l1 if state[7] == 0x06 && state[6] == 0x01 }
actions << Proc.new { |state| @state = :r1 if state[7] == 0x07 && state[6] == 0x01 }
actions << Proc.new { |state| @state = :select if state[7] == 0x08 && state[6] == 0x01 }
actions << Proc.new { |state| @state = :start if state[7] == 0x09 && state[6] == 0x01 }
actions
end
# TODO using the right struct (LsCC) for unpacking, C* is wrong (but works :)
# struct js_event {
# unsigned int time; /* event timestamp in milliseconds */
# short value; /* value */
# unsigned char type; /* event type */
# unsigned char number; /* axis/button number */
#};
def work
f = IO.open(@fd)
Thread.new {
loop {
data = f.read(8).unpack("C*")
actions.each { |a| a.call(data) }
}
}
end
end