083e91760000ecfb5bcdfa8b8cdcfe2d7896865f
[kiosk.git] / kiosk.py
1 #!/usr/bin/env python3
2
3 import collections
4 from datetime import datetime
5 from difflib import SequenceMatcher
6 import gc
7 import logging
8 import os
9 import re
10 from threading import Thread
11 import time
12 import tracemalloc
13 from typing import Dict, List, Optional
14 from queue import Queue
15
16 import astral  # type: ignore
17 from astral.sun import sun  # type: ignore
18 import numpy as np
19 import pvporcupine
20 import pytz
21
22 from pyutils import (
23     bootstrap,
24     config,
25 )
26 from pyutils.datetimes import datetime_utils
27 from pyutils.files import file_utils
28
29 import kiosk_constants
30 import file_writer
31 import renderer_catalog
32 import chooser
33 import listen
34 import trigger_catalog
35
36
37 cfg = config.add_commandline_args(
38     f"Kiosk Server ({__file__})", "A python server that runs a kiosk."
39 )
40 logger = logging.getLogger(__file__)
41
42
43 def thread_janitor() -> None:
44     tracemalloc.start()
45     tracemalloc_target = 0.0
46     gc_target = 0.0
47     gc.enable()
48
49     # Main janitor loop; dump the largest pigs and force regular gcs.
50     while True:
51         now = time.time()
52         if now > tracemalloc_target:
53             tracemalloc_target = now + 30.0
54             snapshot = tracemalloc.take_snapshot()
55             snapshot = snapshot.filter_traces(
56                 (
57                     tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
58                     tracemalloc.Filter(False, "<unknown>"),
59                 )
60             )
61             key_type = "lineno"
62             limit = 10
63             top_stats = snapshot.statistics(key_type)
64             logger.info(f"janitor: Top {limit} lines")
65             for index, stat in enumerate(top_stats[:limit], 1):
66                 frame = stat.traceback[0]
67
68                 # replace "/path/to/module/file.py" with "module/file.py"
69                 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
70                 logger.info(
71                     f"janitor: #{index}: {filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB"
72                 )
73
74             other = top_stats[limit:]
75             if other:
76                 size = sum(stat.size for stat in other)
77                 logger.info(f"janitor: {len(other)} others: {size/1024:.1f} KiB")
78             total = sum(stat.size for stat in top_stats)
79             logger.info(f"janitor: Total allocated size: {total / 1024:.1f} KiB")
80         if now > gc_target:
81             logger.info("janitor: kicking off a manual gc operation now.")
82             gc.collect()
83             gc_target = now + 120.0
84         time.sleep(30.0)
85
86
87 def guess_page(command: str, page_chooser: chooser.chooser) -> str:
88     def normalize_page(page: str) -> str:
89         logger.debug(f"normalize_page input: {page}")
90         page = page.replace("(", " ")
91         page = page.replace("_", " ")
92         page = page.replace(")", " ")
93         page = page.replace(".html", "")
94         page = page.replace("CNNNews", "news")
95         page = page.replace("CNNTechnology", "technology")
96         page = page.replace("gocostco", "costco list")
97         page = page.replace("gohardware", "hardware list")
98         page = page.replace("gohouse", "house list honey do")
99         page = page.replace("gcal", "google calendar events")
100         page = page.replace("mynorthwest", "northwest news")
101         page = page.replace("myq", "myq garage door status")
102         page = page.replace("gomenu", "dinner menu")
103         page = page.replace("gmaps-seattle-unwrapped", "traffic")
104         page = page.replace("gomenu", "dinner menu")
105         page = page.replace("WSJNews", "news")
106         page = page.replace("telma", "telma cabin")
107         page = page.replace("WSJBusiness", "business news")
108         page = re.sub(r"[0-9]+", "", page)
109         logger.debug(f"normalize_page output: {page}")
110         return page
111
112     logger.info(f"No exact match for f{command}; trying to guess...")
113     best_page = None
114     best_score = None
115     for page in page_chooser.get_page_list():
116         npage = normalize_page(page)
117         score = SequenceMatcher(None, command, npage).ratio()
118         if best_score is None or score > best_score:
119             best_page = page
120             best_score = score
121     assert best_page is not None
122     logger.info(f"Best guess for f{command} => {best_page} (score = {best_score})")
123     return best_page
124
125
126 def process_command(
127     command: str, page_history: List[str], page_chooser
128 ) -> Optional[str]:
129     command = command.lower()
130     logger.info(f"Parsing verbal command: {command}")
131     page = None
132     if "hold" in command:
133         page = page_history[0]
134     elif "down" in command:
135         os.system(
136             'xdotool search --onlyvisible "chrom" windowactivate click --repeat 8 5'
137         )
138         return None
139     elif "up" in command:
140         os.system(
141             'xdotool search --onlyvisible "chrom" windowactivate click --repeat 8 4'
142         )
143         return None
144     elif "back" in command:
145         page = page_history[1]
146     elif "skip" in command:
147         while True:
148             (page, _) = page_chooser.choose_next_page()
149             if page == page_history[0]:
150                 logger.debug(f"chooser: {page} is the same as last time!  Try again.")
151             else:
152                 break
153     elif "internal" in command:
154         if "render" in command:
155             page = kiosk_constants.render_stats_pagename
156         else:
157             page = kiosk_constants.render_stats_pagename
158     elif "weather" in command:
159         if "telma" in command or "cabin" in command:
160             page = "weather-telma_3_10800.html"
161         elif "stevens" in command:
162             page = "weather-stevens_3_10800.html"
163         else:
164             page = "weather-home_3_10800.html"
165     elif "cabin" in command:
166         if "list" in command:
167             page = "Cabin-(gocabin)_2_3600.html"
168         else:
169             page = "hidden/cabin_driveway.html"
170     elif "news" in command or "headlines" in command:
171         page = "cnn-CNNNews_4_25900.html"
172     elif "clock" in command or "time" in command:
173         page = "clock_10_none.html"
174     elif "countdown" in command or "countdowns" in command:
175         page = "countdown_3_7200.html"
176     elif "costco" in command:
177         page = "Costco-(gocostco)_2_3600.html"
178     elif "calendar" in command or "events" in command:
179         page = "gcal_3_86400.html"
180     elif "countdown" in command or "countdowns" in command:
181         page = "countdown_3_7200.html"
182     elif "grocery" in command or "groceries" in command:
183         page = "Grocery-(gogrocery)_2_3600.html"
184     elif "hardware" in command:
185         page = "Hardware-(gohardware)_2_3600.html"
186     elif "garage" in command:
187         page = "myq_4_300.html"
188     elif "menu" in command:
189         page = "Menu-(gomenu)_2_3600.html"
190     elif "cron" in command or "health" in command:
191         page = "periodic-health_6_300.html"
192     elif "photo" in command or "picture" in command:
193         page = "photo_23_3600.html"
194     elif "quote" in command or "quotation" in command or "quotes" in command:
195         page = "quotes_4_10800.html"
196     elif "stevens" in command:
197         page = "stevens-conditions_1_86400.html"
198     elif "stock" in command or "stocks" in command:
199         page = "stock_3_86400.html"
200     elif "twitter" in command:
201         page = "twitter_10_3600.html"
202     elif "traffic" in command:
203         page = "gmaps-seattle-unwrapped_5_none.html"
204     elif "front" in command and "door" in command:
205         page = "hidden/frontdoor.html"
206     elif "driveway" in command:
207         page = "hidden/driveway.html"
208     elif "backyard" in command:
209         page = "hidden/backyard.html"
210     else:
211         page = guess_page(command, page_chooser)
212     assert page is not None
213     logger.info(f"Parsed to {page}")
214     return page
215
216
217 def thread_change_current(command_queue: Queue) -> None:
218     page_history = ["", ""]
219     swap_page_target = 0.0
220
221     def filter_news_during_dinnertime(page: str) -> bool:
222         now = datetime.now(tz=pytz.timezone("US/Pacific"))
223         is_dinnertime = now.hour >= 18 and now.hour <= 20
224         return not is_dinnertime or not (
225             "cnn" in page
226             or "news" in page
227             or "mynorthwest" in page
228             or "seattle" in page
229             or "wsj" in page
230         )
231
232     page_chooser = chooser.weighted_random_chooser_with_triggers(
233         trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
234     )
235     current_file = os.path.join(kiosk_constants.pages_dir, "current.shtml")
236     emergency_file = os.path.join(kiosk_constants.pages_dir, "reload_immediately.html")
237
238     # Main chooser loop
239     while True:
240         now = time.time()
241
242         # Check for a verbal command.
243         command = None
244         try:
245             command = command_queue.get(block=False)
246         except Exception:
247             command = None
248
249         if command is not None:
250             logger.info(
251                 f'chooser: We got a verbal command ("{command}"), parsing it...'
252             )
253             page = process_command(command, page_history, page_chooser)
254             if page:
255                 triggered = True
256
257         if not triggered:
258             while True:
259                 (page, triggered) = page_chooser.choose_next_page()
260                 if triggered:
261                     logger.info("chooser: A trigger is active...")
262                     break
263                 else:
264                     if page == page_history[0]:
265                         logger.debug(
266                             f"chooser: {page} is the same as last time! Try again."
267                         )
268                     else:
269                         break
270
271         if triggered:
272             if page != page_history[0] or (swap_page_target - now) < 10.0:
273                 logger.info(
274                     f"chooser: An emergency page reload to {page} is needed at this time."
275                 )
276                 swap_page_target = now + kiosk_constants.emergency_refresh_period_sec
277
278                 # Set current.shtml to the right page.
279                 try:
280                     with open(current_file, "w") as f:
281                         emit(
282                             f,
283                             page,
284                             override_refresh_sec=kiosk_constants.emergency_refresh_period_sec,
285                             command=command,
286                         )
287                     logger.debug(f"chooser: Wrote {current_file}.")
288                 except Exception as e:
289                     logger.exception(e)
290                     logger.error(
291                         f"chooser: Unexpected exception; assuming {page} doesn't exist?!"
292                     )
293                     continue
294
295                 # Also notify XMLHTTP clients that they need to refresh now.
296                 with open(emergency_file, "w") as f:
297                     f.write(f"Reload, suckers... you HAVE to see {page}!")
298                 logger.debug(f"chooser: Wrote {emergency_file}...")
299
300                 # Fix this hack... maybe read the webserver logs and see if it
301                 # actually was picked up?
302                 time.sleep(0.999)
303                 os.remove(emergency_file)
304                 logger.debug(f"chooser: ...and removed {emergency_file}.")
305
306         elif now >= swap_page_target:
307             assert page != page_history[0]
308             logger.info(f"chooser: Nominal choice of {page} as the next to show.")
309             swap_page_target = now + kiosk_constants.refresh_period_sec
310             try:
311                 with open(current_file, "w") as f:
312                     emit(f, page)
313                 logger.debug(f"chooser: Wrote {current_file}.")
314             except Exception as e:
315                 logger.exception(e)
316                 logger.error(
317                     f"chooser: Unexpected exception; assuming {page} doesn't exist?!"
318                 )
319                 continue
320         page_history.insert(0, page)
321         page_history = page_history[0:10]
322         time.sleep(0.5)
323
324
325 def emit(f, filename: str, *, override_refresh_sec: int = None, command: str = None):
326     if "unwrapped" not in filename:
327         logger.debug(f"Emitting {filename} wrapped.")
328         emit_wrapped(
329             f, filename, override_refresh_sec=override_refresh_sec, command=command
330         )
331     else:
332         logger.debug(f"Emitting {filename} raw.")
333         emit_raw(f, filename)
334
335
336 def emit_raw(f, filename: str):
337     f.write(f'<!--#include virtual="{filename}"-->')
338
339
340 def emit_wrapped(
341     f, filename: str, *, override_refresh_sec: int = None, command: str = None
342 ) -> None:
343     def pick_background_color() -> str:
344         now = datetime_utils.now_pacific()
345         city = astral.LocationInfo("Bellevue", "USA", "US/Pacific", 47.610, -122.201)
346         s = sun(city.observer, date=now, tzinfo=pytz.timezone("US/Pacific"))
347         sunrise_mod = datetime_utils.minute_number(
348             s["sunrise"].hour, s["sunrise"].minute
349         )
350         sunset_mod = datetime_utils.minute_number(s["sunset"].hour, s["sunset"].minute)
351         now_mod = datetime_utils.minute_number(now.hour, now.minute)
352         if now_mod < sunrise_mod or now_mod > (sunset_mod + 45):
353             return "E6B8B8"
354         elif now_mod < (sunrise_mod + 45) or now_mod > (sunset_mod + 120):
355             return "EECDCD"
356         else:
357             return "FFFFFF"
358
359     def get_refresh_period() -> float:
360         if override_refresh_sec is not None:
361             return float(override_refresh_sec * 1000.0)
362         now = datetime.now(tz=pytz.timezone("US/Pacific"))
363         if now.hour < 6:
364             return float(kiosk_constants.refresh_period_night_sec * 1000.0)
365         else:
366             return float(kiosk_constants.refresh_period_sec * 1000.0)
367
368     age = file_utils.describe_file_ctime(f"pages/{filename}")
369     bgcolor = pick_background_color()
370     if command is None:
371         pageid = filename
372     else:
373         pageid = f'"{command}" -> {filename}'
374
375     f.write(
376         """
377 <HEAD>
378   <TITLE>Kitchen Kiosk</TITLE>
379   <LINK rel="stylesheet" type="text/css" href="style.css">
380   <meta name="google" content="notranslate">
381   <SCRIPT TYPE="text/javascript">
382
383   // Zoom the 'contents' div to fit without scrollbars and then make
384   // it visible.
385   function zoomScreen() {
386     z = 285;
387     do {
388       document.getElementById("content").style.zoom = z+"%";
389       var body = document.body;
390       var html = document.documentElement;
391       var height = Math.max(body.scrollHeight,
392                             body.offsetHeight,
393                             html.clientHeight,
394                             html.scrollHeight,
395                             html.offsetHeight);
396       var windowHeight = window.innerHeight;
397       var width = Math.max(body.scrollWidth,
398                            body.offsetWidth,
399                            html.clientWidth,
400                            html.scrollWidth,
401                            html.offsetWidth);
402       var windowWidth = window.innerWidth;
403       var heightRatio = height / windowHeight;
404       var widthRatio = width / windowWidth;
405
406       if (heightRatio <= 1.0 && widthRatio <= 1.0) {
407         break;
408       }
409       z -= 4;
410     } while(z >= 70);
411     document.getElementById("content").style.visibility = "visible";
412   }
413
414   // Load IMG tags with DATA-SRC attributes late.
415   function lateLoadImages() {
416     var image = document.getElementsByTagName('img');
417     for (var i = 0; i < image.length; i++) {
418       if (image[i].getAttribute('DATA-SRC')) {
419         image[i].setAttribute('SRC', image[i].getAttribute('DATA-SRC'));
420       }
421     }
422   }
423 """
424     )
425     f.write(
426         """
427   // Operate the clock at the top of the page.
428   function runClock() {
429     var today = new Date();
430     var h = today.getHours();
431     var ampm = h >= 12 ? 'pm' : 'am';
432     h = h %% 12;
433     h = h ? h : 12; // the hour '0' should be '12'
434     var m = maybeAddZero(today.getMinutes());
435     var colon = ":";
436     if (today.getSeconds() %% 2 == 0) {
437       colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
438     }
439     document.getElementById("time").innerHTML = h + colon + m + ampm;
440     document.getElementById("date").innerHTML = today.toDateString();
441     var t = setTimeout(function(){runClock()}, 1000);
442   }
443 """
444         % bgcolor
445     )
446     f.write(
447         """
448   // Helper method for running the clock.
449   function maybeAddZero(x) {
450     return (x < 10) ? "0" + x : x;
451   }
452
453   // Do something on page load.
454   function addLoadEvent(func) {
455     var oldonload = window.onload;
456     if (typeof window.onload != 'function') {
457       window.onload = func;
458     } else {
459       window.onload = function() {
460         if (oldonload) {
461           oldonload();
462         }
463         func();
464       }
465     }
466   }
467
468   // Sleep thread helper.
469   const sleep = (milliseconds) => {
470     return new Promise(resolve => setTimeout(resolve, milliseconds))
471   }
472
473   var loadedDate = new Date();
474
475   addLoadEvent(zoomScreen);
476   addLoadEvent(runClock);
477   addLoadEvent(lateLoadImages);
478 """
479     )
480     f.write(
481         """
482   // Runs the countdown line at the bottom and is responsible for
483   // normal page reloads caused by the expiration of a timer.
484   (function countdown() {
485     setTimeout(
486       function() {
487         var now = new Date();
488         var deltaMs = now.getTime() - loadedDate.getTime();
489         var totalMs = %d;
490         var remainingMs = (totalMs - deltaMs);
491
492         if (remainingMs > 0) {
493           var hr = document.getElementById("countdown");
494           var width = (remainingMs / (totalMs - 5000)) * 100.0;
495           if (width <= 100) {
496             hr.style.visibility = "visible";
497             hr.style.width = " ".concat(width, "%%");
498             hr.style.backgroundColor = "maroon";
499           }
500         } else {
501           // Reload unconditionally after 22 sec.
502           window.location.reload(true);
503         }
504
505         // Brief sleep before doing it all over again.
506         sleep(50).then(() => {
507           countdown();
508         });
509       }, 50)
510   })();
511 """
512         % get_refresh_period()
513     )
514     f.write(
515         """
516   function check_reload() {
517     var xhr = new XMLHttpRequest();
518     xhr.open('GET',
519              '%s/reload_immediately.html');
520     xhr.onload =
521       function() {
522         if (xhr.status === 200) {
523           window.location.reload(true);
524         }
525       };
526     xhr.send();
527   }
528
529   // Periodically checks for emergency reload events.
530   setInterval(check_reload, 500);
531   </SCRIPT>
532 </HEAD>
533 """
534         % kiosk_constants.root_url
535     )
536     f.write(f'<BODY BGCOLOR="#{bgcolor}">')
537     f.write(
538         """
539     <TABLE style="height:100%; width:100%" BORDER=0>
540     <TR HEIGHT=30>
541         <TD ALIGN="left">
542             <DIV id="date">&nbsp;</DIV>
543         </TD>
544         <TD ALIGN="center"><FONT COLOR=#bbbbbb>
545             <DIV id="info"></DIV></FONT>
546         </TD>
547         <TD ALIGN="right">
548             <DIV id="time">&nbsp;</DIV>
549         </TD>
550     </TR>
551     <TR STYLE="vertical-align:top">
552         <TD COLSPAN=3>
553             <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
554               <!-- BEGIN main page contents. -->
555 """
556     )
557     f.write(f'<!--#include virtual="{filename}"-->')
558     f.write(
559         """
560             <!-- END main page contents. -->
561             </DIV>
562             <BR>
563             <DIV STYLE="position: absolute; top:1030px; width:99%">
564             <P ALIGN="right">
565 """
566     )
567     f.write(f"<FONT SIZE=2 COLOR=#bbbbbb>{pageid} @ {age} ago.</FONT>")
568     f.write(
569         """
570             </P>
571             <HR id="countdown" STYLE="width:0px;
572                                       text-align:left;
573                                       margin:0;
574                                       border:none;
575                                       border-width:0;
576                                       height:5px;
577                                       visibility:hidden;
578                                       background-color:#ffffff;">
579             </DIV>
580         </TD>
581     </TR>
582     </TABLE>
583 </BODY>"""
584     )
585
586
587 def renderer_update_internal_stats_page(
588     last_render: Dict[str, datetime],
589     render_counts: collections.Counter,
590     render_times: Dict[str, np.array],
591 ) -> None:
592     logger.info("renderer: Updating internal render statistics page.")
593     with file_writer.file_writer(kiosk_constants.render_stats_pagename) as f:
594         f.write(
595             """
596 <CENTER>
597 <TABLE BORDER=0 WIDTH=95%>
598     <TR>
599     <TH><B>Renderer Name</B></TH>
600     <TH><B>Last Run</B></TH>
601     <TH><B>Num Invocations</B></TH>
602     <TH><B>Render Latency</B></TH>
603     </TR>
604 """
605         )
606         for n, r in enumerate(renderer_catalog.get_renderers()):
607             if n % 2 == 0:
608                 style = 'style="margin: 0; padding: 0; background: #c6b0b0;"'
609             else:
610                 style = 'style="margin: 0; padding: 0; background: #eeeeee;"'
611             name = r.get_name()
612             last = last_render.get(name, None)
613             if last is None:
614                 last = "never"
615             else:
616                 last = last.strftime("%Y/%m/%d %I:%M:%S%P")
617             count = render_counts.get(name, 0)
618             latency = render_times.get(name, np.array([]))
619             p25 = p50 = p75 = p90 = p99 = "N/A"
620             try:
621                 p25 = np.percentile(latency, 25)
622                 p50 = np.percentile(latency, 50)
623                 p75 = np.percentile(latency, 75)
624                 p90 = np.percentile(latency, 90)
625                 p99 = np.percentile(latency, 99)
626                 f.write(
627                     f"""
628     <TR>
629     <TD {style}>{name}&nbsp;</TD>
630     <TD {style}>&nbsp;{last}&nbsp;</TD>
631     <TD {style}><CENTER>&nbsp;{count}&nbsp;</CENTER></TD>
632     <TD {style}>&nbsp;p25={p25:5.2f}, p50={p50:5.2f}, p75={p75:5.2f}, p90={p90:5.2f}, p99={p99:5.2f}</TD>
633     </TR>
634 """
635                 )
636             except IndexError:
637                 pass
638         f.write("</TABLE>")
639
640
641 def thread_invoke_renderers() -> None:
642     render_times: Dict[str, np.array] = {}
643     render_counts: collections.Counter = collections.Counter()
644     last_render: Dict[str, datetime] = {}
645
646     # Touch the internal render page now to signal that we're alive.
647     renderer_update_internal_stats_page(last_render, render_counts, render_times)
648
649     # Main renderer loop
650     while True:
651         logger.info("renderer: invoking all overdue renderers in catalog...")
652         for r in renderer_catalog.get_renderers():
653             name = r.get_name()
654             now = time.time()
655             logger.info(f"renderer: Invoking {name}'s render method.")
656             try:
657                 r.render()
658             except Exception as e:
659                 logger.exception(e)
660                 logger.error(
661                     f"renderer: Unexpected and unhandled exception ({e}) in {name}, swallowing it."
662                 )
663                 continue
664
665             # Increment the count of render operations per renderer.
666             render_counts[name] += 1
667
668             # Keep track of the last time we invoked each renderer.
669             last_render[name] = datetime_utils.now_pacific()
670
671             # Record how long each render operation takes and warn if very long.
672             delta = time.time() - now
673             times = render_times.get(name, np.array([]))
674             times = np.insert(times, 0, delta)
675             render_times[name] = times
676             if delta > 1.0:
677                 hdr = "renderer: "
678                 logger.warning(
679                     f"""
680 {hdr} Warning: {name}'s rendering took {delta:5.2f}s.
681 {hdr} FYI: {name}'s render times: p25={np.percentile(times, 25):5.2f}, p50={np.percentile(times, 50):5.2f}, p75={np.percentile(times, 75):5.2f}, p90={np.percentile(times, 90):5.2f}, p99={np.percentile(times, 99):5.2f}
682 """
683                 )
684
685         # Update a page about internal stats of renderers.
686         renderer_update_internal_stats_page(last_render, render_counts, render_times)
687         logger.info("renderer: having a little nap...")
688         time.sleep(kiosk_constants.render_period_sec)
689
690
691 @bootstrap.initialize
692 def main() -> None:
693     command_queue: Queue = Queue()
694     changer_thread: Optional[Thread] = None
695     renderer_thread: Optional[Thread] = None
696     janitor_thread: Optional[Thread] = None
697     hotword_thread: Optional[Thread] = None
698     while True:
699         if hotword_thread is None or not hotword_thread.is_alive():
700             if hotword_thread is None:
701                 logger.info("watchdog: Starting up the hotword detector thread...")
702             else:
703                 logger.warning(
704                     "watchdog: The hotword detector thread seems to have died; restarting it and hoping for the best."
705                 )
706             keyword_paths = [pvporcupine.KEYWORD_PATHS[x] for x in ["bumblebee"]]
707             sensitivities = [0.7] * len(keyword_paths)
708             listener = listen.HotwordListener(
709                 command_queue,
710                 keyword_paths,
711                 sensitivities,
712             )
713             hotword_thread = Thread(target=listener.listen_forever, args=())
714             hotword_thread.start()
715
716         if changer_thread is None or not changer_thread.is_alive():
717             if changer_thread is None:
718                 logger.info("watchdog: Starting up the current page changer thread...")
719             else:
720                 logger.warning(
721                     "watchdog: The current page changer thread seems to have died; restarting it and hoping for the best."
722                 )
723             changer_thread = Thread(target=thread_change_current, args=(command_queue,))
724             changer_thread.start()
725
726         if renderer_thread is None or not renderer_thread.is_alive():
727             if renderer_thread is None:
728                 logger.info("watchdog: Starting up the page renderer thread...")
729             else:
730                 logger.warning(
731                     "watchdog: The page renderer thread seems to have died; restarting it and hoping for the best."
732                 )
733             renderer_thread = Thread(target=thread_invoke_renderers, args=())
734             renderer_thread.start()
735
736         if janitor_thread is None or not janitor_thread.is_alive():
737             if janitor_thread is None:
738                 logger.info("watchdog: Starting up the memory janitor thread...")
739             else:
740                 logger.warning(
741                     "watchdog: The memory janitor thread seems to have died; restarting it and hoping for the best."
742                 )
743             janitor_thread = Thread(target=thread_janitor, args=())
744             janitor_thread.start()
745
746         # Have a little break and then check to make sure all threads are still alive.
747         logger.debug("watchdog: having a little nap.")
748         time.sleep(kiosk_constants.check_threads_period_sec)
749
750
751 if __name__ == "__main__":
752     main()