#ifndef OUTPUT_H #define OUTPUT_H #include #include "Initial.h" class Output { protected: String name; const uint8_t pin; const bool inverted; const bool logState; Initial initial = INITIAL_OFF; long onCount = -1; unsigned long onMillis = 0; unsigned long offMillis = 0; unsigned long stateMillis = 0; void _write(const bool state) { if (state != get()) { if (logState) { Serial.printf("[RELAY] \"%s\" = %s\n", name.c_str(), state ? "ON" : "OFF"); } stateMillis = millis(); } digitalWrite(pin, state ^ inverted ? HIGH : LOW); } void _applyInitial() { _write(initial != INITIAL_OFF); if (initial != INITIAL_CYCLE) { onCount = 0; } else { onCount = -1; } } public: Output(const String &name, const uint8_t pin, const bool inverted, const bool logState) : name(name), pin(pin), inverted(inverted), logState(logState) { // } virtual ~Output() = default; virtual void setup() { pinMode(pin, OUTPUT); _applyInitial(); } bool get() const { return (digitalRead(pin) == HIGH) ^ inverted; } void set(const bool state) { _write(state); onCount = 0; } void toggle() { set(!get()); } void cycle(const unsigned long onMillis_, const unsigned long offMillis_, const unsigned long onCount_ = -1) { this->onMillis = onMillis_; this->offMillis = offMillis_; this->onCount = onCount_; set(false); } void loop() { if (get()) { if (onMillis > 0 && millis() - stateMillis > onMillis) { _write(false); } } else { if (offMillis > 0 && millis() - stateMillis > offMillis && onCount != 0) { _write(true); if (onCount > 0) { onCount--; } } } } virtual void setName(const String &value) { name = value; } virtual void setInitial(const Initial value) { initial = value; } void setOnCount(const long value) { onCount = value; } virtual void setOnMillis(const unsigned long value) { onMillis = value; } virtual void setOffMillis(const unsigned long value) { offMillis = value; } Initial getInitial() const { return initial; } long getOnCount() const { return onCount; } unsigned long getOnMillis() const { return onMillis; } unsigned long getOffMillis() const { return offMillis; } unsigned long getStateMillis() const { return millis() - stateMillis; } String getName() const { return name; } }; #endif