Files
ESP-Telegram-Server-Bot/main.ino
2025-10-03 21:06:28 +02:00

228 lines
5.9 KiB
C++

//------------DEFINITIONS------------
// Libaries
#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>
// 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<numNewMessages; i++) {
// Chat id of the requester
String chat_id = String(bot.messages[i].chat_id);
// Print the received message
String text = bot.messages[i].text;
Serial.println(text);
// Handling Start/Help
String from_name = bot.messages[i].from_name;
if (text == "/start" || text == "/help") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following commands to control your outputs.\n\n";
welcome += "/state to request current server state \n";
welcome += "/on to boot server \n";
welcome += "/off to shutdown server \n";
bot.sendMessage(chat_id, welcome, "");
}
// Handling turn-on
else if (text == "/on" and powerState == LOW) {
bot.sendMessage(chat_id, "Booting Server..." "");
switchPowerState(HIGH);
if (powerState = HIGH) {
bot.sendMessage(chat_id, "Bootup succeded" "");
}
else
{
bot.sendMessage(chat_id, "[WARNING]: Bootup failed" "");
}
}
// Handling turn-off
else if (text == "/off" and powerState == HIGH) {
bot.sendMessage(chat_id, "Shutting down Server..." "");
switchPowerState(LOW);
if (powerState = LOW) {
bot.sendMessage(chat_id, "Shutdown succeded" "");
}
else
{
bot.sendMessage(chat_id, "[WARNING]: Shutdown failed" "");
}
}
// Handling unnessassary turn-on
else if (text == "/on" and powerState == HIGH) {
bot.sendMessage(chat_id, "Server is already online" "");
}
// Handling unnessassary turn-off
else if (text == "/off" and powerState == LOW) {
bot.sendMessage(chat_id, "Server is already offline" "");
}
// Waiting for change in power-state
else if (text == "/state") {
checkPowerState();
if (powerState == HIGH) {
bot.sendMessage(chat_id, "Server is online" "");
}
else {
bot.sendMessage(chat_id, "Server is offline" "");
}
}
}
}
//------------SETUP------------
void setup() {
Serial.begin(9600);
// Telegram Certification
#ifdef ESP8266
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
#endif
// GPIO-Initialisation
pinMode(powerPin, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(powerPin, powerState);
// Changing Mac-Address
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Old MacAdress: ");
Serial.println(WiFi.macAddress());
wifi_set_macaddr(0, &newMACAddress[0]);
Serial.print("New MacAdress: ");
Serial.println(WiFi.macAddress());
// Connect to WiFi
#ifdef ESP32
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());
}
//------------LOOP------------
void loop() {
// Checking power-state
checkPowerState();
// Signal Activity
digitalWrite(LED_BUILTIN, LOW);
// Handling Messages
Serial.println("Checking for messages...");
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
// Signal Activity
digitalWrite(LED_BUILTIN, HIGH);
// Delay
delay(botRequestDelay);
}