diff --git a/main.ino b/main.ino new file mode 100644 index 0000000..a7c5cfa --- /dev/null +++ b/main.ino @@ -0,0 +1,228 @@ +//------------DEFINITIONS------------ +// Libaries +#ifdef ESP32 + #include +#else + #include +#endif +#include +#include // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot +#include + +// Replace with your network credentials +//const char* ssid = "S10"; +//const char* password = "aUjK67$2"; +const char* ssid = "SchneckenAufPasta"; +const char* password = "hf8CnyjPwrhc"; + + +// Initialize Telegram BOT +#define BOTtoken "5094918649:AAFPjufh6NMhPtwWeMwRAZMygFaDyMoRfXk" // your Bot Token (Get from Botfather) +#ifdef ESP8266 + X509List cert(TELEGRAM_CERTIFICATE_ROOT); +#endif +WiFiClientSecure client; +UniversalTelegramBot bot(BOTtoken, client); + + +// Variables +const int powerPin = D1; +const int powerStateReadPin = A0; +bool powerState = HIGH; //LOW = of +int t1, t2, t3, t4, t5, avg; +uint8_t newMACAddress[] = {0x32, 0xAE, 0xA4, 0x07, 0x0D, 0x66}; + + +// Tweaks & Settings +int botRequestDelay = 5000; +const int powerStateThreshhold = 470; //min 0=0V, max 1023=3.3V, 470=1.5V +const int maxCycles = 40; //c.a. 1.5s per cycle + + + + +//------------FUNCTIONS------------ +// Check current power-state +void checkPowerState() { + // Do multiple measurements to catch blinking led + t1 = analogRead(powerStateReadPin); + //delay(120); + t2 = analogRead(powerStateReadPin); + //delay(150); + t3 = analogRead(powerStateReadPin); + //delay(180); + t4 = analogRead(powerStateReadPin); + //delay(50); + t5 = analogRead(powerStateReadPin); + avg = (t1+t2+t3+t4+t5)/5; + + // Interprete Result + if (avg > powerStateThreshhold) { + powerState = HIGH; + } + else { + powerState = LOW; + } +} + +// Switch power state +void switchPowerState(bool desiredPowerState) { + // Simulate press of power-button + digitalWrite(powerPin, LOW); + delay(200); + digitalWrite(powerPin, HIGH); + + // Give the server time to boot + // My server does a double or tripple boot sometimes, so in this case, i wait for 2min + delay(60000); + + // Check PowerState + int i = 0; + Serial.print("Waiting for power change"); + while (powerState != desiredPowerState) + { + checkPowerState(); + i = i+1; + delay(1000); + Serial.print("."); + if (i == 36); //6min + { + break; + } + } + Serial.println("[OK]"); +} + +// Handle new messages +void handleNewMessages(int numNewMessages) { + Serial.println("handleNewMessages"); + Serial.println(String(numNewMessages)); + + // Fetch Message details + for (int i=0; i