python reading HID

血红的双手。 提交于 2020-01-02 08:34:17

问题


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)


回答1:


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)


来源:https://stackoverflow.com/questions/7012282/python-reading-hid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!