key.h
#ifndef KEY_H
#define KEY_H
#include <QObject>
#include <QFile>
#include <QDebug>
#include <linux/input.h>
class Key : public QObject
{
Q_OBJECT
public:
explicit Key(QObject *parent = nullptr);
~Key();
static void Qsys_led_on();
static void Qsys_led_off();
static void Quser_led_on();
static void Quser_led_off();
public slots:
void read_key();
private:
QFile* file;
};
#endif // KEY_H
key.cpp
#include "key.h"
Key::Key(QObject *parent) : QObject(parent)
{
file = new QFile(this);
file->setFileName("/dev/input/event1");
file->open(QIODevice::ReadWrite);
connect(file, &QFile::readyRead, this, &Key::read_key);
}
Key::~Key()
{
file->close();
}
void Key::read_key()
{
int size = sizeof(struct input_event);
char* buff = new char[size];
if(size == file->read(buff, size)){
struct input_event* key_ev;
key_ev = (struct input_event*)buff;
if(key_ev->type == EV_KEY){
switch(key_ev->code){
case 1:
if(key_ev->value == 1){
Qsys_led_on();
}
break;
case 139:
if(key_ev->value == 1){
Qsys_led_off();
}
break;
case 105:
if(key_ev->value == 1){
Quser_led_on();
}
break;
case 106:
if(key_ev->value == 1){
Quser_led_off();
}
break;
}
}
}
delete[] buff;
}
//客厅灯打开
void Key::Qsys_led_on()
{
QFile sfile;
sfile.setFileName("/sys/class/leds/sys-led/brightness");
if(!sfile.open(QIODevice::ReadWrite)){
qDebug()<<sfile.errorString();
}
sfile.write("1");
sfile.close();
}
//客厅灯关闭
void Key::Qsys_led_off()
{
QFile sfile;
sfile.setFileName("/sys/class/leds/sys-led/brightness");
if(!sfile.open(QIODevice::ReadWrite)){
qDebug()<<sfile.errorString();
}
sfile.write("0");
sfile.close();
}
//卧室灯打开
void Key::Quser_led_on()
{
QFile ufile;
ufile.setFileName("/sys/class/leds/user-led/brightness");
if(!ufile.open(QIODevice::ReadWrite)){
qDebug()<<ufile.errorString();
}
ufile.write("1");
ufile.close();
}
//卧室灯关闭
void Key::Quser_led_off()
{
QFile ufile;
ufile.setFileName("/sys/class/leds/user-led/brightness");
if(!ufile.open(QIODevice::ReadWrite)){
qDebug()<<ufile.errorString();
}
ufile.write("0");
ufile.close();
}