cotestatnt / AsyncTelegram2

Powerful, flexible and secure Arduino Telegram BOT library. Hardware independent, it can be used with any MCU capable of handling an SSL connection.
MIT License
85 stars 25 forks source link

ESP.reset() - looping #70

Closed gravedigger21 closed 2 years ago

gravedigger21 commented 2 years ago

Who can explain why after executing ESP.reset () there is a loop on the execution of the last command? I use this code:

void loop() {
  TBMessage msg;
  if (bot.getNewMessage(msg) ) {
    String msgText = msg.text;
    Serial.print("msgText = ");
    Serial.println(msgText);
    if (msgText.equals("/rst")) {
      bot.sendMessage(msg, "reset");
      Serial.println("reset"); Serial.println();
      ESP.reset();
    }
  }
}

The module receives a command, executes it, reboots and ... again receives the same command. And so it goes on indefinitely. Only uploading the same code with the commented-out ESP.reset() line helps. Here is what I get in Serial

Test Telegram connection... OK
msgText = /rst
reset

?)⸮
⸮⸮!H⸮.......
Test Telegram connection... OK
msgText = /rst
reset

?⸮⸮⸮1⸮D×⸮⸮⸮......
Test Telegram connection... OK
msgText = /rst
reset

⸮⸮⸮⸮L⸮⸮@`⸮9⸮⸮⸮⸮........
Test Telegram connection... OK
msgText = /rst
2dO,4⸮hl,⸮xd>x⸮⸮⸮⸮R⸮......⸮EO|t.......
Test Telegram connection... OK
msgText = /rst
reset

The last received message after a reboot is again perceived as a new one? What is it connected with?

cotestatnt commented 2 years ago

This is the same as https://github.com/cotestatnt/AsyncTelegram2/issues/62

You have to wait that message is fully handled before restart ESP. Check this example

    if (msgText.equals("/rst")) {
      bot.sendMessage(msg, "reset");
      Serial.println("reset"); Serial.println();

      // Wait until bot synced with telegram to prevent cyclic reboot
      while (!myBot.noNewMessage()) {
        Serial.print(".");
        delay(50);
      }
      ESP.reset();
    }
gravedigger21 commented 2 years ago

Yes, it works. But now I would like to understand why this happens. Why doesn't regular delay() before ESP.reset() help? When is a received command considered processed? Does the module send some kind of confirmation to the bot?

cotestatnt commented 2 years ago

When you send a request of update to Telegram server, it will reply with a list of last unreaded messages with specific message ID. In order to get last message marked as readed, the next update request have to request for the last message ID + 1 otherwise Telegram server will reply again with last one unreaded.

This is the reason why you need to wait for noNewMessage() in you sketch.