Skip to content

Instantly share code, notes, and snippets.

@heiko-r
Last active September 5, 2023 03:35
Show Gist options
  • Save heiko-r/852523b318018b33da26425dac373f22 to your computer and use it in GitHub Desktop.
Save heiko-r/852523b318018b33da26425dac373f22 to your computer and use it in GitHub Desktop.
Read mouse buttons from /dev/input/mice in Python
from enum import Enum, auto
import struct
INPUT_DEVICE = '/dev/input/mice'
class Button(Enum):
LEFT = auto()
RIGHT = auto()
MIDDLE = auto()
codeMap = {
8: [],
9: [Button.LEFT],
10: [Button.RIGHT],
11: [Button.LEFT, Button.RIGHT],
12: [Button.MIDDLE],
13: [Button.LEFT, Button.MIDDLE],
14: [Button.RIGHT, Button.MIDDLE],
15: [Button.LEFT, Button.RIGHT, Button.MIDDLE],
}
previousDownButtons = []
with open(INPUT_DEVICE, 'rb') as mousefile:
while True:
data = mousefile.read(3);
mousecode = struct.unpack('3b', data)
if mousecode[1] != 0 or mousecode[2] != 0:
continue # Ignore mouse movement
clickcode = mousecode[0]
downButtons = codeMap[clickcode]
for button in list(Button):
if button in downButtons and button not in previousDownButtons:
previousDownButtons.append(button)
print('%s clicked' % button.name) # TODO: Call whatever useful function instead
if button not in downButtons and button in previousDownButtons:
previousDownButtons.remove(button)
print('%s released' % button.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment