diff --git a/Config.h b/Config.h index f958528..d4e2f68 100644 --- a/Config.h +++ b/Config.h @@ -4,3 +4,5 @@ #define MQTT_QOS_LEVEL 1 #define MQTT_CLEAN_SESSIONS false + +#define GPIO_DEBOUNCE_TIME 300 \ No newline at end of file diff --git a/Gpio.cpp b/Gpio.cpp index 9d396d2..4d8fcba 100644 --- a/Gpio.cpp +++ b/Gpio.cpp @@ -1,5 +1,6 @@ #include #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) diff --git a/Network.cpp b/Network.cpp index 3457ad6..e1901a3 100644 --- a/Network.cpp +++ b/Network.cpp @@ -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() { diff --git a/Network.h b/Network.h index d46cd18..71e5faa 100644 --- a/Network.h +++ b/Network.h @@ -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 _gpioTs; char* _buffer; const size_t _bufferSize;