Files
deckenlampe/main/feature_switch.cpp
T

78 lines
1.6 KiB
C++
Raw Normal View History

2021-07-15 13:17:07 +02:00
#include "feature_switch.h"
// Arduino includes
#include <Arduino.h>
// local includes
#include "myconfig.h"
#include "mymqtt.h"
#include "feature_lamp.h"
2021-07-15 14:12:01 +02:00
#include "espchrono.h"
using namespace std::chrono_literals;
2021-07-15 13:17:07 +02:00
namespace deckenlampe {
std::atomic<bool> switchState;
namespace {
uint8_t switchDebounce{};
2021-07-15 14:12:01 +02:00
espchrono::millis_clock::time_point last_switch_readout;
2021-07-15 13:17:07 +02:00
bool readSwitch();
} // namespace
void init_switch()
{
2021-07-15 16:38:04 +02:00
if (!config::enable_switch.value())
2021-07-15 13:17:07 +02:00
return;
2021-07-15 16:38:04 +02:00
pinMode(config::pins_switch.value(), INPUT);
2021-07-15 13:17:07 +02:00
}
void update_switch()
{
2021-07-15 16:38:04 +02:00
if (!config::enable_switch.value())
2021-07-15 13:17:07 +02:00
return;
2021-07-15 14:12:01 +02:00
if (espchrono::ago(last_switch_readout) < 20ms)
return;
last_switch_readout = espchrono::millis_clock::now();
2021-07-15 13:17:07 +02:00
const auto newState = readSwitch();
if (newState == switchState.load())
switchDebounce = 0;
2021-08-06 15:50:44 +02:00
else
{
2021-07-15 13:17:07 +02:00
switchDebounce++;
2021-08-06 15:50:44 +02:00
if (switchDebounce >= 10)
{
2021-07-15 13:17:07 +02:00
switchDebounce = 0;
switchState = newState;
2021-07-15 14:12:01 +02:00
if (mqttConnected)
2021-07-15 16:38:04 +02:00
mqttVerbosePub(config::topic_switch_status.value(), switchState ? "ON" : "OFF", 0, 1);
2021-07-15 13:17:07 +02:00
2021-08-06 15:50:44 +02:00
if (config::enable_lamp.value())
{
2021-07-15 13:17:07 +02:00
lampState = !lampState;
writeLamp(lampState);
2021-07-15 14:12:01 +02:00
if (mqttConnected)
2021-07-15 16:38:04 +02:00
mqttVerbosePub(config::topic_lamp_status.value(), lampState ? "ON" : "OFF", 0, 1);
2021-07-15 13:17:07 +02:00
}
}
}
}
namespace {
bool readSwitch()
{
2021-07-15 16:38:04 +02:00
bool state = digitalRead(config::pins_switch.value()) == HIGH;
if (config::invert_switch.value())
2021-07-15 13:17:07 +02:00
state = !state;
return state;
}
} // namespace
} // namespace deckenlampe