nareto
nareto

Reputation: 185

python reading HID

I'd like to do a program that takes input from HIDs attached to a linux system and generates MIDI from those. I'm ok on the MIDI side, but I'm struggling on the HID side of things. While this approach works ok (taken from here):

#!/usr/bin/python2
import struct

inputDevice = "/dev/input/event0" #keyboard on my system
inputEventFormat = 'iihhi'
inputEventSize = 16

file = open(inputDevice, "rb") # standard binary file input
event = file.read(inputEventSize)
while event:
  (time1, time2, type, code, value) = struct.unpack(inputEventFormat, event)
  print type,code,value
  event = file.read(inputEventSize)
file.close()

it gets high on CPU usage when there are lots of events; especially if tracking the mouse, large movements take almost 50% CPU on my system. I guess because of how the while is structured.

So, is there a better way to do this in python? I'd preferably like to not use non-maintained or old libraries, since I'd like to be able to distribute this code and have it working on modern distros (so eventual dependencies should easily be avaiable in package managers for end users)

Upvotes: 3

Views: 2470

Answers (1)

Oleg Korenevich
Oleg Korenevich

Reputation: 34

there are a lot of events that don't meet your requirements. you must filter events by type or code:

while event:
  (time1, time2, type, code, value) = struct.unpack(inputEventFormat, event)
  if type==X and code==Y:
    print type,code,value
  event = file.read(inputEventSize)

Upvotes: 1

Related Questions