Ok, simply and fix up this crap.
authorScott Gasch <[email protected]>
Mon, 27 Feb 2023 21:58:17 +0000 (13:58 -0800)
committerScott Gasch <[email protected]>
Mon, 27 Feb 2023 21:58:17 +0000 (13:58 -0800)
kiosk.py

index 083e91760000ecfb5bcdfa8b8cdcfe2d7896865f..5ff6e1ce67d9fd7dd03d4604565ba092f85a6e2a 100755 (executable)
--- a/kiosk.py
+++ b/kiosk.py
@@ -10,7 +10,7 @@ import re
 from threading import Thread
 import time
 import tracemalloc
-from typing import Dict, List, Optional
+from typing import Dict, List, Optional, Tuple
 from queue import Queue
 
 import astral  # type: ignore
@@ -229,53 +229,71 @@ def thread_change_current(command_queue: Queue) -> None:
             or "wsj" in page
         )
 
-    page_chooser = chooser.weighted_random_chooser_with_triggers(
-        trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
-    )
-    current_file = os.path.join(kiosk_constants.pages_dir, "current.shtml")
-    emergency_file = os.path.join(kiosk_constants.pages_dir, "reload_immediately.html")
-
-    # Main chooser loop
-    while True:
-        now = time.time()
-
-        # Check for a verbal command.
+    def check_for_command() -> Tuple[Optional[str], Optional[str]]:
         command = None
         try:
             command = command_queue.get(block=False)
         except Exception:
             command = None
 
-        if command is not None:
+        if command:
             logger.info(
                 f'chooser: We got a verbal command ("{command}"), parsing it...'
             )
             page = process_command(command, page_history, page_chooser)
             if page:
-                triggered = True
+                return page, command
+        return None, None
 
-        if not triggered:
-            while True:
-                (page, triggered) = page_chooser.choose_next_page()
-                if triggered:
-                    logger.info("chooser: A trigger is active...")
-                    break
+    def choose_page_randomly() -> Tuple[str, bool]:
+        while True:
+            (page, triggered) = page_chooser.choose_next_page()
+            if triggered:
+                logger.info("chooser: A trigger is active...")
+                break
+            else:
+                if page == page_history[0]:
+                    logger.debug(
+                        f"chooser: {page} is the same as last time! Try again."
+                    )
                 else:
-                    if page == page_history[0]:
-                        logger.debug(
-                            f"chooser: {page} is the same as last time! Try again."
-                        )
-                    else:
-                        break
+                    break
+        return (page, triggered)
 
+    page_chooser = chooser.weighted_random_chooser_with_triggers(
+        trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
+    )
+    current_file = os.path.join(kiosk_constants.pages_dir, "current.shtml")
+    emergency_file = os.path.join(kiosk_constants.pages_dir, "reload_immediately.html")
+
+    # Main chooser loop -- note that this executes a couple of times per second
+    # to be responsive to triggers.
+    while True:
+        now = time.time()
+        page = None
+        triggered = False
+        command = None
+
+        # Is there a verbal command to parse?
+        (page, command) = check_for_command()
+        if page and command:
+            triggered = True
+        else:
+            # If not, choose the a (new!) page randomly or respond to a trigger.
+            (page, triggered) = choose_page_randomly()
+
+        # By now we have a page and we may be triggered.
         if triggered:
-            if page != page_history[0] or (swap_page_target - now) < 10.0:
+
+            # If we are triggered and the page is new, change the
+            # current page to the new page immediately.
+            if page != page_history[0]:
                 logger.info(
                     f"chooser: An emergency page reload to {page} is needed at this time."
                 )
                 swap_page_target = now + kiosk_constants.emergency_refresh_period_sec
 
-                # Set current.shtml to the right page.
+                # Set current.shtml to the triggered page.
                 try:
                     with open(current_file, "w") as f:
                         emit(
@@ -285,14 +303,13 @@ def thread_change_current(command_queue: Queue) -> None:
                             command=command,
                         )
                     logger.debug(f"chooser: Wrote {current_file}.")
-                except Exception as e:
-                    logger.exception(e)
-                    logger.error(
+                except Exception:
+                    logger.exception(
                         f"chooser: Unexpected exception; assuming {page} doesn't exist?!"
                     )
                     continue
 
-                # Also notify XMLHTTP clients that they need to refresh now.
+                # Notify XMLHTTP clients that they need to refresh now.
                 with open(emergency_file, "w") as f:
                     f.write(f"Reload, suckers... you HAVE to see {page}!")
                 logger.debug(f"chooser: Wrote {emergency_file}...")
@@ -302,23 +319,25 @@ def thread_change_current(command_queue: Queue) -> None:
                 time.sleep(0.999)
                 os.remove(emergency_file)
                 logger.debug(f"chooser: ...and removed {emergency_file}.")
+                page_history.insert(0, page)
+                page_history = page_history[0:10]
 
+        # If we're not triggered, only render a new page if time has expired.
         elif now >= swap_page_target:
-            assert page != page_history[0]
             logger.info(f"chooser: Nominal choice of {page} as the next to show.")
             swap_page_target = now + kiosk_constants.refresh_period_sec
             try:
                 with open(current_file, "w") as f:
                     emit(f, page)
                 logger.debug(f"chooser: Wrote {current_file}.")
-            except Exception as e:
-                logger.exception(e)
-                logger.error(
+            except Exception:
+                logger.exception(
                     f"chooser: Unexpected exception; assuming {page} doesn't exist?!"
                 )
                 continue
-        page_history.insert(0, page)
-        page_history = page_history[0:10]
+            page_history.insert(0, page)
+            page_history = page_history[0:10]
+
         time.sleep(0.5)