File: hid_joystick.py

package info (click to toggle)
python-mido 1.3.3-0.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 920 kB
  • sloc: python: 4,006; makefile: 127; sh: 4
file content (261 lines) | stat: -rw-r--r-- 6,891 bytes parent folder | download
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# SPDX-FileCopyrightText: 2013 Ole Martin Bjorndalen <ombdalen@gmail.com>
#
# SPDX-License-Identifier: MIT

"""Read from /dev/input/js0 and return as dictionaries.

If you have pygame it is easier and more portable to do something
like::

    import pygame.joystick
    from pygame.event import event_name

    pygame.init()
    pygame.joystick.init()

    js = pygame.joystick.Joystick(0)
    js.init()

    while True:
        for event in pygame.event.get():
            if event.axis == 0:
                print(event)


Init:

                  8 = init?
Time stamp        |
(ms since boot)   |
--+--+--+--       |  -- Button number
f0 fb 37 09 00 00 81 00
f0 fb 37 09 00 00 81 01
f0 fb 37 09 00 00 81 02
f0 fb 37 09 00 00 81 03
f0 fb 37 09 00 00 81 04
f0 fb 37 09 00 00 81 05
f0 fb 37 09 00 00 81 06
f0 fb 37 09 00 00 81 07
f0 fb 37 09 00 00 81 08
f0 fb 37 09 00 00 81 09
f0 fb 37 09 00 00 81 0a
f0 fb 37 09 00 00 81 0b
f0 fb 37 09 00 00 82 00
f0 fb 37 09 00 00 82 01
f0 fb 37 09 00 00 82 02
f0 fb 37 09 00 00 82 03
f0 fb 37 09 00 00 82 04
f0 fb 37 09 00 00 82 05
            --+--  |
              |    1 = button, 2 =
              |
            value (little endian unsigned)

        button down
             |
98 f0 2f 09 01 00 01 00   1 down
08 fa 2f 09 00 00 01 00   1 up

2c 6a 31 09 01 00 01 01   2 down
04 73 31 09 00 00 01 01   2 up

48 bf 32 09 01 00 01 02   3 down
f8 c4 32 09 00 00 01 02   3 up


Logitech PS2-style gamepad:

   axis 0 == left stick   -left / right   (left is negative)
   axis 1 == left stick   -up / down      (up is negative)
   axis 2 == right stick  -left / right
   axis 3 == right stick  -up / down
   axis 4 == plus stick   -left / right   (when mode is off), values min/0/max
   axis 5 == plus stick   -up / down      (when mode is off, values min/0/max

The + stick has two modes. When the mode light is off, it sends axis
4/5. When mode is on, it sends axis 0/1. The values are -32767, 0, and 32767.

Other axis have values from -32767 to 32767 as well.

"""
import struct

JS_EVENT_BUTTON = 0x1
JS_EVENT_AXIS = 0x2
JS_EVENT_INIT = 0x80


def read_event(device):
    data = device.read(8)

    event = {}

    (event['time'],
     event['value'],
     event['type'],
     event['number']) = struct.unpack('IhBB', data)

    event['init'] = bool(event['type'] & JS_EVENT_INIT)
    event['type'] &= 0x7f  # Strip away the flag bits (JS_EVENT_INIT etc.)
    if event['type'] != JS_EVENT_BUTTON:
        event['normalized_value'] = \
            float(event['value']) / 0x7fff  # Normalize to -1..1

    event['type'] = {1: 'button', 2: 'axis'}[event['type']]

    return event


def read_events(device_name):
    with open(device_name, 'rb') as device:
        while True:
            yield read_event(device)


def panic(port):
    """
    Send "All Notes Off" and "Reset All Controllers" on
    all channels.
    """
    for channel in range(16):
        for control in [121, 123]:
            message = mido.Message('control_change',
                                   channel=channel,
                                   control=control, value=0)
            print(message)
            port.send(message)


class Monophonic:
    # Todo: this assumes everything is on channel 0!

    def __init__(self, output, channel=0):
        self.output = output
        self.notes = set()
        self.current_note = None
        self.channel = channel

    def send(self, message):
        if message.type not in ['note_on', 'note_off'] or \
                message.channel != self.channel:
            self.output.send(message)
            return

        if message.type == 'note_on':
            self.notes.add(message.note)
        elif message.type == 'note_off':
            if message.note in self.notes:
                self.notes.remove(message.note)

        print(self.notes)

        try:
            note = min(self.notes)
        except ValueError:
            note = None

        if note == self.current_note:
            return  # Same note as before, no change.

        if self.current_note is not None:
            off = mido.Message('note_off',
                               note=self.current_note,
                               velocity=message.velocity)
            print(off)
            self.output.send(off)
            self.current_note = None

        if note is not None:
            on = mido.Message('note_on',
                              note=note,
                              velocity=message.velocity)
            print(on)
            self.output.send(on)
            self.current_note = note


def play_scale(dev, out):
    # out = Monophonic(out, channel=0)

    # Major scale.
    scale = [0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19]

    # program = 16  # Organ
    program = 74
    out.send(mido.Message('program_change', program=program))

    while True:
        event = read_event(dev)

        if event['init']:
            continue  # Skip init events.

        if event['type'] == 'button':
            # Convert to D-major scale starting at middle D.
            note = 62 + 12 + scale[event['number']]
            if event['value']:
                type_ = 'note_on'
            else:
                type_ = 'note_off'

            message = mido.Message(type_, note=note, velocity=64)
            out.send(message)

        # elif event['type'] == 'axis':
        #     if event['number'] == 0:
        #         pitch_scale = mido.messages.MAX_PITCHWHEEL
        #         pitch = int(event['normalized_value'] * pitch_scale)
        #         out.send(mido.Message('pitchwheel', pitch=pitch))


def play_drums(dev, out):
    # http://www.midi.org/techspecs/gm1sound.php
    note_mapping = {
        2: 35,  # Acoustic Bass Drum
        6: 38,  # Acoustic Snare
        1: 41,  # Low Floor Tom
        4: 47,  # Low Mid Tom
        3: 50,  # High Tom
        8: 51,  # Ride Cymbal

        5: 42,  # Closed Hi Hat
        7: 46,  # Open Hi Hat

        9: 52,  # Chinese Cymbal
        10: 55,  # Splash Cymbal
    }

    while True:
        event = read_event(dev)
        if event['init']:
            continue

        if event['type'] == 'button':
            print(event)

            button = event['number'] + 1  # Number buttons starting with 1.
            if button not in note_mapping:
                continue

            if event['value']:
                type_ = 'note_on'
            else:
                type_ = 'note_off'

            note = note_mapping[button]

            message = mido.Message(type_, channel=9, note=note, velocity=64)
            print(message)
            out.send(message)


if __name__ == '__main__':
    import mido

    with open('/dev/input/js0') as dev:
        with mido.open_output('SD-20 Part A') as out:
            try:
                # play_drums(dev, out)
                play_scale(dev, out)
            finally:
                panic(out)