From 99808ed6f11eefaf167c51c38f139549e9002082 Mon Sep 17 00:00:00 2001
From: David Huss <dh@atoav.com>
Date: Mon, 15 Mar 2021 17:19:52 +0100
Subject: [PATCH] Add blinking if server is not reachable

---
 stechuhr_client/client.py | 51 ++++++++++++++++++++++++++++++++-------
 1 file changed, 42 insertions(+), 9 deletions(-)

diff --git a/stechuhr_client/client.py b/stechuhr_client/client.py
index ad4d967..0ed9873 100644
--- a/stechuhr_client/client.py
+++ b/stechuhr_client/client.py
@@ -83,7 +83,7 @@ def set_led(ledstate, config):
             time.sleep(repeat(config["led"]["success_on_time"], i))
             LEDS.fill((0, 0, 0))
             time.sleep(repeat(config["led"]["success_off_time"], i))
-    elif ledstate in ["failure", "error", "fail", "404"]:
+    elif ledstate in ["failure", "fail", "404"]:
         # Display the fitting LED color for the state at the given repetition
         for i in range(config["led"]["failure_repetitions"] + 1):
             LEDS.fill(repeat(config["led"]["failure_color"], i))
@@ -97,6 +97,12 @@ def set_led(ledstate, config):
             time.sleep(0.2)
             LEDS.fill((0, 0, 0))
             time.sleep(0.1)
+    elif ledstate in ["error"]:
+        for i in range(3):
+            LEDS.fill(config["led"]["failure_color"][0])
+            time.sleep(1)
+            LEDS.fill((0, 0, 0))
+            time.sleep(1)
 
     # Return to default standby LED color in the end
     LEDS.fill(config["led"]["standby_color"][0])
@@ -158,25 +164,49 @@ def process_request(output_queue, config=None, logger=None):
     Process a event from the output queue.
     This:
     1. Sends a requests
-    2. Reacts to a given respnse
+    2. Reacts to a given response
+    3. Blinks a LED red as long as the server cannot be reached
     """
     while (True):
         if (output_queue.qsize() > 0):
             verified_id = output_queue.get()
-            success = send_request(verified_id, config, logger)
-            if success:
+            response = send_request(verified_id, config, logger)
+            if response == "ok":
                 logger.info("Server Response: Success")
                 dispatch_led("success", config)
                 dispatch_buzzer("success", config)
-            else:
+            elif response == "failure":
                 logger.info("Server Response: Failed")
                 dispatch_led("failure", config)
                 dispatch_buzzer("failure", config)
+            elif response == "error":
+                if config["server"]["port"] == 80:
+                    protocol = "http"
+                else:
+                    protocol = "https"
+
+                url = '{}://{}/alive'.format(protocol, config["server"]["address"].rstrip("/"))
+                reached = False
+                attempts = 1
+                # Display the fitting LED color for the state at the given repetition
+                while not reached:
+                    dispatch_led("error", config)
+                    try:
+                        r = requests.get(url, timeout=config["server"]["timout"])
+                        if r.ok:
+                            reached == True
+                        else:
+                            if logger is not None:
+                                logger.warn("Didn't reach server at {} for {} attempts: Server responded with {}".format(url, attempts, r.status))
+                    except Exception as e:
+                        if logger is not None:
+                            logger.warn("Didn't reach server at {} for {} attempts: ".format(url, attempts, e))
+                        attempts += 1
         else:
             time.sleep(0.01)
 
 
-def send_request(verified_id, config, logger) -> bool:
+def send_request(verified_id, config, logger) -> str:
     """
     Send post request to stechuhr-server
     Return true if everything was ok, false otherwise
@@ -199,13 +229,16 @@ def send_request(verified_id, config, logger) -> bool:
             r = requests.post(target_address, json=payload, timeout=config["server"]["timeout"], verify=config["server"]["verify_cert"])
         except Exception as e:
             logger.error(e)
-            return False
-        return r.ok
+            return "error"
+        if r.ok:
+            return "ok"
+        else:
+            return "failure"
     else:
         # Always return true on dry run
         logger.info("Dryrun: Would post request to {}".format(target_address))
         logger.info("Dryrun: Payload: {}".format(str(payload)))
-        return True
+        return "ok"
 
 
 def id_pattern_check(visitor_id: str, config: dict) -> bool:
-- 
GitLab