Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read HID devices (/dev/hidrawX) with Qt on Linux?

Tags:

c++

linux

qt

hid

I'm working on a 'RepRap calibration tool' which would use a mouse attached to the printing platform to measure the movement of the platform.

Right now I'm stuck trying to read raw mouse data from /dev/hidrawX, but I'm unable to read any data.

So far I've tried:

First attempt:

QFile f("/dev/hidraw0");
f.readAll();

Reads nothing.

Second attempt:

m_file = new QFile("/dev/hidraw0");
m_sn= new QSocketNotifier(m_file->handle(), QSocketNotifier::Read);
m_sn->setEnabled(true);
connect(m_sn, SIGNAL(activated(int)), this, SLOT(readyRead()));

then on the readyRead SLOT:

qDebug()<<"Ready Read!!"<<m_file.bytesAvailable();
QTextStream d(&m_file);
qDebug()<< d.read(64);

This code fires the readyRead slot once but it gets stuck on the read(64) call, if I comment the read(64) the slot will be fired each time the mouse its moved. m_file.bytesAvailable() always reports 0.

Which is the right way to read these devices with Qt?

Solution:

I reworked the code like:

bool rcMouseHandler::openHidraw(QString device)
{
    int fd =open(device.toLocal8Bit(),O_NONBLOCK);
    if(fd <=0)
    {
        qDebug()<<"[WARN]rcMouseHandler::open-> Cant open!";
        return false;
    }
    m_sn= new QSocketNotifier(fd, QSocketNotifier::Read);
    m_sn->setEnabled(true);
    connect(m_sn, SIGNAL(activated(int)), this, SLOT(readyRead()));
    return true;
}

void rcMouseHandler::readyRead()
{
    qDebug()<<"Ready Read!!";
    char buffer[4] = {0,0,0,0};
    read(m_sn->socket(),&buffer,4);
    qDebug()<<(quint8)buffer[0]<<(quint8)buffer[1]<<(quint8)buffer[2]<<(quint8)buffer[3];
}
like image 475
darkjavi Avatar asked Jul 14 '13 19:07

darkjavi


1 Answers

The right way I suppose here to not use Qt. Why you need portable wrapper above POSIX open and read, when this part of your code is not portable (part that work with /dev/*). Open device with "open" "man 2 open" in O_NONBLOCK and call "read" (man 2 read) to get data from it. And you can still use QSocketNotifier with handle that return "open".

like image 51
fghj Avatar answered Oct 19 '22 19:10

fghj