Advertisement
safwan092

Untitled

Dec 7th, 2021
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.37 KB | None | 0 0
  1. #include <WiFi.h>
  2. #include <WiFiClientSecure.h>
  3. #include "soc/soc.h"
  4. #include "soc/rtc_cntl_reg.h"
  5. #include "esp_camera.h"
  6. #include <UniversalTelegramBot.h>
  7. #include <ArduinoJson.h>
  8. #include <Wire.h>
  9. #include "SparkFunBME280.h"
  10.  
  11. // Replace with your network credentials
  12. const char* ssid = "gg";
  13. const char* password = "123456789";
  14.  
  15. // Use @myidbot to find out the chat ID of an individual or a group
  16. // Also note that you need to click "start" on a bot before it can
  17. // message you
  18. String chatId = "1103375087";
  19.  
  20. // Initialize Telegram BOT
  21. String BOTtoken = "2092224612:AAGmLz-G6VwGtuCQXC-YGRvfuwiAR4HSsDo";
  22.  
  23. bool sendPhoto = false;
  24.  
  25. WiFiClientSecure clientTCP;
  26.  
  27. UniversalTelegramBot bot(BOTtoken, clientTCP);
  28.  
  29. //CAMERA_MODEL_AI_THINKER
  30. #define PWDN_GPIO_NUM 32
  31. #define RESET_GPIO_NUM -1
  32. #define XCLK_GPIO_NUM 0
  33. #define SIOD_GPIO_NUM 26
  34. #define SIOC_GPIO_NUM 27
  35.  
  36. #define Y9_GPIO_NUM 35
  37. #define Y8_GPIO_NUM 34
  38. #define Y7_GPIO_NUM 39
  39. #define Y6_GPIO_NUM 36
  40. #define Y5_GPIO_NUM 21
  41. #define Y4_GPIO_NUM 19
  42. #define Y3_GPIO_NUM 18
  43. #define Y2_GPIO_NUM 5
  44. #define VSYNC_GPIO_NUM 25
  45. #define HREF_GPIO_NUM 23
  46. #define PCLK_GPIO_NUM 22
  47.  
  48. #define FLASH_LED_PIN 4
  49. bool flashState = LOW;
  50.  
  51. // Motion Sensor
  52. bool motionDetected = false;
  53. #define pirSensorPin = 12;
  54.  
  55. // Define I2C Pins for BME280
  56. #define I2C_SDA 14
  57. #define I2C_SCL 15
  58.  
  59. BME280 bme;
  60.  
  61. int botRequestDelay = 1000; // mean time between scan messages
  62. long lastTimeBotRan; // last time messages' scan has been done
  63.  
  64. void handleNewMessages(int numNewMessages);
  65. String sendPhotoTelegram();
  66.  
  67. // Get BME280 sensor readings and return them as a String variable
  68. String getReadings() {
  69. float temperature, humidity;
  70. temperature = bme.readTempC();
  71. //temperature = bme.readTempF();
  72. humidity = bme.readFloatHumidity();
  73. String message = "Temperature: " + String(temperature) + " ºC \n";
  74. message += "Humidity: " + String (humidity) + " % \n";
  75. return message;
  76. }
  77.  
  78. // Indicates when motion is detected
  79. static void IRAM_ATTR detectsMovement(void * arg) {
  80. //Serial.println("MOTION DETECTED!!!");
  81. motionDetected = true;
  82. }
  83.  
  84. void setup() {
  85. WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  86. Serial.begin(115200);
  87. pinMode(pirSensorPin, INPUT);
  88. pinMode(FLASH_LED_PIN, OUTPUT);
  89. digitalWrite(FLASH_LED_PIN, flashState);
  90.  
  91. // Init BME280 sensor
  92. Wire.begin(I2C_SDA, I2C_SCL);
  93. bme.settings.commInterface = I2C_MODE;
  94. bme.settings.I2CAddress = 0x76;
  95. bme.settings.runMode = 3;
  96. bme.settings.tStandby = 0;
  97. bme.settings.filter = 0;
  98. bme.settings.tempOverSample = 1;
  99. bme.settings.pressOverSample = 1;
  100. bme.settings.humidOverSample = 1;
  101. bme.begin();
  102.  
  103. WiFi.mode(WIFI_STA);
  104. Serial.println();
  105. Serial.print("Connecting to ");
  106. Serial.println(ssid);
  107. WiFi.begin(ssid, password);
  108. clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  109. while (WiFi.status() != WL_CONNECTED) {
  110. Serial.print(".");
  111. delay(500);
  112. }
  113. Serial.println();
  114. Serial.print("ESP32-CAM IP Address: ");
  115. Serial.println(WiFi.localIP());
  116.  
  117. camera_config_t config;
  118. config.ledc_channel = LEDC_CHANNEL_0;
  119. config.ledc_timer = LEDC_TIMER_0;
  120. config.pin_d0 = Y2_GPIO_NUM;
  121. config.pin_d1 = Y3_GPIO_NUM;
  122. config.pin_d2 = Y4_GPIO_NUM;
  123. config.pin_d3 = Y5_GPIO_NUM;
  124. config.pin_d4 = Y6_GPIO_NUM;
  125. config.pin_d5 = Y7_GPIO_NUM;
  126. config.pin_d6 = Y8_GPIO_NUM;
  127. config.pin_d7 = Y9_GPIO_NUM;
  128. config.pin_xclk = XCLK_GPIO_NUM;
  129. config.pin_pclk = PCLK_GPIO_NUM;
  130. config.pin_vsync = VSYNC_GPIO_NUM;
  131. config.pin_href = HREF_GPIO_NUM;
  132. config.pin_sscb_sda = SIOD_GPIO_NUM;
  133. config.pin_sscb_scl = SIOC_GPIO_NUM;
  134. config.pin_pwdn = PWDN_GPIO_NUM;
  135. config.pin_reset = RESET_GPIO_NUM;
  136. config.xclk_freq_hz = 20000000;
  137. config.pixel_format = PIXFORMAT_JPEG;
  138.  
  139. //init with high specs to pre-allocate larger buffers
  140. if (psramFound()) {
  141. config.frame_size = FRAMESIZE_UXGA;
  142. config.jpeg_quality = 10; //0-63 lower number means higher quality
  143. config.fb_count = 2;
  144. } else {
  145. config.frame_size = FRAMESIZE_SVGA;
  146. config.jpeg_quality = 12; //0-63 lower number means higher quality
  147. config.fb_count = 1;
  148. }
  149.  
  150. // camera init
  151. esp_err_t err = esp_camera_init(&config);
  152. if (err != ESP_OK) {
  153. Serial.printf("Camera init failed with error 0x%x", err);
  154. delay(1000);
  155. ESP.restart();
  156. }
  157.  
  158. // Drop down frame size for higher initial frame rate
  159. sensor_t * s = esp_camera_sensor_get();
  160. s->set_framesize(s, FRAMESIZE_CIF); // UXGA|SXGA|XGA|SVGA|VGA|CIF|QVGA|HQVGA|QQVGA
  161.  
  162. /*
  163. // PIR Motion Sensor mode INPUT_PULLUP
  164. //err = gpio_install_isr_service(0);
  165. err = gpio_isr_handler_add(GPIO_NUM_13, &detectsMovement, (void *) 13);
  166. if (err != ESP_OK){
  167. Serial.printf("handler add failed with error 0x%x \r\n", err);
  168. }
  169. err = gpio_set_intr_type(GPIO_NUM_13, GPIO_INTR_POSEDGE);
  170. if (err != ESP_OK){
  171. Serial.printf("set intr type failed with error 0x%x \r\n", err);
  172. }
  173. */
  174. }
  175.  
  176. void loop() {
  177. if (sendPhoto) {
  178. Serial.println("Preparing photo");
  179. sendPhotoTelegram();
  180. sendPhoto = false;
  181. }
  182.  
  183. if (digitalRead(pirSensorPin)) {
  184. bot.sendMessage(chatId, "Motion detected!!", "");
  185. Serial.println("Motion Detected");
  186. sendPhotoTelegram();
  187. motionDetected = false;
  188. }
  189.  
  190. if (millis() > lastTimeBotRan + botRequestDelay) {
  191. int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  192. while (numNewMessages) {
  193. Serial.println("got response");
  194. handleNewMessages(numNewMessages);
  195. numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  196. }
  197. lastTimeBotRan = millis();
  198. }
  199. }
  200.  
  201. String sendPhotoTelegram() {
  202. const char* myDomain = "api.telegram.org";
  203. String getAll = "";
  204. String getBody = "";
  205.  
  206. camera_fb_t * fb = NULL;
  207. fb = esp_camera_fb_get();
  208. if (!fb) {
  209. Serial.println("Camera capture failed");
  210. delay(1000);
  211. ESP.restart();
  212. return "Camera capture failed";
  213. }
  214.  
  215. Serial.println("Connect to " + String(myDomain));
  216.  
  217. if (clientTCP.connect(myDomain, 443)) {
  218. Serial.println("Connection successful");
  219.  
  220. String head = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"chat_id\"; \r\n\r\n" + chatId + "\r\n--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
  221. String tail = "\r\n--RandomNerdTutorials--\r\n";
  222.  
  223. uint16_t imageLen = fb->len;
  224. uint16_t extraLen = head.length() + tail.length();
  225. uint16_t totalLen = imageLen + extraLen;
  226.  
  227. clientTCP.println("POST /bot" + BOTtoken + "/sendPhoto HTTP/1.1");
  228. clientTCP.println("Host: " + String(myDomain));
  229. clientTCP.println("Content-Length: " + String(totalLen));
  230. clientTCP.println("Content-Type: multipart/form-data; boundary=RandomNerdTutorials");
  231. clientTCP.println();
  232. clientTCP.print(head);
  233.  
  234. uint8_t *fbBuf = fb->buf;
  235. size_t fbLen = fb->len;
  236. for (size_t n = 0; n < fbLen; n = n + 1024) {
  237. if (n + 1024 < fbLen) {
  238. clientTCP.write(fbBuf, 1024);
  239. fbBuf += 1024;
  240. }
  241. else if (fbLen % 1024 > 0) {
  242. size_t remainder = fbLen % 1024;
  243. clientTCP.write(fbBuf, remainder);
  244. }
  245. }
  246.  
  247. clientTCP.print(tail);
  248.  
  249. esp_camera_fb_return(fb);
  250.  
  251. int waitTime = 10000; // timeout 10 seconds
  252. long startTimer = millis();
  253. boolean state = false;
  254.  
  255. while ((startTimer + waitTime) > millis()) {
  256. Serial.print(".");
  257. delay(100);
  258. while (clientTCP.available()) {
  259. char c = clientTCP.read();
  260. if (state == true) getBody += String(c);
  261. if (c == '\n') {
  262. if (getAll.length() == 0) state = true;
  263. getAll = "";
  264. }
  265. else if (c != '\r')
  266. getAll += String(c);
  267. startTimer = millis();
  268. }
  269. if (getBody.length() > 0) break;
  270. }
  271. clientTCP.stop();
  272. Serial.println(getBody);
  273. }
  274. else {
  275. getBody = "Connected to api.telegram.org failed.";
  276. Serial.println("Connected to api.telegram.org failed.");
  277. }
  278. return getBody;
  279. }
  280.  
  281. void handleNewMessages(int numNewMessages) {
  282. Serial.print("Handle New Messages: ");
  283. Serial.println(numNewMessages);
  284.  
  285. for (int i = 0; i < numNewMessages; i++) {
  286. // Chat id of the requester
  287. String chat_id = String(bot.messages[i].chat_id);
  288. if (chat_id != chatId) {
  289. bot.sendMessage(chat_id, "Unauthorized user", "");
  290. continue;
  291. }
  292.  
  293. // Print the received message
  294. String text = bot.messages[i].text;
  295. Serial.println(text);
  296.  
  297. String fromName = bot.messages[i].from_name;
  298.  
  299. if (text == "/flash") {
  300. flashState = !flashState;
  301. digitalWrite(FLASH_LED_PIN, flashState);
  302. }
  303. if (text == "/photo") {
  304. sendPhoto = true;
  305. Serial.println("New photo request");
  306. }
  307. if (text == "/readings") {
  308. String readings = getReadings();
  309. bot.sendMessage(chatId, readings, "");
  310. }
  311. if (text == "/start") {
  312. String welcome = "Welcome to the ESP32-CAM Telegram bot.\n";
  313. welcome += "/photo : takes a new photo\n";
  314. welcome += "/flash : toggle flash LED\n";
  315. welcome += "/readings : request sensor readings\n\n";
  316. welcome += "You'll receive a photo whenever motion is detected.\n";
  317. bot.sendMessage(chatId, welcome, "Markdown");
  318. }
  319. }
  320. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement