Add /deps.sh, in /linapple remove full-screen mode to make it run properly on recent...
[applesoft_basic.git] / apple_joystick.py
1 import apple_io
2 import evdev
3 import select
4 import sys
5 import threading
6
7 POLL_TIMEOUT_MS = 1 # program will take this long to exit
8
9 input_path = None
10 input_device = None
11 input_thread = None
12
13 thread = None
14 stop = False
15 poll = select.poll()
16
17 flip_x = False
18 flip_y = False
19 swap_axes = False
20 swap_buttons = False
21
22 def init():
23   global input_device, poll, stop, thread
24   assert input_device is None
25   if input_path is not None:
26     # with joystick present it is centred and has buttons not pressed
27     apple_io.pdl_value[:3] = [0x7f] * 3
28     apple_io.mem[apple_io.HW_PB0] = 0
29     apple_io.mem[apple_io.HW_PB1] = 0
30     apple_io.mem[apple_io.HW_PB2] = 0
31
32     input_device = evdev.InputDevice(input_path)
33
34     poll = select.poll()
35     poll.register(input_device.fd, select.POLLIN)
36
37     stop = False
38     thread = threading.Thread(target = run, daemon = True)
39     thread.start()
40
41 def deinit():
42   global input_device, poll, stop, thread
43   if thread is not None:
44     stop = True
45     thread.join()
46     thread = None
47
48     poll = None
49
50     input_device.close()
51     input_device = None
52
53     # with no joystick present it has the timeout value and buttons pressed
54     apple_io.pdl_value[:3] = [0xff] * 3
55     apple_io.mem[apple_io.HW_PB0] = 0x80
56     apple_io.mem[apple_io.HW_PB1] = 0x80
57     apple_io.mem[apple_io.HW_PB2] = 0x80
58
59 def run():
60   while not stop:
61     if len(poll.poll(POLL_TIMEOUT_MS)):
62       for event in input_device.read():
63         # the below event codes were determined by experiment using my
64         # Mad Catz, Inc. Mad Catz V.1 Stick (USB ID 0738:2237), I don't
65         # know whether other joysticks use consistent axis/button codes
66         if event.type == evdev.ecodes.EV_ABS:
67           #sys.stderr.write(f'abs code {event.code:d} value {event.value:d}\r\n')
68           if event.code == 0:
69             apple_io.pdl_value[0 + swap_axes] = \
70               (event.value & 0xff) ^ (flip_x * 0xff)
71           elif event.code == 1:
72             apple_io.pdl_value[1 - swap_axes] = \
73               (event.value & 0xff) ^ (flip_y * 0xff)
74           elif event.code == 5:
75             apple_io.pdl_value[2] = event.value & 0xff
76         elif event.type == evdev.ecodes.EV_KEY:
77           #sys.stderr.write(f'key code {event.code:d} value {event.value:d}\r\n')
78           if event.code == 288:
79             apple_io.mem[apple_io.HW_PB0 + swap_buttons] = \
80               (event.value != 0) * 0x80
81           if event.code == 289:
82             apple_io.mem[apple_io.HW_PB1 - swap_buttons] = \
83               (event.value != 0) * 0x80
84           if event.code == 290:
85             apple_io.mem[apple_io.HW_PB2] = (event.value != 0) * 0x80