Merge PR #8: Replace GpioMonitor implementation with libnymeas version.

This commit is contained in:
Jenkins nymea 2021-12-11 00:30:36 +01:00
commit 2e58f7f34d
6 changed files with 135 additions and 300 deletions

View File

@ -139,6 +139,7 @@ Gpio::Gpio(int gpio, QObject *parent) :
m_direction(Gpio::DirectionInvalid), m_direction(Gpio::DirectionInvalid),
m_gpioDirectory(QDir(QString("/sys/class/gpio/gpio%1").arg(QString::number(gpio)))) m_gpioDirectory(QDir(QString("/sys/class/gpio/gpio%1").arg(QString::number(gpio))))
{ {
qRegisterMetaType<Gpio::Value>();
} }

View File

@ -164,7 +164,7 @@ void GpioButton::onTimeout()
emit longPressed(); emit longPressed();
} }
void GpioButton::onInterruptOccurred(bool value) void GpioButton::onValueChanged(bool value)
{ {
if (value) { if (value) {
// Pressed // Pressed
@ -197,16 +197,14 @@ bool GpioButton::enable()
disable(); disable();
m_monitor = new GpioMonitor(m_gpioNumber, this); m_monitor = new GpioMonitor(m_gpioNumber, this);
m_monitor->setEdge(Gpio::EdgeBoth);
m_monitor->setActiveLow(m_activeLow);
if (!m_monitor->enable()) { if (!m_monitor->enable(m_activeLow, Gpio::EdgeBoth)) {
qCWarning(dcGpio()) << "Could not enable GPIO monitor for" << this; qCWarning(dcGpio()) << "Could not enable GPIO monitor for" << this;
delete m_monitor; delete m_monitor;
m_monitor = nullptr; m_monitor = nullptr;
return false; return false;
} }
connect(m_monitor, &GpioMonitor::interruptOccurred, this, &GpioButton::onInterruptOccurred); connect(m_monitor, &GpioMonitor::valueChanged, this, &GpioButton::onValueChanged);
// Setup timer, if this timer reaches timeout, a long pressed happend // Setup timer, if this timer reaches timeout, a long pressed happend
m_timer = new QTimer(this); m_timer = new QTimer(this);

View File

@ -77,7 +77,7 @@ signals:
private slots: private slots:
void onTimeout(); void onTimeout();
void onInterruptOccurred(bool value); void onValueChanged(bool value);
public slots: public slots:
bool enable(); bool enable();

View File

@ -1,6 +1,6 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright 2013 - 2020, nymea GmbH * Copyright 2013 - 2021, nymea GmbH
* Contact: contact@nymea.io * Contact: contact@nymea.io
* *
* This file is part of nymea. * This file is part of nymea.
@ -30,270 +30,135 @@
/*! /*!
\class GpioMonitor \class GpioMonitor
\brief Monitor for GPIO interrupts. \brief The GpioMonitor class allows to monitor GPIOs.
\inmodule nymea-gpio \ingroup hardware
\ingroup gpio \inmodule libnymea
An instance of this class creates a thread, which monitors each of the added GPIOs. The object
This class allows to monitor an input GPIO for the interrupts depending on the edge interrupt configuration. emits a signal if one of the added GPIOs changes its value. The GpioMonitor configures a GPIO as an
input, with the edge interrupt EDGE_BOTH (\l{Gpio::setEdgeInterrupt()}{setEdgeInterrupt}).
This class will start a poll thread in the background. Depending on the Gpio::Edge configuration, the \l{interruptOccured()} signal \chapter Example
will be emitted. Default is Gpio::EdgeBoth which means the interrupt will be on rising and falling signal of the Gpio. Following example shows how to use the GpioMonitor class for a button on the Raspberry Pi. There are two possibilitys
to connect a button. Following picture shows the schematics:
The behavior of the interrupt can also be inverted using the \l{activeLow()} parameter. \image Raspberry_Pi_Button_Example.png "Raspberry Pi button example"
Button A represents a clean solutin with a 10 k\unicode{0x2126} resistor (set up as activeLow = false).
Button B represents a "dirty" solution, were the 3.3V will be directly connected to the GPIO if the button is pressed (set activeLow = true).
Here is the code example for a button class:
\code \code
GpioMonitor *monitor = new GpioMonitor(112, this); Button::Button(QObject *parent) :
QObject(parent)
if (!monitor->enable()) { {
qWarning() << "Could not enable GPIO monitor"; m_button = new GpioMonitor(110, this);
monitor->deleteLater(); connect(m_button, &GpioMonitor::valueChanged, this, &Button::stateChanged);
return; }
} bool Button::init()
{
connect(monitor, &GpioMonitor::interruptOccured, this, [this, monitor](bool value){ return m_button->enable();
qDebug() << "GPIO value changed" << value; }
}); void Button::stateChanged(const bool &value)
{
if (m_pressed != value) {
m_pressed = value;
if (value) {
emit buttonPressed();
} else {
emit buttonReleased();
}
}
}
\endcode \endcode
*/ */
/*! /*! \fn void GpioMonitor::valueChanged(const bool &value);
\fn void GpioMonitor::interruptOccured(bool value); * This signal will be emitted, if the monitored \l{Gpio}{Gpios} changed his \a value. */
This signal will be emitted, if an interrupt on the monitored Gpio occured with the new \a value. This event depends on the Gpio::Edge configuration of the Gpio.
\sa edge(), setEdge()
*/
/*!
\fn void GpioMonitor::enabledChanged(bool enabled);
This signal will be emitted when the GpioMonitor \a enabled changed.
*/
#include "gpiomonitor.h" #include "gpiomonitor.h"
#include <poll.h>
#include <QMutexLocker>
/*! Constructs a \l{GpioMonitor} object with the given \a gpio number and \a parent. */ /*! Constructs a \l{GpioMonitor} object with the given \a gpio number and \a parent. */
GpioMonitor::GpioMonitor(int gpio, QObject *parent) : GpioMonitor::GpioMonitor(int gpio, QObject *parent) :
QThread(parent), QObject(parent),
m_gpioNumber(gpio) m_gpioNumber(gpio)
{ {
// Inform about the thread status m_valueFile.setFileName("/sys/class/gpio/gpio" + QString::number(m_gpioNumber) + "/value");
connect(this, &GpioMonitor::started, this, &GpioMonitor::onThreadStarted, Qt::DirectConnection);
connect(this, &GpioMonitor::finished, this, &GpioMonitor::onThreadFinished, Qt::DirectConnection);
} }
/*! Destroys and unexports the Gpio. */ /*! Returns true if this \l{GpioMonitor} could be enabled successfully. With the \a activeLow parameter the values can be inverted.
GpioMonitor::~GpioMonitor() With the \a edgeInterrupt parameter the interrupt type can be specified. */
bool GpioMonitor::enable(bool activeLow, Gpio::Edge edgeInterrupt)
{ {
disable(); if (!Gpio::isAvailable())
wait(200); return false;
}
int GpioMonitor::gpioNumber() const m_gpio = new Gpio(m_gpioNumber, this);
{ if (!m_gpio->exportGpio() ||
return m_gpioNumber; !m_gpio->setDirection(Gpio::DirectionInput) ||
} !m_gpio->setActiveLow(activeLow) ||
!m_gpio->setEdgeInterrupt(edgeInterrupt)) {
/*! Returns the edge interrupt configuration for this GpioMonitor. */ qCWarning(dcGpio()) << "GpioMonitor: Error while initializing GPIO" << m_gpio->gpioNumber();
Gpio::Edge GpioMonitor::edge() const
{
return m_edge;
}
/*! Sets the edge interrupt configuration for this GpioMonitor to the given \a edge. */
void GpioMonitor::setEdge(Gpio::Edge edge)
{
if (m_edge == edge)
return;
m_edge = edge;
}
/*! Returns true, if the monitor is configured as active low. If active low is true, the GPIO values and interrupt behavior will be inverted. */
bool GpioMonitor::activeLow() const
{
return m_activeLow;
}
/*! Sets the the monitor to \a activeLow. If active low is true, the GPIO values and interrupt behavior will be inverted. */
void GpioMonitor::setActiveLow(bool activeLow)
{
if (m_activeLow == activeLow)
return;
m_activeLow = activeLow;
}
/*! Returns the current value of the Gpio. */
Gpio::Value GpioMonitor::value()
{
QMutexLocker valueLocker(&m_valueMutex);
return m_value;
}
/*! Returns true if this GpioMonitor is enabled. */
bool GpioMonitor::enabled() const
{
return m_enabled;
}
void GpioMonitor::setValue(Gpio::Value value)
{
QMutexLocker valueLocker(&m_valueMutex);
m_value = value;
switch (m_value) {
case Gpio::ValueLow:
emit interruptOccurred(false);
break;
case Gpio::ValueHigh:
emit interruptOccurred(true);
break;
default:
break;
}
}
void GpioMonitor::setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
m_enabled = enabled;
emit enabledChanged(m_enabled);
}
/*! Reimplementation of the QThread run() method. Within the thread the Gpio value will be polled using poll() 2. */
void GpioMonitor::run()
{
// Create GPIO in the thread for initialisation
Gpio inputGpio(m_gpioNumber);
if (!inputGpio.exportGpio()) {
qCWarning(dcGpio()) << "Could not enable GPIO monitor.";
return;
}
if (!inputGpio.setDirection(Gpio::DirectionInput)) {
qCWarning(dcGpio()) << "Could not enable GPIO monitor.";
return;
}
if (!inputGpio.setEdgeInterrupt(m_edge)) {
qCWarning(dcGpio()) << "Could not set interrupt for the GPIO monitor.";
return;
}
if (!inputGpio.setActiveLow(m_activeLow)) {
qCWarning(dcGpio()) << "Could not set active low for the GPIO monitor.";
return;
}
// In order to do correctly, use poll (2) according to the kernel documentation
// https://www.kernel.org/doc/Documentation/gpio/sysfs.txt
QFile valueFile(inputGpio.gpioDirectory() + QDir::separator() + "value");
if (!valueFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCWarning(dcGpio()) << "Could not open GPIO" << &inputGpio << "value file:" << valueFile.errorString();
return;
}
struct pollfd fdset[1];
int rc = -1;
uint nfds = 1;
int timeout = 100; // ms
fdset[0].fd = valueFile.handle();
fdset[0].events = POLLPRI;
// Poll the GPIO value until stop is true
while (true) {
// Poll the value file
rc = poll(fdset, nfds, timeout);
// Poll failed...
if (rc < 0) {
qCWarning(dcGpio()) << "Failed to poll" << &inputGpio;
break;
}
// Check if we should stop the thread
m_stopMutex.lock();
if (m_stop) {
m_stopMutex.unlock();
break;
}
m_stopMutex.unlock();
// No interrupt occured
if (rc == 0)
continue;
// Interrupt occured
if (fdset[0].revents & POLLPRI) {
QString valueString;
QTextStream readStream(&valueFile);
if (!readStream.seek(0)) {
qCWarning(dcGpio()) << "Failed to seek value file of" << &inputGpio;
continue;
}
// Notify the main thread about the interrupt
readStream >> valueString;
if (valueString == "0") {
setValue(Gpio::ValueLow);
} else {
setValue(Gpio::ValueHigh);
}
}
}
// Clean up once done
valueFile.close();
}
void GpioMonitor::onThreadStarted()
{
qCDebug(dcGpio()) << "Monitor thread started";
setEnabled(true);
}
void GpioMonitor::onThreadFinished()
{
qCDebug(dcGpio()) << "Monitor thread finished";
setEnabled(false);
}
/*! Returns true, if this GpioMonitor was enabled successfully. */
bool GpioMonitor::enable()
{
qCDebug(dcGpio()) << "Enabling gpio monitor";
if (isRunning()) {
qCWarning(dcGpio()) << "This GPIO monitor is already running.";
return true;
}
// Init the GPIO
if (!Gpio::isAvailable()) {
qCWarning(dcGpio()) << "Could not enable GPIO monitor. There are no GPIOs available on this platform.";
return false; return false;
} }
QMutexLocker locker(&m_stopMutex); if (!m_valueFile.open(QFile::ReadOnly)) {
m_stop = false; qWarning(dcGpio()) << "GpioMonitor: Could not open value file for gpio monitor" << m_gpio->gpioNumber();
return false;
}
// Everything looks good, lets start the poll thread and inform about the result m_notifier = new QSocketNotifier(m_valueFile.handle(), QSocketNotifier::Exception);
start(); connect(m_notifier, &QSocketNotifier::activated, this, &GpioMonitor::readyReady);
qCDebug(dcGpio()) << "Socket notififier started";
m_notifier->setEnabled(true);
return true; return true;
} }
/*! Disables this GpioMonitor. The \l{interruptOccured()} signal will not be emitted any more and the Gpio will be unexported. */ /*! Disables this \l{GpioMonitor}. */
void GpioMonitor::disable() void GpioMonitor::disable()
{ {
qCDebug(dcGpio()) << "Disabling gpio monitor"; delete m_notifier;
// Stop the thread if not already disabled delete m_gpio;
QMutexLocker locker(&m_stopMutex);
if (m_stop) return; m_notifier = 0;
m_stop = true; m_gpio = 0;
m_valueFile.close();
}
/*! Returns true if this \l{GpioMonitor} is running. */
bool GpioMonitor::isRunning() const
{
if (!m_notifier)
return false;
return m_notifier->isEnabled();
}
/*! Returns the current value of this \l{GpioMonitor}. */
bool GpioMonitor::value() const
{
return m_currentValue;
}
/*! Returns the \l{Gpio} of this \l{GpioMonitor}. */
Gpio *GpioMonitor::gpio()
{
return m_gpio;
}
void GpioMonitor::readyReady(const int &ready)
{
Q_UNUSED(ready)
m_valueFile.seek(0);
QByteArray data = m_valueFile.readAll();
bool value = false;
if (data[0] == '1') {
value = true;
} else if (data[0] == '0') {
value = false;
} else {
return;
}
m_currentValue = value;
emit valueChanged(value);
} }

View File

@ -1,6 +1,5 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **
* * Copyright 2013 - 2021, nymea GmbH
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io * Contact: contact@nymea.io
* *
* This file is part of nymea. * This file is part of nymea.
@ -31,61 +30,40 @@
#ifndef GPIOMONITOR_H #ifndef GPIOMONITOR_H
#define GPIOMONITOR_H #define GPIOMONITOR_H
#include <QMutex>
#include <QThread>
#include <QObject> #include <QObject>
#include <QDebug>
#include <QSocketNotifier>
#include <QFile>
#include "gpio.h" #include "gpio.h"
class GpioMonitor : public QThread class GpioMonitor : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit GpioMonitor(int gpio, QObject *parent = nullptr); explicit GpioMonitor(int gpio, QObject *parent = nullptr);
~GpioMonitor() override;
int gpioNumber() const; bool enable(bool activeLow = false, Gpio::Edge edgeInterrupt = Gpio::EdgeBoth);
void disable();
Gpio::Edge edge() const; bool isRunning() const;
void setEdge(Gpio::Edge edge); bool value() const;
bool activeLow() const; Gpio* gpio();
void setActiveLow(bool activeLow);
Gpio::Value value();
bool enabled() const;
private: private:
int m_gpioNumber = -1; int m_gpioNumber;
Gpio::Edge m_edge = Gpio::EdgeBoth; Gpio *m_gpio;
bool m_activeLow = true; QSocketNotifier *m_notifier;
bool m_enabled = false; QFile m_valueFile;
bool m_currentValue;
// Thread stuff
QMutex m_valueMutex;
Gpio::Value m_value = Gpio::ValueInvalid;
QMutex m_stopMutex;
bool m_stop = false;
void setValue(Gpio::Value value);
void setEnabled(bool enabled);
protected:
void run() override;
signals: signals:
void interruptOccurred(bool value); void valueChanged(const bool &value);
void enabledChanged(bool enabled);
private slots: private slots:
void onThreadStarted(); void readyReady(const int &ready);
void onThreadFinished();
public slots:
bool enable();
void disable();
}; };

View File

@ -151,21 +151,14 @@ int main(int argc, char *argv[])
return EXIT_SUCCESS; return EXIT_SUCCESS;
} else { } else {
GpioMonitor *monitor = new GpioMonitor(gpioNumber); GpioMonitor *monitor = new GpioMonitor(gpioNumber);
monitor->setEdge(edge);
monitor->setActiveLow(activeLow);
// Inform about enabled changed
QObject::connect(monitor, &GpioMonitor::enabledChanged, [gpioNumber](bool enabled) {
qDebug() << "GPIO" << gpioNumber << "monitor" << (enabled ? "enabled" : "disabled");
});
// Inform about interrupt // Inform about interrupt
QObject::connect(monitor, &GpioMonitor::interruptOccurred, [gpioNumber](bool value) { QObject::connect(monitor, &GpioMonitor::valueChanged, [gpioNumber](bool value) {
qDebug() << "GPIO" << gpioNumber << "interrupt occurred. Current value:" << (value ? "1" : "0"); qDebug() << "GPIO" << gpioNumber << "value changed:" << (value ? "1" : "0");
}); });
// Enable the monitor // Enable the monitor
if (!monitor->enable()) { if (!monitor->enable(activeLow, edge)) {
qCritical() << "Could not enable GPIO" << gpioNumber << "monitor."; qCritical() << "Could not enable GPIO" << gpioNumber << "monitor.";
return EXIT_FAILURE; return EXIT_FAILURE;
} }