From f72e0ea5917e6869be7370b97ef6ec3e9b4df37c Mon Sep 17 00:00:00 2001
From: sqozz <sqozz-git@geekify.de>
Date: Tue, 17 Sep 2024 02:14:16 +0200
Subject: [PATCH] Add timeout while waiting for answer

---
 tw7100.cpp | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/tw7100.cpp b/tw7100.cpp
index 28f070a..8309280 100644
--- a/tw7100.cpp
+++ b/tw7100.cpp
@@ -9,6 +9,7 @@ namespace esphome {
 namespace tw7100 {
 
 bool waiting_for_answer = false;
+unsigned long waiting_for_answer_since = 0;
 std::deque<std::string> cmd_queue;
 unsigned long last_set_cmd_timestamp;
 
@@ -136,11 +137,16 @@ void tw7100Component::loop() {
         ESP_LOGV(TAG, "sending out command: %s", cmd.c_str());
         write_str((cmd + "\r\n").c_str());
         flush();
-	if (cmd.find("?") != std::string::npos) { // only wait for response on CMD? requests
+        if (cmd.find("?") != std::string::npos) { // only wait for response on CMD? requests
           waiting_for_answer = true;
-	} else {
+          waiting_for_answer_since = millis();
+        } else {
           last_set_cmd_timestamp = millis();
-	}
+        }
+      }
+      if (waiting_for_answer && (millis() - waiting_for_answer_since > 1000)) {
+        ESP_LOGE(TAG, "no response for last request since 1000ms, timing out!");
+        waiting_for_answer = false;
       }
     } else { // response found, handle eventual errors
       ESP_LOGV(TAG, "buffer content: %s", response.c_str());