implement gpio input via mqtt

This commit is contained in:
technyon
2023-06-04 13:11:54 +02:00
parent b7053db767
commit 56bd07629f
4 changed files with 34 additions and 1 deletions

View File

@@ -4,3 +4,5 @@
#define MQTT_QOS_LEVEL 1
#define MQTT_CLEAN_SESSIONS false
#define GPIO_DEBOUNCE_TIME 300

View File

@@ -1,5 +1,6 @@
#include <esp32-hal.h>
#include "Gpio.h"
#include "Config.h"
#include "Arduino.h"
#include "Logger.h"
#include "PreferencesKeys.h"
@@ -8,7 +9,7 @@
Gpio* Gpio::_inst = nullptr;
unsigned long Gpio::_debounceTs = 0;
const uint Gpio::_debounceTime = 1000;
const uint Gpio::_debounceTime = GPIO_DEBOUNCE_TIME;
Gpio::Gpio(Preferences* preferences)
: _preferences(preferences)

View File

@@ -246,6 +246,10 @@ void Network::initialize()
break;
}
}
_gpio->addCallback([this](const GpioAction& action, const int& pin)
{
gpioActionCallback(action, pin);
});
}
bool Network::update()
@@ -345,6 +349,26 @@ bool Network::update()
_lastMaintenanceTs = ts;
}
for(const auto& gpioTs : _gpioTs)
{
uint8_t pin = gpioTs.first;
unsigned long ts = gpioTs.second;
if(ts != 0 && ((millis() - ts) >= GPIO_DEBOUNCE_TIME))
{
_gpioTs[pin] = 0;
uint8_t pinState = digitalRead(pin) == HIGH ? 1 : 0;
char gpioPath[250];
buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pin)).c_str(), mqtt_topic_gpio_state});
publishInt(_lockPath.c_str(), gpioPath, pinState);
Log->print(F("GPIO "));
Log->print(pin);
Log->print(F(" (Input) --> "));
Log->println(pinState);
}
}
return true;
}
@@ -581,6 +605,10 @@ void Network::parseGpioTopics(const espMqttClientTypes::MessageProperties &prope
}
}
void Network::gpioActionCallback(const GpioAction &action, const int &pin)
{
_gpioTs[pin] = millis();
}
void Network::reconfigureDevice()
{

View File

@@ -77,6 +77,7 @@ private:
static void onMqttDataReceivedCallback(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total);
void onMqttDataReceived(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total);
void parseGpioTopics(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total);
void gpioActionCallback(const GpioAction& action, const int& pin);
void setupDevice();
bool reconnect();
@@ -139,6 +140,7 @@ private:
bool _mqttEnabled = true;
static unsigned long _ignoreSubscriptionsTs;
long _rssiPublishInterval = 0;
std::map<uint8_t, unsigned long> _gpioTs;
char* _buffer;
const size_t _bufferSize;