From 702396f8a2a4349a681d3f1071cbfef1b72e75a9 Mon Sep 17 00:00:00 2001 From: Ross 'H3ALY' Healy Date: Sat, 19 Oct 2024 09:39:07 +0100 Subject: [PATCH] Create power_control.h --- core/power_control.h | 60 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core/power_control.h diff --git a/core/power_control.h b/core/power_control.h new file mode 100644 index 0000000..78f2113 --- /dev/null +++ b/core/power_control.h @@ -0,0 +1,60 @@ +#ifndef POWER_CONTROL_H +#define POWER_CONTROL_H + +#include +#include + +class PowerController { +private: + const int powerButtonPin; + const int powerSensePin; + String currentStatus = "OFF"; + String oldStatus = "OFF"; + PubSubClient& client; + +public: + PowerController(int btnPin, int sensePin, PubSubClient& mqttClient) + : powerButtonPin(btnPin), powerSensePin(sensePin), client(mqttClient) {} + + void setup() { + pinMode(powerSensePin, INPUT_PULLDOWN_16); + pinMode(powerButtonPin, OUTPUT); + } + + void sensePower() { + if (pulseIn(powerSensePin, HIGH, 300000) > 100) { + setStatus("ON"); + } else if (digitalRead(powerSensePin) == HIGH) { + setStatus("ON"); + } else { + setStatus("OFF"); + } + } + + void setStatus(String status) { + if (currentStatus != status) { + currentStatus = status; + client.publish("state/PC", status.c_str(), true); + oldStatus = currentStatus; + } + } + + void handleCommand(const String& command) { + if (command == "ON" && currentStatus == "OFF") { + pressPowerButton(); + } else if (command == "OFF" && currentStatus == "ON") { + pressPowerButton(); + } else if (command == "FORCE OFF") { + pressPowerButton(10000); + } + } + +private: + void pressPowerButton(int pressDuration = 1000) { + digitalWrite(powerButtonPin, HIGH); + delay(pressDuration); + digitalWrite(powerButtonPin, LOW); + } +}; + +#endif