【问题标题】:Not able to use GET method in WiFi initialization of program无法在程序的 WiFi 初始化中使用 GET 方法
【发布时间】: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++


【解决方案1】:

安全连接 (https) 需要检查证书的有效性。这包括检查日期。 ESP32 SDK 连接互联网后立即检索互联网时间,但需要几毫秒。

您可以通过将时间与大于 1970-01-01 的某个时间戳(这是默认的“未设置”时间)进行比较来检查是否已检索到时间。

time_t now = time(nullptr);
uint8_t timeoutCounter = 0;
while (now < SECS_YR_2000 && timeoutCounter < 10) {
   timeoutCounter++ 
   delay(100);
   now = time(nullptr);
}

#define SECS_YR_2000 ((time_t)(946684800UL))

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多