Logging is a good thing.
[kiosk.git] / stevens_renderer.py
index bba06030b90e7924327f5238ebc8bf0f3e2957be..bf97785256933beb350d84d9ee47b87a59ca8ec2 100644 (file)
 #!/usr/bin/env python3
 
-import http.client
-from typing import List, Dict
-import xml.etree.ElementTree as ET
+import json
+import logging
+import requests
+from typing import Dict
 
-import renderer
 import file_writer
+import renderer
+
+
+logger = logging.getLogger(__file__)
+
 
+class stevens_renderer(renderer.abstaining_renderer):
+    URL = 'https://wsdot.com/Travel/Real-time/Service/api/MountainPass/Details/10'
 
-class stevens_pass_conditions_renderer(renderer.debuggable_abstaining_renderer):
-    """Renders a page about Stevens Pass conditions."""
-
-    def __init__(
-        self, name_to_timeout_dict: Dict[str, int], feed_site: str, feed_uris: List[str]
-    ) -> None:
-        super(stevens_pass_conditions_renderer, self).__init__(
-            name_to_timeout_dict, False
-        )
-        self.feed_site = feed_site
-        self.feed_uris = feed_uris
-
-    def debug_prefix(self) -> str:
-        return "stevens"
-
-    def periodic_render(self, key: str) -> bool:
-        with file_writer.file_writer("stevens-conditions_1_86400.html") as f:
-            for uri in self.feed_uris:
-                self.conn = http.client.HTTPSConnection(self.feed_site)
-                self.conn.request("GET", uri, None, {"Accept-Charset": "utf-8"})
-                response = self.conn.getresponse()
-                if response.status == 200:
-                    raw = response.read()
-                    rss = ET.fromstring(raw)
-                    channel = rss[0]
-                    for item in channel.getchildren():
-                        if item.tag == "title":
-                            f.write(f"<h1>{item.text}</h1><hr>")
-                            f.write(
-                                '<IMG WIDTH=512 ALIGN=RIGHT HEIGHT=382 SRC="https://images.wsdot.wa.gov/nc/002vc06430.jpg?t=637059938785646824" style="padding:8px;">'
-                            )
-                        elif item.tag == "item":
-                            for x in item.getchildren():
-                                if x.tag == "description":
-                                    text = x.text
-                                    if text is not None:
-                                        text = text.replace(
-                                            "<strong>Stevens Pass US2</strong><br/>", ""
-                                        )
-                                        text = text.replace("<br/><br/>", "<BR>")
-                                        text = text.replace(
-                                            "<strong>Elevation Meters:</strong>1238<BR>", ""
-                                        )
-                                    else:
-                                        text = ""
-                                    f.write(f"<P>\n{text}\n")
-                    return True
+    def __init__(self, name_to_timeout_dict: Dict[str, int]) -> None:
+        super().__init__(name_to_timeout_dict)
+
+    def render_conditions(mp: Dict[str, str], conditions: Dict[str, str]) -> str:
+        ret = f'''
+<TABLE>
+<TR>
+  <TD WIDTH="150"><FONT SIZE=+2><B>Temp:</B></FONT></TD>
+  <TD><FONT SIZE=+2>{conditions['temperature']}&deg;{conditions['temperatureUnit'][0]}</FONT></TD>
+</TR>
+<TR>
+  <TD><FONT SIZE=+2><B>Weather:</B></FONT></TD>
+  <TD><FONT SIZE=+2>{conditions['weather']}</FONT></TD>
+</TR>
+<TR>
+  <TD><FONT SIZE=+2><B>Roadway:</B></FONT></TD>
+  <TD><FONT SIZE=+2>{conditions['roadCondition']}</FONT></TD>
+</TR>'''
+        if 'restrictionOne' in conditions and 'restrictionTwo' in conditions:
+            ret += '''
+<TR>
+  <TD><FONT SIZE=+2><B>Restrictions:</B></FONT></TD>
+  <TD><FONT SIZE=+2>'''
+            count = 0
+            msg = conditions['restrictionOne'].get('publicPage', 'no restrictions')
+            if msg.lower() != 'no restrictions':
+                count += 1
+            msg = conditions['restrictionTwo'].get('publicPage', 'no restrictions')
+            if msg.lower() != 'no restrictions':
+                count += 1
+            if count == 2:
+                ret += f'''
+    <U>{conditions['restrictionOne']['travelDirectionName']}:</U>
+    {conditions['restrictionOne']['publicPage']} <BR>
+    <U>{conditions['restrictionTwo']['travelDirectionName']}:</U>
+    {conditions['restrictionTwo']['publicPage']}'''
+            elif count == 1:
+                msg = conditions['restrictionOne'].get('publicPage', 'no restrictions')
+                if msg.lower() != 'no restrictions':
+                    ret += f'''
+    <U>{conditions['restrictionOne']['travelDirectionName']}:</U>
+    {conditions['restrictionOne']['publicPage']}<BR>'''
+                else:
+                    ret += f'''
+    <U>{conditions['restrictionTwo']['travelDirectionName']}:</U>
+    {conditions['restrictionTwo']['publicPage']}<BR>'''
+            else:
+                ret += '''None.<BR>'''
+        ret += '</FONT></TD></TR></TABLE>'
+        return ret
+
+    def render_forecast(forecasts: Dict[str, str]) -> str:
+        ret = '<TABLE>'
+        fc = forecasts['forecast']['forecastData']
+        for n, f in enumerate(fc):
+            color = ''
+            if n % 2 == 0:
+                color = ' BGCOLOR="#dfefff"'
+            ret += f'''
+<TR>
+  <TD WIDTH="150" valign="top" {color}><B>{f['periodText']}</B></TD>
+  <TD{color}>{f['forecastText']}</TD>
+</TR>'''
+        ret += '</TABLE>'
+        return ret
+
+    def render_image(cameras: Dict[str, str]) -> str:
+        for camera in cameras:
+            if camera['cameraId'] == 8063:
+                return f'''
+<CENTER>
+  <A HREF='https://wsdot.com/travel/real-time/mountainpasses/Stevens'>
+    <IMG SRC={camera['cameraUrl']} WIDTH={camera['width'] * 1.75}>
+  </A>
+  <BR>
+  <I>{camera['cameraLabel']} ({camera['direction']})</I>
+</CENTER>'''
+        return ''
+
+    def periodic_render(self, unused: str) -> bool:
+        page = requests.get(stevens_renderer.URL)
+        if page.status_code == 200:
+            contents = json.loads(page.content)
+            mp = contents['mountainPass']
+            conditions = contents['condition']
+            cameras = contents['cameras']
+            forecasts = contents['stationForecasts'][0]
+            with file_writer.file_writer('stevens-conditions_5_3000.html') as f:
+                f.write(f'''
+<H1>Stevens Pass Conditions:</H1>
+<HR>
+<TABLE WIDTH=90%>
+<TR>
+  <TD>
+    {stevens_renderer.render_conditions(mp, conditions)}
+  </TD>
+  <TD>
+    {stevens_renderer.render_image(cameras)}
+  </TD>
+</TR>
+<TR>
+  <TD COLSPAN=2>
+    {stevens_renderer.render_forecast(forecasts)}
+  </TD>
+</TR>
+</TABLE>''')
+            return True
         return False
+
+# Test:
+#test = stevens_renderer({"Test", 123})
+#test.periodic_render("Test")