3 from datetime import datetime
9 from threading import Thread
13 from typing import Optional, List
14 from queue import Queue
16 import astral # type: ignore
17 from astral.sun import sun # type: ignore
23 import kiosk_constants as constants
24 import renderer_catalog
29 import trigger_catalog
32 def thread_janitor() -> None:
34 tracemalloc_target = 0.0
40 if now > tracemalloc_target:
41 tracemalloc_target = now + 30.0
42 snapshot = tracemalloc.take_snapshot()
43 snapshot = snapshot.filter_traces((
44 tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
45 tracemalloc.Filter(False, "<unknown>"),
49 top_stats = snapshot.statistics(key_type)
50 print("janitor: Top %s lines" % limit)
51 for index, stat in enumerate(top_stats[:limit], 1):
52 frame = stat.traceback[0]
53 # replace "/path/to/module/file.py" with "module/file.py"
54 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
55 print("janitor: #%s: %s:%s: %.1f KiB"
56 % (index, filename, frame.lineno, stat.size / 1024))
57 line = linecache.getline(frame.filename, frame.lineno).strip()
59 print('janitor: %s' % line)
61 other = top_stats[limit:]
63 size = sum(stat.size for stat in other)
64 print("janitor: %s other: %.1f KiB" % (len(other), size / 1024))
65 total = sum(stat.size for stat in top_stats)
66 print("janitor: Total allocated size: %.1f KiB" % (total / 1024))
68 print("janitor: Running gc operation")
69 gc_target = now + 60.0
74 def guess_page(command: str, page_chooser: chooser.chooser) -> str:
77 for page in page_chooser.get_page_list():
78 page = page.replace('(', ' ')
79 page = page.replace('_', ' ')
80 page = page.replace(')', ' ')
81 page = page.replace('.html', '')
82 page = page.replace('CNNNews', 'news')
83 page = page.replace('CNNTechnology', 'technology')
84 page = page.replace('gocostco', 'costco list')
85 page = page.replace('gohardware', 'hardware list')
86 page = page.replace('gohouse', 'house list honey do')
87 page = page.replace('gcal', 'google calendar events')
88 page = page.replace('mynorthwest', 'northwest news')
89 page = page.replace('myq', 'myq garage door status')
90 page = page.replace('gomenu', 'dinner menu')
91 page = page.replace('wsdot', 'traffic')
92 page = page.replace('gomenu', 'dinner menu')
93 page = page.replace('WSJNews', 'news')
94 page = page.replace('telma', 'telma cabin')
95 page = page.replace('WSJBusiness', 'business news')
96 page = re.sub(r'[0-9]+', '', page)
97 score = SequenceMatcher(None, command, page).ratio()
98 if best_score is None or score > best_score:
100 assert best_page is not None
104 def process_command(command: str, page_history: List[str]) -> str:
106 if 'hold' in command:
107 page = page_history[0]
108 elif 'back' in command:
109 page = page_history[1]
110 elif 'skip' in command:
112 (page, _) = page_chooser.choose_next_page()
113 if page != page_history[0]:
115 elif 'weather' in command:
116 if 'telma' in command or 'cabin' in command:
117 page = 'weather-telma_3_10800.html'
118 elif 'stevens' in command:
119 page = 'weather-stevens_3_10800.html'
121 page = 'weather-home_3_10800.html'
122 elif 'cabin' in command:
123 if 'list' in command:
124 page = 'Cabin-(gocabin)_2_3600.html'
126 page = 'hidden/cabin_driveway.html'
127 elif 'news' in command or 'headlines' in command:
128 page = 'cnn-CNNNews_4_25900.html'
129 elif 'clock' in command or 'time' in command:
130 page = 'clock_10_none.html'
131 elif 'countdown' in command or 'countdowns' in command:
132 page = 'countdown_3_7200.html'
133 elif 'costco' in command:
134 page = 'Costco-(gocostco)_2_3600.html'
135 elif 'calendar' in command or 'events' in command:
136 page = 'gcal_3_86400.html'
137 elif 'countdown' in command or 'countdowns' in command:
138 page = 'countdown_3_7200.html'
139 elif 'grocery' in command or 'groceries' in command:
140 page = 'Grocery-(gogrocery)_2_3600.html'
141 elif 'hardware' in command:
142 page = 'Hardware-(gohardware)_2_3600.html'
143 elif 'garage' in command:
144 page = 'myq_4_300.html'
145 elif 'menu' in command:
146 page = 'Menu-(gomenu)_2_3600.html'
147 elif 'cron' in command or 'health' in command:
148 page = 'periodic-health_6_300.html'
149 elif 'photo' in command or 'picture' in command:
150 page = 'photo_23_3600.html'
151 elif 'quote' in command or 'quotation' in command or 'quotes' in command:
152 page = 'quotes_4_10800.html'
153 elif 'stevens' in command:
154 page = 'stevens-conditions_1_86400.html'
155 elif 'stock' in command or 'stocks' in command:
156 page = 'stock_3_86400.html'
157 elif 'twitter' in command:
158 page = 'twitter_10_3600.html'
159 elif 'traffic' in command:
160 page = 'wsdot-bridges_3_none.html'
161 elif 'front' in command and 'door' in command:
162 page = 'hidden/frontdoor.html'
163 elif 'driveway' in command:
164 page = 'hidden/driveway.html'
165 elif 'backyard' in command:
166 page = 'hidden/backyard.html'
168 page = guess_page(command, page_chooser)
169 assert page is not None
173 def thread_change_current(command_queue: Queue) -> None:
174 page_history = [ "", "" ]
175 swap_page_target = 0.0
177 def filter_news_during_dinnertime(page: str) -> bool:
179 is_dinnertime = now.hour >= 17 and now.hour <= 20
180 print(f"is dinnertime = {is_dinnertime}")
181 print(f'page = {page}')
182 return not is_dinnertime or not (
185 or "mynorthwest" in page
187 or "stranger" in page
191 page_chooser = chooser.weighted_random_chooser_with_triggers(
192 trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
198 # Check for a verbal command.
201 command = command_queue.get(block=False)
205 if command is not None:
207 page = process_command(command, page_history)
209 # Else pick a page randomly.
212 (page, triggered) = page_chooser.choose_next_page()
213 if triggered or page != page_history[0]:
217 print("chooser[%s] - WE ARE TRIGGERED." % datetime_utils.timestamp())
218 if page != page_history[0] or (swap_page_target - now < 10.0):
220 "chooser[%s] - EMERGENCY PAGE %s LOAD NEEDED"
221 % (datetime_utils.timestamp(), page)
224 with open(os.path.join(constants.pages_dir, "current.shtml"), "w") as f:
225 emit_wrapped(f, page, override_refresh_sec = 40, command = command)
226 page_history.insert(0, page)
227 page_history = page_history[0:10]
228 swap_page_target = now + 40
230 print("chooser[%s] - page does not exist?!" % (datetime_utils.timestamp()))
233 # Also notify XMLHTTP clients that they need to refresh now.
234 path = os.path.join(constants.pages_dir, "reload_immediately.html")
235 with open(path, "w") as f:
236 f.write("Reload, suckers!")
238 # Fix this hack... maybe read the webserver logs and see if it
239 # actually was picked up?
243 elif now >= swap_page_target:
244 assert page != page_history[0]
245 print("chooser[%s] - nominal choice of %s" % (datetime_utils.timestamp(), page))
247 with open(os.path.join(constants.pages_dir, "current.shtml"), "w") as f:
248 emit_wrapped(f, page)
249 page_history.insert(0, page)
250 page_history = page_history[0:10]
251 swap_page_target = now + constants.refresh_period_sec
253 print("chooser[%s] - page does not exist?!" % (datetime_utils.timestamp()))
261 override_refresh_sec: int = None,
262 command: str = None) -> None:
263 def pick_background_color() -> str:
264 now = datetime.now(tz=pytz.timezone("US/Pacific"))
265 city = astral.LocationInfo(
266 "Bellevue", "USA", "US/Pacific", 47.610, -122.201
268 s = sun(city.observer, date=now, tzinfo=pytz.timezone("US/Pacific"))
269 sunrise_mod = datetime_utils.minute_number(s["sunrise"].hour, s["sunrise"].minute)
270 sunset_mod = datetime_utils.minute_number(s["sunset"].hour, s["sunset"].minute)
271 now_mod = datetime_utils.minute_number(now.hour, now.minute)
272 if now_mod < sunrise_mod or now_mod > (sunset_mod + 45):
274 elif now_mod < (sunrise_mod + 45) or now_mod > (sunset_mod + 120):
279 def get_refresh_period() -> float:
280 if override_refresh_sec is not None:
281 return float(override_refresh_sec * 1000.0)
284 return float(constants.refresh_period_night_sec * 1000.0)
286 return float(constants.refresh_period_sec * 1000.0)
288 age = file_utils.describe_file_ctime(f"pages/{filename}")
289 bgcolor = pick_background_color()
293 pageid = f'"{command}" -> {filename}'
298 <TITLE>Kitchen Kiosk</TITLE>
299 <LINK rel="stylesheet" type="text/css" href="style.css">
300 <SCRIPT TYPE="text/javascript">
302 // Zoom the 'contents' div to fit without scrollbars and then make
304 function zoomScreen() {
307 document.getElementById("content").style.zoom = z+"%%";
308 var body = document.body;
309 var html = document.documentElement;
310 var height = Math.max(body.scrollHeight,
315 var windowHeight = window.innerHeight;
316 var width = Math.max(body.scrollWidth,
321 var windowWidth = window.innerWidth;
322 var heightRatio = height / windowHeight;
323 var widthRatio = width / windowWidth;
325 if (heightRatio <= 1.0 && widthRatio <= 1.0) {
330 document.getElementById("content").style.visibility = "visible";
333 // Load IMG tags with DATA-SRC attributes late.
334 function lateLoadImages() {
335 var image = document.getElementsByTagName('img');
336 for (var i = 0; i < image.length; i++) {
337 if (image[i].getAttribute('DATA-SRC')) {
338 image[i].setAttribute('SRC', image[i].getAttribute('DATA-SRC'));
343 // Operate the clock at the top of the page.
344 function runClock() {
345 var today = new Date();
346 var h = today.getHours();
347 var ampm = h >= 12 ? 'pm' : 'am';
349 h = h ? h : 12; // the hour '0' should be '12'
350 var m = maybeAddZero(today.getMinutes());
352 if (today.getSeconds() %% 2 == 0) {
353 colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
355 document.getElementById("time").innerHTML = h + colon + m + ampm;
356 document.getElementById("date").innerHTML = today.toDateString();
357 var t = setTimeout(function(){runClock()}, 1000);
360 // Helper method for running the clock.
361 function maybeAddZero(x) {
362 return (x < 10) ? "0" + x : x;
365 // Do something on page load.
366 function addLoadEvent(func) {
367 var oldonload = window.onload;
368 if (typeof window.onload != 'function') {
369 window.onload = func;
371 window.onload = function() {
380 // Sleep thread helper.
381 const sleep = (milliseconds) => {
382 return new Promise(resolve => setTimeout(resolve, milliseconds))
385 var loadedDate = new Date();
387 addLoadEvent(zoomScreen);
388 addLoadEvent(runClock);
389 addLoadEvent(lateLoadImages);
391 // Runs the countdown line at the bottom and is responsible for
392 // normal page reloads caused by the expiration of a timer.
393 (function countdown() {
396 var now = new Date();
397 var deltaMs = now.getTime() - loadedDate.getTime();
399 var remainingMs = (totalMs - deltaMs);
401 if (remainingMs > 0) {
402 var hr = document.getElementById("countdown");
403 var width = (remainingMs / (totalMs - 5000)) * 100.0;
405 hr.style.visibility = "visible";
406 hr.style.width = " ".concat(width, "%%");
407 hr.style.backgroundColor = "maroon";
410 // Reload unconditionally after 22 sec.
411 window.location.reload();
414 // Brief sleep before doing it all over again.
415 sleep(50).then(() => {
421 // Periodically checks for emergency reload events.
425 var xhr = new XMLHttpRequest();
427 'http://%s/kiosk/pages/reload_immediately.html');
430 if (xhr.status === 200) {
431 window.location.reload();
433 sleep(500).then(() => {
444 <TABLE style="height:100%%; width:100%%" BORDER=0>
447 <DIV id="date"> </DIV>
449 <TD ALIGN="center"><FONT COLOR=#bbbbbb>
450 <DIV id="info"></DIV></FONT>
453 <DIV id="time"> </DIV>
456 <TR STYLE="vertical-align:top">
458 <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
459 <!-- BEGIN main page contents. -->
460 <!--#include virtual=\"%s\"-->
461 <!-- END main page contents. -->
464 <DIV STYLE="position: absolute; top:1030px; width:99%%">
466 <FONT SIZE=2 COLOR=#bbbbbb>%s @ %s ago.</FONT>
468 <HR id="countdown" STYLE="width:0px;
475 background-color:#ffffff;">
483 get_refresh_period(),
493 def thread_invoke_renderers() -> None:
495 print(f"renderer[{datetime_utils.timestamp()}]: invoking all renderers in catalog...")
496 for r in renderer_catalog.get_renderers():
500 except Exception as e:
501 traceback.print_exc(file=sys.stdout)
503 f"renderer[{datetime_utils.timestamp()}] unknown exception ({e}) in {r.get_name()}, swallowing it."
505 delta = time.time() - now
508 f"renderer[{datetime_utils.timestamp()}]: Warning: {r.get_name()}'s rendering took {delta:5.2f}s."
511 f"renderer[{datetime_utils.timestamp()}]: thread having a little break for {constants.render_period_sec}s..."
513 time.sleep(constants.render_period_sec)
516 if __name__ == "__main__":
517 logging.basicConfig()
518 command_queue: Queue = Queue()
519 changer_thread: Optional[Thread] = None
520 renderer_thread: Optional[Thread] = None
521 janitor_thread: Optional[Thread] = None
522 hotword_thread: Optional[Thread] = None
524 if hotword_thread is None or not hotword_thread.is_alive():
525 keyword_paths = [pvporcupine.KEYWORD_PATHS[x] for x in ["bumblebee"]]
526 sensitivities = [0.7] * len(keyword_paths)
527 listener = listen.HotwordListener(
532 hotword_thread = Thread(target=listener.listen_forever, args=())
533 hotword_thread.start()
534 if changer_thread is None or not changer_thread.is_alive():
536 f"MAIN[{datetime_utils.timestamp()}] - (Re?)initializing chooser thread... (wtf?!)"
538 changer_thread = Thread(target=thread_change_current, args=(command_queue,))
539 changer_thread.start()
540 if renderer_thread is None or not renderer_thread.is_alive():
542 f"MAIN[{datetime_utils.timestamp()}] - (Re?)initializing render thread... (wtf?!)"
544 renderer_thread = Thread(target=thread_invoke_renderers, args=())
545 renderer_thread.start()
546 if janitor_thread is None or not janitor_thread.is_alive():
548 f"MAIN[{datetime_utils.timestamp()}] - (Re?)initializing janitor thread... (wtf?!)"
550 janitor_thread = Thread(target=thread_janitor, args=())
551 janitor_thread.start()