【发布时间】:2022-01-21 19:43:08
【问题描述】:
我有一个向 Telegram 发送日志的功能。
当我从void setup() 或void loop() 函数或我定义的某个函数调用它时,此函数工作正常。
当我的 esp32 连接到 Wifi 时,我还想向 Telegram 发送消息。
这就是我的代码的样子。
void telegram_report(String error_message) {
String url = "";
url += "https://api.telegram.org/bot";
url += TELEGRAM_TOKEN;
url += "/sendMessage?chat_id=";
url += TELEGRAM_CHAT_ID;
url += "&parse_mode=Markdown&text=";
url += "[ ESP32(1) ] ";
url += error_message;
HTTPClient http;
http.begin(url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int countTries = 0;
int httpCode = -1;
while(httpCode == -1){
if (countTries > 3) {
Serial.println("[ ERR ] Could not send Error Report to Telegram. Max number of tries reached");
http.end();
Serial.println(error_message);
return;
}
httpCode = http.GET();
countTries++;
}
}
void connectToWiFi() {
Serial.println(" ");
Serial.print("[ INF ] Connencting to WiFi");
Serial.print(" ");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
unsigned long startAttemptTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < 20000) {
Serial.print(".");
delay(500);
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("[ ERR ] Failed connect to WiFi!");
delay(5000);
}
else {
String connected = "";
connected += "[ SUCC ] Connected to WiFi:";
connected += String(WIFI_NETWORK);
connected += " - with IP address ";
connected += String(WiFi.localIP());
telegram_report(connected); // This is where I'm struggling
}
}
当我从我的代码某处调用函数 telegram_report() 时,我能够得到对 Telegram 的响应。
但是当我尝试从 Wifi 连接函数调用该函数时,我什么也没得到。
当我拨打 telegram_report(connected); 时,我的 Wifi 连接已经建立。
可能是我将String 传递给函数而不是引用?
此外,当我尝试打印它时,我从String(WiFi.localIP()) 得到了奇怪的输出。是因为我将其转换为String?
【问题讨论】:
-
连接后未立即检索 TLS (https) 的 NTP 时间
-
我应该在调用函数之前使用 delay() 吗?
标签: string arduino esp32 arduino-c++