定义一个遥控器类,继承于QWSKeyboardHandler。
QSocketNotifier用来监听系统文件操作,通过signal/slot跟自定义的ReadRemoteData连接起来。
一旦lirc有数据提交,Qt就会通过ReadRemoteData读取到lirc的按键。
类定义:
1 class RemoteHandler : public QObject, public QWSKeyboardHandler 2 { 3 Q_OBJECT 4 public: 5 bool loadFinish; 6 RemoteHandler(const QString &device=QString("/dev/lircd")); 7 ~RemoteHandler(); 8 private slots: 9 void ReadRemoteData(); 10 private: 11 int RemoteFd; 12 QSocketNotifier *RemoteNotifier; 13 };
实现的RemoteHandler构造函数:
1 RemoteHandler::RemoteHandler(const QString &device) 2 { 3 struct sockaddr_un addr; 4 addr.sun_family = AF_UNIX; 5 strcpy(addr.sun_path, device.toLatin1().data()); 6 7 if ((RemoteFd = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) 8 { 9 if (::connect(RemoteFd, (struct sockaddr *)&addr, sizeof(addr)) != -1) 10 { 11 int opts; 12 if ((opts = fcntl(RemoteFd, F_GETFL)) != -1) 13 { 14 opts = (opts | O_NONBLOCK); 15 if (fcntl(RemoteFd, F_SETFL, opts) != -1) 16 { 17 qDebug("LIRC %s: sucessfully started", __FUNCTION__); 18 char buf[2]; 19 while (read(RemoteFd, buf, 1) > 0); 20 RemoteNotifier = new QSocketNotifier(RemoteFd, QSocketNotifier::Read, this); 21 connect(RemoteNotifier, SIGNAL(activated(int)), this, SLOT(ReadRemoteData())); 22 } 23 else 24 qDebug("LIRC %s: fcntl O_NONBLOCK failed", __FUNCTION__); 25 } 26 else 27 qDebug("LIRC %s: fcntl failed", __FUNCTION__); 28 } 29 else 30 qDebug("LIRC %s: connect failed", __FUNCTION__); 31 } 32 else 33 qDebug("LIRC %s: socket failed", __FUNCTION__); 34 }
获取lirc的数据:
1 void RemoteHandler::ReadRemoteData() 2 { 3 qDebug("RemoteHandler::ReadRemoteData"); 4 if (loadFinish) 5 { 6 char readBuf[128] = {0}; 7 if (read(RemoteFd, readBuf, sizeof(readBuf)) != -1) 8 qDebug("buf = %s", readBuf); 9 else 10 qDebug("LIRC %s: read failed", __FUNCTION__); 11 12 readBuf[strlen(readBuf)-1] = '\0'; 13 14 char scanCode[128] = {0}; 15 char repeatStr[4] = {0}; 16 char buttonName[128] = {0}; 17 char deviceName[128] = {0}; 18 sscanf(readBuf, "%s %s %s %s", &scanCode[0], &repeatStr[0], &buttonName[0], &deviceName[0]); 19 char *end = NULL; 20 long repeat = strtol(repeatStr, &end, 16); 21 if (!end || *end != 0) 22 return; 23 if (repeat == 0) 24 { 25 if (strncmp(deviceName, DEVICENAME, strlen(deviceName)+1) == 0) 26 { 27 int keyCode = 0; 28 if (strncmp(buttonName, CURSOR_UP, strlen(deviceName)+1) == 0) 29 keyCode = Qt::Key_Up; 30 else if (strncmp(buttonName, CURSOR_DOWN, strlen(deviceName)+1) == 0) 31 keyCode = Qt::Key_Down; 32 else if (strncmp(buttonName, OK, strlen(deviceName)+1) == 0) 33 keyCode = Qt::Key_Enter; 34 processKeyEvent(0, keyCode, 0, 1, 0); 35 } 36 } 37 } 38 else 39 { 40 char buf[2]; 41 while (read(RemoteFd, buf, 1) > 0); 42 } 43 44 }