Get mouse deltas using Python! (in Linux)

Question:

I know that Linux gives out a 9-bit two’s complement data out of the /dev/input/mice. I also know that you can get that data via /dev/hidraw0 where hidraw is your USB device giving out raw data from the HID.

I know the data sent is the delta of the movement (displacement) rather than position. By the by I can also view gibberish data via the "cat /dev/input/mice".

By using the Python language, how can I read this data? I really rather get that data as in simple integers. But it has proven hard. The real problem is reading the damn data. Is there a way to read bits and do bit arithmetic? (Currently I’m not worrying over root user-related issues. Please assume the script is run as root.)

(My main reference was http://www.computer-engineering.org/ps2mouse/)

Asked By: JohnRoach

||

Answers:

Yes, Python can read a file in binary form. Just use a 'b' flag when you open a file, e.g. open('dev/input/mice', 'rb').

Python also supports all the typical bitwise arithmetic operations: shifts, inversions, bitwise and, or, xor, and not, etc.

You’d probably be better served by using a library to process this data, instead of doing it on your own, though.

Answered By: Rafe Kettler

The data from the input system comes out as structures, not simple integers. The mice device is deprecated, I believe. The preferred method is the event device interfaces, where the mouse (and other) input events can also be obtained. I wrote some code that does this, the Event.py module You can use that, or start from there.

Answered By: Keith

I’m on a basic device and not having access to X or … so event.py doesn’t works.

So here’s my simpler decode code part to interpret from “deprecated” ‘/dev/input/mice’:

import struct

file = open( "/dev/input/mice", "rb" );

def getMouseEvent():
  buf = file.read(3);
  button = ord( buf[0] );
  bLeft = button & 0x1;
  bMiddle = ( button & 0x4 ) > 0;
  bRight = ( button & 0x2 ) > 0;
  x,y = struct.unpack( "bb", buf[1:] );
  print ("L:%d, M: %d, R: %d, x: %d, y: %dn" % (bLeft,bMiddle,bRight, x, y) );
  # return stuffs

while( 1 ):
  getMouseEvent();
file.close();
Answered By: Alexandre Mazel

You need to open your editor as a root to bypass the permissions-related error messages you might experience when trying to run this script.

The /dev/input/mice device is only available to root.

Answered By: MT_Shikomba
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.