/* * hardware.cpp * * Created on: 27.05.2015 * Author: wn */ #include #include "hardware.h" #include #include "config.h" Switch::Switch() : m_state(false), m_feedbackState(false), m_stateConflict(false), m_lastButtonState(false), m_buttonEngineState(0), m_buttonTimestamp(0), m_ledEngineState(0), m_ledState(false), m_ledTimestamp(0), m_index(0) { } void Switch::begin(const uint8_t feedbackPin, const uint8_t buttonPin, const uint8_t relayPin, const uint8_t ledPin, uint8_t index) { m_feedbackPin = feedbackPin; m_buttonPin = buttonPin; m_relayPin = relayPin; m_ledPin = ledPin; m_index = index; if (! configIsValid()) { Serial << "Initializing config" << endl; bool initValue = false; configWrite(CONFIG_STATES_BEGIN + m_index, 1, (char*)&initValue); } pinMode(m_feedbackPin, INPUT_PULLUP); pinMode(m_buttonPin, INPUT_PULLUP); pinMode(m_relayPin, OUTPUT); digitalWrite(m_relayPin, true); pinMode(m_ledPin, OUTPUT); configRead(CONFIG_STATES_BEGIN + m_index, 1, (char*)&m_state); action(); } void Switch::toggle() { m_state = ! m_state; action(); } void Switch::on() { m_state = true; action(); } void Switch::off() { m_state = false; action(); } void Switch::action() { configWrite(CONFIG_STATES_BEGIN + m_index, 1, (char*)&m_state); digitalWrite(m_relayPin, ! m_state); } void Switch::exec() { uint32_t now = millis(); bool buttonState = digitalRead(m_buttonPin); switch (m_buttonEngineState) { case 0: if (! buttonState) { m_lastButtonState = buttonState; m_buttonTimestamp = now; m_buttonEngineState = 1; } break; case 1: if (m_buttonTimestamp + BUTTON_TIME < now) { m_buttonEngineState = 2; } if (m_lastButtonState != buttonState) { m_buttonEngineState = 0; } break; case 2: toggle(); m_buttonTimestamp = now; m_buttonEngineState = 3; break; case 3: if (m_buttonTimestamp + BUTTON_COOL_TIME < now) { m_buttonEngineState = 0; } break; default: m_buttonEngineState = 0; break; } m_feedbackState = ! digitalRead(m_feedbackPin); if (m_feedbackState == m_state) { digitalWrite(m_ledPin, m_state); m_stateConflict = false; } else { m_stateConflict = true; switch (m_ledEngineState) { case 0: digitalWrite(m_ledPin, m_ledState); m_ledTimestamp = now; m_ledEngineState = 1; break; case 1: if (m_ledTimestamp + BLINK_TIME < now) { m_ledState = ! m_ledState; m_ledEngineState = 0; } break; default: m_ledEngineState = 0; break; } } }