79 lines
1.3 KiB
C++
79 lines
1.3 KiB
C++
#ifndef SENSOR3_OUTPUT_H
|
|
#define SENSOR3_OUTPUT_H
|
|
|
|
#include "base.h"
|
|
|
|
class Output {
|
|
|
|
private:
|
|
|
|
const int pin;
|
|
|
|
const bool invert;
|
|
|
|
uint64_t onSince = 0;
|
|
|
|
uint64_t offSince = 0;
|
|
|
|
uint64_t totalOnMillis = 0;
|
|
|
|
public:
|
|
|
|
Output(const int pin, const bool invert, const bool initial) : pin(pin), invert(invert) {
|
|
pinMode(pin, OUTPUT);
|
|
set(initial);
|
|
}
|
|
|
|
void loop() {
|
|
uint64_t now = getUptimeMillis();
|
|
static uint64_t last = now;
|
|
if (isOn()) {
|
|
totalOnMillis += now - last;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] bool isOn() const {
|
|
return (digitalRead(pin) == HIGH) ^ invert;
|
|
}
|
|
|
|
void on() {
|
|
set(true);
|
|
}
|
|
|
|
void off() {
|
|
set(false);
|
|
}
|
|
|
|
void set(const bool newState) {
|
|
if (isOn() != newState) {
|
|
digitalWrite(pin, newState ^ invert ? HIGH : LOW);
|
|
if (newState) {
|
|
onSince = getUptimeMillis();
|
|
} else {
|
|
offSince = getUptimeMillis();
|
|
}
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] uint64_t getOnSince() const {
|
|
if (!isOn()) {
|
|
return 0;
|
|
}
|
|
return getUptimeMillis() - onSince;
|
|
}
|
|
|
|
[[nodiscard]] uint64_t getOffSince() const {
|
|
if (isOn()) {
|
|
return 0;
|
|
}
|
|
return getUptimeMillis() - offSince;
|
|
}
|
|
|
|
[[nodiscard]] uint64_t getTotalOnMillis() const {
|
|
return totalOnMillis;
|
|
}
|
|
|
|
};
|
|
|
|
#endif
|