ESP32配置Telegram机器人要使用哪个库?

huangapple go评论83阅读模式
英文:

what library to use with ESP32 to configure a telegram bot?

问题

抱歉,以下是您的代码的翻译部分:

#include <Keypad.h> // 包括Keypad库
#include <WiFi.h> // 包括WiFi库
#include <UniversalTelegramBot.h> // 包括UniversalTelegramBot库
#include <MFRC522.h> // 包括MFRC522库

#define SS_PIN 5 // 定义MFRC522 RFID传感器的SS引脚
#define RST_PIN 23 // 定义MFRC522 RFID传感器的RST引脚
#define LED_PIN 2 // 定义LED引脚
#define BUZZER_PIN 4 // 定义蜂鸣器引脚
#define DOOR_PIN 16 // 定义门的引脚
const byte ROWS = 4; // 定义键盘中的行数
const byte COLS = 4; // 定义键盘中的列数
char keys[ROWS][COLS] = { // 定义键盘中的按键
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {14, 27, 26, 25}; // 定义键盘的行引脚
byte colPins[COLS] = {33, 32, 35, 34}; // 定义键盘的列引脚
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); // 创建Keypad对象

const char* ssid = "your_SSID"; // 用您的WiFi网络名称替换
const char* password = "your_PASSWORD"; // 用您的WiFi网络密码替换
const char* token = "6063247261:AAE-dCDewFBwZLQQzw_TwVpp40C8plhMhko"; // 用您的Telegram机器人令牌替换
const int chat_id = 594170852; // 用您的Telegram聊天ID替换
//WiFiClientSecure client; // 创建安全的WiFi客户端
//UniversalTelegramBot bot(token, client); // 创建UniversalTelegramBot对象

MFRC522 rfid(SS_PIN, RST_PIN); // 创建MFRC522对象
MFRC522::MIFARE_Key key; // 创建MFRC522 MIFARE密钥对象

int state = 0; // 初始化状态变量
String password_str = ""; // 初始化密码字符串
bool door_opened = false; // 初始化门的状态

void setup() {
  Serial.begin(9600); // 开始串行通信
  pinMode(LED_PIN, OUTPUT); // 将LED引脚设为输出
  pinMode(BUZZER_PIN, OUTPUT); // 将蜂鸣器引脚设为输出
  pinMode(DOOR_PIN, OUTPUT); // 将门的引脚设为输出
  digitalWrite(LED_PIN, LOW); // 关闭LED
  digitalWrite(BUZZER_PIN, LOW); // 关闭蜂鸣器
  digitalWrite(DOOR_PIN, LOW); // 关闭门
  WiFi.begin(ssid, password); // 连接到WiFi网络
  while (WiFi.status() != WL_CONNECTED) { // 等待WiFi连接建立
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  SPI.begin(); // 初始化SPI总线
  rfid.PCD_Init(); // 初始化MFRC522 RFID传感器
  for (byte i = 0; i < 6; i++) { // 初始化MIFARE密钥
    key.keyByte[i] = 0xFF;
  }
}

void loop() {
  switch (state) {
    case 0:
      password_str = ""; // 重置密码字符串
      Serial.println("Enter password:");
      state = 1; // 移动到下一个状态
      break;
    case 1:
      char key_pressed = keypad.getKey(); // 读取键盘上按下的按键
      if (key_pressed != NO_KEY) { // 如果按下了按键
        if (key_pressed == '#') { // 如果按下了'#'键
          if (password_str == "1234") { // 如果密码正确
            Serial.println("Password correct");
            open_door(); // 打开门
            state = 2; // 移动到下一个状态
          } else { // 如果密码错误
            Serial.println("Password incorrect");
            buzz(); // 响蜂鸣器
            state = 0; // 重置状态
          }
        } else { // 如果按下了数字键
          password_str += key_pressed; // 将按键添加到密码字符串中
        }
      }
      break;
    case 2:
      if (door_opened) { // 如果门已经打开
        send_telegram_message("Door opened via keypad"); // 向Telegram聊天发送消息,通知用户通过键盘打开了门
        door_opened = false; // 重置门的状态
      }
      state = 3; // 移动到下一个状态
      break;
    case 3:
      if (bot.getUpdates(bot.last_message_received + 1)) { // 检查是否有来自Telegram的消息
        handle_telegram_message(); // 处理收到的消息
      }
      break;
  }
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) { // 如果检测到RFID卡
    if (authenticate_card()) { // 如果卡片经过验证
      Serial.println("Card authenticated");
      open_door(); // 打开门
      send_telegram_message("Door opened via RFID"); // 向Telegram聊天发送消息,通知用户通过RFID打开了门
      delay(5000); // 等待5秒
      door_opened = false; // 重置门的状态
    } else { // 如果卡片未经过验证
      Serial.println("Card authentication failed");
      buzz(); // 响蜂鸣器
    }
    rfid.PICC_HaltA(); // 停止RFID标签
    rfid.PCD_StopCrypto1(); // 停止crypto1过程
  }
}

