 uint16 readTelegram(byte *buffer, uint16 size) {
   uint16 i;
   byte state = 0;
+  unsigned long start_time = millis();
   for (i = 0; i < size; i++) {
-    int b = P1_INPUT.read();
-    if (b < 0) {
-      Serial.println("Read timed out before telegram end sequence");
-      return 0;
-    }
+    int b;
+    do {
+      unsigned long now = millis();
+      if (now - start_time > READ_TIMEOUT_MILLIS) {
+        Serial.print("Telegram read timed out after ");
+        Serial.print(READ_TIMEOUT_MILLIS);
+        Serial.print(" ms, having read ");
+        Serial.print(i);
+        Serial.println(" bytes");
+        return 0;
+      }
+
+      b = P1_INPUT.read();
+    } while (b < 0);
     buffer[i] = b;
 
     // Each telegram ends with a line like this:

        if (b == '\n') state++; else state = 0;
    }

    if (state == 8) {
      readGarbage(true);
      return i;
    }
  }
  Serial.print("Telegram buffer overflow after ");
  Serial.print(size);
  Serial.println(" bytes");
  readGarbage(false);
  return 0;
}


#define P1_BUFFER_SIZE_BYTES 64

#define MAX_TELEGRAM_SIZE 4096

#define READ_TIMEOUT_MILLIS 1000

#ifndef SERVER_PORT
#define SERVER_PORT 443
