From 5cba359881c2620dcb47487f4fb19390104b7bf3 Mon Sep 17 00:00:00 2001 From: bdnugget Date: Tue, 10 Jun 2025 00:52:34 +0200 Subject: [PATCH] Initial working Telegram bot, LDR and LED --- .gitignore | 1 + Arduino/Arduino.ino | 23 ++++++ Arduino/LDRtest/LDRtest.ino | 16 ++++ ESP8266/ESP8266.ino | 160 ++++++++++++++++++++++++++++++++++++ ESP8266/secrets_template.h | 6 ++ README.md | 13 +++ 6 files changed, 219 insertions(+) create mode 100644 .gitignore create mode 100755 Arduino/Arduino.ino create mode 100644 Arduino/LDRtest/LDRtest.ino create mode 100644 ESP8266/ESP8266.ino create mode 100644 ESP8266/secrets_template.h create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..562d8fb --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +ESP8266/secrets.h \ No newline at end of file diff --git a/Arduino/Arduino.ino b/Arduino/Arduino.ino new file mode 100755 index 0000000..65ff171 --- /dev/null +++ b/Arduino/Arduino.ino @@ -0,0 +1,23 @@ +#define LEDPIN 8 + +String incomingString; + +void setup() { + pinMode(LEDPIN, OUTPUT); + Serial.begin(9600); +} + +void loop() { + if (Serial.available() > 0) { + char cmd = Serial.read(); + if (cmd == 'O') { + digitalWrite(LEDPIN, HIGH); // Open + } else if (cmd == 'C') { + digitalWrite(LEDPIN, LOW); // Close + } else if (cmd == 'R') { + int ldrValue = analogRead(A0); + Serial.println(ldrValue); + } + } + delay(50); +} diff --git a/Arduino/LDRtest/LDRtest.ino b/Arduino/LDRtest/LDRtest.ino new file mode 100644 index 0000000..b889f65 --- /dev/null +++ b/Arduino/LDRtest/LDRtest.ino @@ -0,0 +1,16 @@ +/* LDR test measuring with A0 in middle of 10k Ohm resistor and LDR + * +5V ---[ LDR ]---+---[ Resistor ]--- GND + | + Analog A0 +*/ + +void setup() { + Serial.begin(9600); +} + +void loop() { + int value = analogRead(A0); // Reads value between 0 and 1023 + Serial.println(value); + delay(500); +} + diff --git a/ESP8266/ESP8266.ino b/ESP8266/ESP8266.ino new file mode 100644 index 0000000..26962e3 --- /dev/null +++ b/ESP8266/ESP8266.ino @@ -0,0 +1,160 @@ +#include +#include +#include +#include +#include "secrets.h" + +// --- WiFi & Telegram Config --- +const char* ssid = WIFI_SSID; +const char* password = WIFI_PASS; +const char* botToken = TELEGRAM_BOT_TOKEN; +const char* chatID = TELEGRAM_CHAT_ID; + +WiFiClientSecure telegramClient; + +// --- Timing --- +long lastUpdateId = 0; +unsigned long lastTelegramCheck = 0; +const unsigned long telegramCheckInterval = 10000; // 10 seconds +unsigned long lastLDRSend = 0; +const unsigned long ldrSendInterval = 5UL * 60UL * 1000UL; // 5 minutes + +// --- Utility: URL Encode --- +String urlencode(const String& str) { + String encoded = ""; + char c; + char code0, code1; + for (unsigned int i = 0; i < str.length(); i++) { + c = str.charAt(i); + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + encoded += c; + } else { + code1 = (c & 0xf) + '0'; + if ((c & 0xf) > 9) code1 = (c & 0xf) - 10 + 'A'; + c = (c >> 4) & 0xf; + code0 = c + '0'; + if (c > 9) code0 = c - 10 + 'A'; + encoded += '%'; + encoded += code0; + encoded += code1; + } + } + return encoded; +} + +// --- Telegram Messaging --- +void sendTelegramMessage(String message) { + if (WiFi.status() != WL_CONNECTED) return; + HTTPClient http; + String url = "https://api.telegram.org/bot" + String(botToken) + + "/sendMessage?chat_id=" + String(chatID) + + "&text=" + urlencode(message); + http.begin(telegramClient, url); + int httpCode = http.GET(); + http.end(); +} + +// --- LDR Handling --- +void sendLDRToTelegram() { + Serial.write('R'); + unsigned long start = millis(); + String ldrValue = ""; + while (millis() - start < 2000) { // wait up to 2 seconds + if (Serial.available()) { + ldrValue = Serial.readStringUntil('\n'); + ldrValue.trim(); + break; + } + } + if (ldrValue.length() > 0) { + sendTelegramMessage("Current LDR value: " + ldrValue); + } else { + sendTelegramMessage("Failed to read LDR value from Arduino."); + } +} + +// --- Telegram Command Handling --- +void checkTelegramCommands() { + HTTPClient http; + String url = "https://api.telegram.org/bot" + String(botToken) + + "/getUpdates?offset=" + String(lastUpdateId + 1); + http.begin(telegramClient, url); + int httpCode = http.GET(); + if (httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + DynamicJsonDocument doc(2048); + DeserializationError error = deserializeJson(doc, payload); + if (error) { + http.end(); + return; + } + JsonArray results = doc["result"].as(); + for (JsonObject msg : results) { + lastUpdateId = msg["update_id"]; + long fromId = msg["message"]["from"]["id"]; + String text = msg["message"]["text"]; + if (String(fromId) != chatID) { + continue; + } + if (text == "/open_chickencoop") { + Serial.write('O'); + sendTelegramMessage("Opening chicken coop."); + } else if (text == "/close_chickencoop") { + Serial.write('C'); + sendTelegramMessage("Closing chicken coop."); + } else if (text == "/ldr") { + sendLDRToTelegram(); + } else { + sendTelegramMessage("Unknown command."); + } + } + } + http.end(); +} + +// --- Sync lastUpdateId on startup --- +void syncLastUpdateId() { + HTTPClient http; + String url = "https://api.telegram.org/bot" + String(botToken) + "/getUpdates"; + http.begin(telegramClient, url); + int httpCode = http.GET(); + if (httpCode == HTTP_CODE_OK) { + String payload = http.getString(); + DynamicJsonDocument doc(4096); + DeserializationError error = deserializeJson(doc, payload); + if (!error) { + JsonArray results = doc["result"].as(); + for (JsonObject msg : results) { + long updateId = msg["update_id"]; + if (updateId > lastUpdateId) lastUpdateId = updateId; + } + } + } + http.end(); +} + +// --- Setup --- +void setup() { + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + } + telegramClient.setInsecure(); + syncLastUpdateId(); + sendTelegramMessage("ESP8266 connected. IP: " + WiFi.localIP().toString()); +} + +// --- Main Loop --- +void loop() { + unsigned long now = millis(); + if (now - lastTelegramCheck >= telegramCheckInterval) { + lastTelegramCheck = now; + checkTelegramCommands(); + } + if (now - lastLDRSend >= ldrSendInterval) { + lastLDRSend = now; + sendLDRToTelegram(); + } +} diff --git a/ESP8266/secrets_template.h b/ESP8266/secrets_template.h new file mode 100644 index 0000000..2311ee0 --- /dev/null +++ b/ESP8266/secrets_template.h @@ -0,0 +1,6 @@ +#pragma once + +#define WIFI_SSID "your_wifi_ssid" +#define WIFI_PASS "your_wifi_password" +#define TELEGRAM_BOT_TOKEN "your_bot_token" +#define TELEGRAM_CHAT_ID "your_chat_id" \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..fdbc03f --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# Automatic chicken coop door opener and closer with Telegram notifier + +## Setup Secrets + +1. Copy `ESP8266/secrets_template.h` to `ESP8266/secrets.h`: + ```sh + cp ESP8266/secrets_template.h ESP8266/secrets.h + ``` +2. Edit `ESP8266/secrets.h` and fill in your WiFi and Telegram bot credentials. + +**Do not commit `secrets.h` to version control.** + +### Bdnugget 2025 \ No newline at end of file