void open_door() {
  digitalWrite(LED_PIN, HIGH); // 打开LED
  digitalWrite(BUZZER_PIN, HIGH); // 打开蜂鸣器
  digitalWrite(DOOR_PIN, HIGH); //

<details>
<summary>英文:</summary>

hello stack overflow community.

i want to finish my graduation project, but am having trouble in the ESP32 coding.

i am making a smart safe box
the program should do the following:

 1. allow the user to open the safe door via keypad
 2. allow the user to open the safe door via RFID
 3. the safe is connected to a telegram bot, to make it possible to open the safe via telegram, and also receive the state of the safe box ( Door opened, door closed, wrong password entered, etc )

this is the code i did: 

#include <Keypad.h> // Include the Keypad library
#include <WiFi.h> // Include the WiFi library
#include <UniversalTelegramBot.h> // Include the UniversalTelegramBot library
#include <MFRC522.h> // Include the MFRC522 library

#define SS_PIN 5 // Define the SS pin for the MFRC522 RFID sensor
#define RST_PIN 23 // Define the RST pin for the MFRC522 RFID sensor
#define LED_PIN 2 // Define the LED pin
#define BUZZER_PIN 4 // Define the buzzer pin
#define DOOR_PIN 16 // Define the pin for the door
const byte ROWS = 4; // Define the number of rows in the keypad
const byte COLS = 4; // Define the number of columns in the keypad
char keys[ROWS][COLS] = { // Define the keys in the keypad
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {14, 27, 26, 25}; // Define the row pins for the keypad
byte colPins[COLS] = {33, 32, 35, 34}; // Define the column pins for the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); // Create a Keypad object

const char* ssid = "your_SSID"; // Replace with your WiFi network name
const char* password = "your_PASSWORD"; // Replace with your WiFi network password
const char* token = "6063247261:AAE-dCDewFBwZLQQzw_TwVpp40C8plhMhko"; // Replace with your Telegram bot token
const int chat_id = 594170852; // Replace with your Telegram chat ID
//WiFiClientSecure client; // Create a secure WiFi client
//UniversalTelegramBot bot(token, client); // Create a UniversalTelegramBot object

MFRC522 rfid(SS_PIN, RST_PIN); // Create an MFRC522 object
MFRC522::MIFARE_Key key; // Create an MFRC522 MIFARE key object

int state = 0; // Initialize the state variable
String password_str = ""; // Initialize the password string
bool door_opened = false; // Initialize the door_opened boolean

void setup() {
Serial.begin(9600); // Start the serial communication
pinMode(LED_PIN, OUTPUT); // Set the LED pin as an output
pinMode(BUZZER_PIN, OUTPUT); // Set the buzzer pin as an output
pinMode(DOOR_PIN, OUTPUT); // Set the door pin as an output
digitalWrite(LED_PIN, LOW); // Turn off the LED
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
digitalWrite(DOOR_PIN, LOW); // Close the door
WiFi.begin(ssid, password); // Connect to the WiFi network
while (WiFi.status() != WL_CONNECTED) { // Wait for the WiFi connection to be established
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
SPI.begin(); // Initialize the SPI bus
rfid.PCD_Init(); // Initialize the MFRC522 RFID sensor
for (byte i = 0; i < 6; i++) { // Initialize the MIFARE key
key.keyByte[i] = 0xFF;
}
}

void loop() {
switch (state) {
case 0:
password_str = ""; // Reset the password string
Serial.println("Enter password:");
state = 1; // Move to the next state
break;
case 1:
char key_pressed = keypad.getKey(); // Read the key pressed on the keypad
if (key_pressed != NO_KEY) { // If a key is pressed
if (key_pressed == '#') { // If the '#' key is pressed
if (password_str == "1234") { // If the password is correct
Serial.println("Password correct");
open_door(); // Open the door
state = 2; // Move to the next state
} else { // If the password is incorrect
Serial.println("Password incorrect");
buzz(); // Buzz the buzzer
state = 0; // Reset the state
}
} else { // If a number key is pressed
password_str += key_pressed; // Add the key to the password string
}
}
break;
case 2:
if (door_opened) { // If the door has been opened
send_telegram_message("Door opened via keypad"); //Send a message to the Telegram chat to notify the user that the door has been opened via the keypad
door_opened = false; // Reset the door_opened boolean
}
state = 3; // Move to the next state
break;
case 3:
if (bot.getUpdates(bot.last_message_received + 1)) { // Check for incoming Telegram messages
handle_telegram_message(); // Handle the incoming message
}
break;
}
if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) { // If an RFID card is detected
if (authenticate_card()) { // If the card is authenticated
Serial.println("Card authenticated");
open_door(); // Open the door
send_telegram_message("Door opened via RFID"); // Send a message to the Telegram chat to notify the user that the door has been opened via RFID
delay(5000); // Wait for 5 seconds
door_opened = false; // Reset the door_opened boolean
} else { // If the card is not authenticated
Serial.println("Card authentication failed");
buzz(); // Buzz the buzzer
}
rfid.PICC_HaltA(); // Halt the RFID tag
rfid.PCD_StopCrypto1(); // Stop the crypto1 process
}
}

void open_door() {
digitalWrite(LED_PIN, HIGH); // Turn on the LED
digitalWrite(BUZZER_PIN, HIGH); // Turn on the buzzer
digitalWrite(DOOR_PIN, HIGH); // Open the door
delay(5000); // Wait for 5 seconds
digitalWrite(LED_PIN, LOW); // Turn off the LED
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
digitalWrite(DOOR_PIN, LOW); // Close the door
door_opened = true; // Set the door_opened boolean to true
}

void buzz() {
digitalWrite(BUZZER_PIN, HIGH); // Turn on the buzzer
delay(500); // Wait for 0.5 seconds
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
}

bool authenticate_card() {
MFRC522::StatusCode status;
byte buffer[18];
byte size = sizeof(buffer);
status = rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(rfid.uid)); // Authenticate the card using the MIFARE key
if (status != MFRC522::STATUS_OK) {
return false;
}
status = rfid.MIFARE_Read(1, buffer, &size); // Read the card data
if (status != MFRC522::STATUS_OK) {
return false;
}
return true;
}

void handle_telegram_message() {
for (int i = 0; i < bot.message_count(); i++) { // Loop through all the incoming messages
String chat_text = bot.messages[i].text; // Get the message text
int chat_from = bot.messages[i].from_id; // Get the chat ID
if (chat_text == "/open" && chat_from == chat_id) { // If the message is "/open" and the chat ID is correct
Serial.println("Door opened via telegram");
open_door(); // Open the door
send_telegram_message("Door opened via telegram"); // Send a message to the Telegram chat to notify the user that the door has been opened via Telegram
}
}
}

void send_telegram_message(String message) {
bot.sendMessage(chat_id, message); // Send a message to the Telegram chat
}


the errors am getting : 

D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino: In function 'void loop()':
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:83:10: error: jump to case label [-fpermissive]
case 2:
^
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:66:12: note: crosses initialization of 'char key_pressed'
char key_pressed = keypad.getKey(); // Read the key pressed on the keypad
^~~~~~~~~~~
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:90:10: error: jump to case label [-fpermissive]
case 3:
^
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:66:12: note: crosses initialization of 'char key_pressed'
char key_pressed = keypad.getKey(); // Read the key pressed on the keypad
^~~~~~~~~~~
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:91:11: error: 'bot' was not declared in this scope
if (bot.getUpdates(bot.last_message_received + 1)) { // Check for incoming Telegram messages
^~~
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:91:11: note: suggested alternative: 'bit'
if (bot.getUpdates(bot.last_message_received + 1)) { // Check for incoming Telegram messages
^~~
bit
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino: In function 'void handle_telegram_message()':
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:145:23: error: 'bot' was not declared in this scope
for (int i = 0; i < bot.message_count(); i++) { // Loop through all the incoming messages
^~~
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:145:23: note: suggested alternative: 'bit'
for (int i = 0; i < bot.message_count(); i++) { // Loop through all the incoming messages
^~~
bit
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino: In function 'void send_telegram_message(String)':
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:157:3: error: 'bot' was not declared in this scope
bot.sendMessage(chat_id, message); // Send a message to the Telegram chat
^~~
D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:157:3: note: suggested alternative: 'bit'
bot.sendMessage(chat_id, message); // Send a message to the Telegram chat
^~~
bit
Compilation error: jump to case label [-fpermissive]


any help please.
i tried talking to chatgpt but nothing were helpful.
</details>
# 答案1
**得分**: 1
作为一名学生,重要的是提出正确的问题,你面临的问题不是“要使用哪个库...”,而是为什么会出现这些错误消息,它们意味着什么?如何解决它们?同样重要的是要阅读错误消息并尝试理解其含义,你的错误日志基本上包含两个问题。
> 编译错误:跳转到 case 标签 [-fpermissive]
这个错误对于刚接触C++的程序员来说通常不太明显,所以我想在这里解释一下。在 `case 1` 中,你声明了一个 `key_pressed` 变量:
```cpp
char key_pressed = keypad.getKey(); // 读取键盘上按下的键

根据c++文档

如果在语句内部遇到声明语句,它必须在自己的复合语句中进行作用域限定

因此,为了解决这个问题,你需要用一对{}case 1 内的代码封装起来,以限定声明的作用域仅在 case 1 内。

case 1:
    {
      char key_pressed = keypad.getKey(); // 读取键盘上按下的键
      if (key_pressed != NO_KEY) { // 如果按下了键
        if (key_pressed == '#') { // 如果按下了'#'键
          if (password_str == "1234") { // 如果密码正确
            Serial.println("密码正确");
            open_door(); // 打开门
            state = 2; // 进入下一个状态
          } else { // 如果密码错误
            Serial.println("密码错误");
            buzz(); // 响铃
            state = 0; // 重置状态
          }
        } else { // 如果按下了数字键
          password_str += key_pressed; // 将按键添加到密码字符串中
        }
      }
    }
    break;

D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:91:11: 注意:建议的替代项:'bit'
if (bot.getUpdates(bot.last_message_received + 1)) { // 检查是否有传入的Telegram消息
^~~

这是你遇到的第二个错误,这是因为你注释掉了 //UniversalTelegramBot bot(token, client); 这行代码,所以 bot 不存在。为了实例化一个 bot 对象,你需要包括两个库:

#include <WiFi.h>
#include <WiFiClientSecure.h>

...
WiFiClientSecure client;
UniversalTelegramBot bot(token, client);

在你修复了这些错误之后,你的代码可能会出现其他错误,但你应该能够自己解决它们。祝你编程愉快,顺利完成毕业项目。

英文:

As a student, it is important to ask the right question, the question to the problem you are facing is not "what library to use...", but why do you get those error messages, what does it means? how to solve it? It is also equally import to read the error message and try to understand what it is means, your error log basically consists of two issues.

> Compilation error: jump to case label [-fpermissive]

This one is often not so obvious and puzzle to the programmers who are new to C++, so I'd like to explain here. In case 1, you had a declarative statement where you declare a key_pressed variable:

    char key_pressed = keypad.getKey(); // Read the key pressed on the keypad

According to c++ documentation:

> if a declaration statement is encountered inside the statement, it has to be scoped in its own compound statement

So to solve this issue, you need to encapsulate the code within the case 1 with a pair of { and } to limit the scope of the declaration is only within the scope of case 1.

case 1:
    {
      char key_pressed = keypad.getKey(); // Read the key pressed on the keypad
      if (key_pressed != NO_KEY) { // If a key is pressed
        if (key_pressed == &#39;#&#39;) { // If the &#39;#&#39; key is pressed
          if (password_str == &quot;1234&quot;) { // If the password is correct
            Serial.println(&quot;Password correct&quot;);
            open_door(); // Open the door
            state = 2; // Move to the next state
          } else { // If the password is incorrect
            Serial.println(&quot;Password incorrect&quot;);
            buzz(); // Buzz the buzzer
            state = 0; // Reset the state
          }
        } else { // If a number key is pressed
          password_str += key_pressed; // Add the key to the password string
        }
      }
    }
    break;

>D:\Study\Study\senior project 2\smartsafecode\smartsafecode.ino:91:11: note: suggested alternative: 'bit'
if (bot.getUpdates(bot.last_message_received + 1)) { // Check for incoming Telegram messages
^~~

This is the second error that you are facing, this is because you comment out the line //UniversalTelegramBot bot(token, client); so bot doesn't exist. In order to instantiate an bot object, you need to include two libraries:

#include &lt;WiFi.h&gt;
#include &lt;WiFiClientSecure.h&gt;

...
WiFiClientSecure client;
UniversalTelegramBot bot(token, client);

Your code may have other error popping up after you fixing those errors, but you should be able to solve it yourself. Happy coding and good luck to your graduation project.

huangapple
  • 本文由 发表于 2023年7月18日 02:19:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707141.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定