Skip to content
This repository has been archived by the owner on May 18, 2024. It is now read-only.

Commit

Permalink
Merge pull request #157 from falkyre/weather
Browse files Browse the repository at this point in the history
  • Loading branch information
riffnshred authored Dec 30, 2020
2 parents 03c1a54 + ca96954 commit 4ad4449
Show file tree
Hide file tree
Showing 19 changed files with 156 additions and 101 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
{
"python.pythonPath": "/usr/bin/python3"
}
Binary file modified nhl_setup
Binary file not shown.
2 changes: 1 addition & 1 deletion src/api/weather/nwsAlerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def getAlerts(self):
# urgency (Immediate, Expected, Future, Unknown)
# severity severity level(minor, moderate, severe, extreme)
#
if self.data.config.wx_alert_nws_show_expire:
if self.data.config.wxalert_nws_show_expire and _attributes['expires'] != None:
warn_date = _attributes['expires']
else:
warn_date = _attributes['effective']
Expand Down
4 changes: 2 additions & 2 deletions src/api/weather/owmWeather.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@

class owmWxWorker(object):
def __init__(self, data, scheduler):

self.data = data
self.weather_frequency = data.config.weather_update_freq
self.time_format = data.config.time_format
self.icons = get_icons("ecIcons_utf8.csv")
self.apikey = data.config.weather_owm_apikey
self.network_issues = False

self.owm = OWM(self.apikey)
self.owm_manager = self.owm.weather_manager()

Expand All @@ -24,7 +25,6 @@ def __init__(self, data, scheduler):
#Get initial obs
self.getWeather()


def getWeather(self):

if self.data.config.weather_units == "metric":
Expand Down
14 changes: 9 additions & 5 deletions src/api/weather/wxForecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@ def __init__(self, data, scheduler):

self.max_days = data.config.weather_forecast_days


if self.data.config.weather_data_feed.lower() == "owm":

self.owm = OWM(self.apikey)
self.owm_manager = self.owm.weather_manager()


# Get forecast for next day, every forecast_update hours

hour_update = '*/' + str(self.data.config.weather_forecast_update)
Expand Down Expand Up @@ -133,7 +130,14 @@ def getForecast(self):
debug.info("Refreshing OWM daily weather forecast")
#lat = self.data.latlng[0]
#lon = self.data.latlng[1]
one_call = self.owm_manager.one_call(lat=self.data.latlng[0],lon=self.data.latlng[1])
one_call = None
try:
one_call = self.owm_manager.one_call(lat=self.data.latlng[0],lon=self.data.latlng[1])
except Exception as e:
debug.error("Unable to get OWM data error:{0}".format(e))
self.data.forecast_updated = False
self.network_issues = True
return

index=1
forecast = []
Expand All @@ -149,7 +153,7 @@ def getForecast(self):
temp_high = one_call.forecast_daily[index].temperature('fahrenheit').get('max', None)
temp_low = one_call.forecast_daily[index].temperature('fahrenheit').get('min', None)

#Round high and low temps to two digitrs only (ie 25 and not 25.61)
#Round high and low temps to two digits only (ie 25 and not 25.61)
temp_hi = str(round(float(temp_high))) + self.data.wx_units[0]
temp_lo = str(round(float(temp_low))) + self.data.wx_units[0]

Expand Down
1 change: 0 additions & 1 deletion src/boards/boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

class Boards:
def __init__(self):
# self.standings_board = Standings(config, matrix)
pass

# Board handler for PushButton
Expand Down
2 changes: 1 addition & 1 deletion src/boards/christmas.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def xmas_today(self) :

debug.info("It's Christmas!")

while self.sleepEvent.is_set():
while not self.sleepEvent.is_set():

self.matrix.clear()

Expand Down
5 changes: 4 additions & 1 deletion src/boards/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ def __init__(self, data, matrix, sleepEvent ,duration=None):

display_time = 0
while display_time < self.duration and not self.sleepEvent.is_set():
self.time = datetime.datetime.now().strftime(self.time_format.replace(":", " "))
if self.data.config.clock_flash_seconds:
self.time = datetime.datetime.now().strftime(self.time_format.replace(":", " "))
else:
self.time = datetime.datetime.now().strftime(self.time_format)
self.meridiem = datetime.datetime.now().strftime("%P")
display_time += 1
self.draw_clock()
Expand Down
7 changes: 4 additions & 3 deletions src/boards/seriesticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
import nhl_api

class Seriesticker:
"""
TODO: Take out the Series object and create a list of instence from the refresh_playoff in Data instead. Call the data only once a day.
"""
def __init__(self, data, matrix, sleepEvent):
self.data = data
self.rotation_rate = 5
Expand All @@ -30,10 +33,8 @@ def render(self):
self.index = 0
self.num_series = len(self.allseries)

for s in self.allseries:
for series in self.allseries:
self.matrix.clear()
series = Series(s,self.data)

banner_text = "Stanley Cup"
color_banner_bg = (200,200,200)
color_banner_text = (0,0,0)
Expand Down
44 changes: 25 additions & 19 deletions src/boards/wxWeather.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,27 +115,33 @@ def WxDrawTemp(self,display_loop):
)

# Covert temp and apparent temp to floats to compare
temp_float = float(self.data.wx_current[3][:-1])
app_temp_float = float(self.data.wx_current[4][:-1])

if (temp_float > app_temp_float):
# apparent temperature is colder than temperature, show blue
self.matrix.draw_text_layout(
self.layout.temp_app_lo,
self.data.wx_current[4]
)
elif (temp_float < app_temp_float):
# apparent temperature is warmer than temperature, show red
if self.data.wx_current[3] == "N/A" or self.data.wx_current[4] == "N/A":
self.matrix.draw_text_layout(
self.layout.temp_app_hi,
self.data.wx_current[4]
)
self.layout.temp_app,
self.data.wx_current[4]
)
else:
# apparent temperature is colder than temperature, show green, same as temp
self.matrix.draw_text_layout(
self.layout.temp_app,
self.data.wx_current[4]
)
temp_float = float(self.data.wx_current[3][:-1])
app_temp_float = float(self.data.wx_current[4][:-1])

if (temp_float > app_temp_float):
# apparent temperature is colder than temperature, show blue
self.matrix.draw_text_layout(
self.layout.temp_app_lo,
self.data.wx_current[4]
)
elif (temp_float < app_temp_float):
# apparent temperature is warmer than temperature, show red
self.matrix.draw_text_layout(
self.layout.temp_app_hi,
self.data.wx_current[4]
)
else:
# apparent temperature is colder than temperature, show green, same as temp
self.matrix.draw_text_layout(
self.layout.temp_app,
self.data.wx_current[4]
)

self.matrix.render()

Expand Down
50 changes: 18 additions & 32 deletions src/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
single one.
"""


from datetime import datetime, timedelta
from time import sleep
import debug
import nhl_api
from api.covid19.data import Data as covid19_data
from data.playoffs import Series
from data.status import Status
from utils import get_lat_lng
import data.refresh

NETWORK_RETRY_SLEEP_TIME = 0.5

Expand Down Expand Up @@ -209,20 +210,9 @@ def _is_new_day(self):
# Today's date
self.today = self.date()

# Get the status info from the API
self.get_status()

# Get the teams info
self.teams = self.get_teams()

# Get favorite team's id
self.pref_teams = self.get_pref_teams_id()

# Reset flag
self.all_pref_games_final = False

# Reset and refresh Data
self.refresh_data()
return True
else:
debug.info("It is not a new day")
Expand Down Expand Up @@ -324,7 +314,6 @@ def get_status(self):
self.status = []
sleep(NETWORK_RETRY_SLEEP_TIME)


#
# Main game event data

Expand Down Expand Up @@ -435,14 +424,15 @@ def refresh_playoff(self):
TODO:
Add a refresh function to the Series object instead and trigger a refresh only at specific time in the renderer.(End of a game, new day)
"""
print("hello")
attempts_remaining = 5
while attempts_remaining > 0:
try:
# Get the plaoffs data from the nhl api
self.playoffs = nhl_api.playoff(self.status.season_id)
# Check if there is any rounds avaialable and grab the most recent one available.
if self.playoffs.rounds:
self.current_round = self.playoffs.rounds[str(self.playoffs.default_round)]
self.current_round = self.playoffs.rounds[str(2)]
self.current_round_name = self.current_round.names.name
if self.current_round_name == "Stanley Cup Qualifier":
self.current_round_name = "Qualifier"
Expand All @@ -452,21 +442,29 @@ def refresh_playoff(self):
debug.info("defaultround number is : {}".format(self.playoffs.default_round))

try:
self.series = []

# Grab the series of the current round of playoff.
self.series = self.current_round.series
self.series_list = self.current_round.series

# Check if prefered team are part of the current round of playoff
self.pref_series = prioritize_pref_series(filter_list_of_series(self.series, self.pref_teams), self.pref_teams)
self.pref_series = prioritize_pref_series(filter_list_of_series(self.series_list, self.pref_teams), self.pref_teams)

# If the user as set to show his favorite teams in the seriesticker
if self.config.seriesticker_preferred_teams_only and self.pref_series:
self.series = self.pref_series
self.series_list = self.pref_series

for s in self.series_list:
print(s)
self.series.append(Series(s,self))

self.isPlayoff = True
print(self.isPlayoff)
except AttributeError:
debug.error("The {} Season playoff has not started yet or is unavailable".format(self.playoffs.season))

self.isPlayoff = False
break

self.isPlayoff = True
break

except ValueError as error_message:
Expand Down Expand Up @@ -506,11 +504,7 @@ def is_nhl_offday(self):
return True

def refresh_data(self):
"""
This method is used when the software move to the next day or . It reset all the main variables
and re-initialize the overall data.
:return:
"""

debug.log("refresing data")
# Flag to determine when to refresh data
self.needs_refresh = True
Expand All @@ -521,13 +515,5 @@ def refresh_data(self):
# Parse today's date and see if we should use today or yesterday
self.refresh_current_date()

# Update team's data
self.get_teams_info()

# Update games for today
self.refresh_games()

# Update standings
self.refresh_standings()


19 changes: 19 additions & 0 deletions src/data/refresh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# NHL Data refresh module.

def daily(data):
print('refreshing data')
# Update team's data
data.get_teams_info()

# Get the teams info
data.teams = data.get_teams()

# Get favorite team's id
data.pref_teams = data.get_pref_teams_id()

# Update standings
data.refresh_standings()

# Fetch the playoff data
data.refresh_playoff()

22 changes: 14 additions & 8 deletions src/data/scoreboard_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ class ScoreboardConfig:
def __init__(self, filename_base, args, size):
json = self.__get_config(filename_base)

self.testing_mode = False
self.testScChampions = False

# Misc config options
self.debug = json["debug"]
self.loglevel = json["loglevel"]
Expand Down Expand Up @@ -89,7 +92,7 @@ def __init__(self, filename_base, args, size):
self.wxalert_alert_feed = json["boards"]["wxalert"]["alert_feed"]
#Allow the weather thread to interrupt the current flow of the display loop and show an alert if it shows up
#Similar to how a pushbutton interrupts the flow
self.wxalert_show_alerts = json["boards"]["wxalert"]["show_alerts"]
self.wxalert_show_alerts = json["boards"]["wxalert"]["show_alerts"]
#Show expire time instead of effective time of NWS alerts
self.wxalert_nws_show_expire = json["boards"]["wxalert"]["nws_show_expire"]
# Display on top and bottom bar the severity (for US) and type
Expand Down Expand Up @@ -159,8 +162,10 @@ def __init__(self, filename_base, args, size):

if args.testScChampions != None:
self.testScChampions = args.testScChampions
else:
self.testScChampions = False

if args.testing_mode :
self.testing_mode = True


def read_json(self, filename):
# Find and return a json file
Expand Down Expand Up @@ -188,21 +193,22 @@ def __get_config(self, base_filename, error=None):
else:
debug.error("Invalid {} config file. Make sure {} exists in config/".format(base_filename, base_filename))
sys.exit(1)



if base_filename == "config":
# Validate against the config.json
debug.info("Now validating config.json.....")
debug.error("INFO: Validating config.json.....")
conffile = "config/config.json"
schemafile = "config/config.schema.json"

confpath = get_file(conffile)
schemapath = get_file(schemafile)
(valid,msg) = validateConf(confpath,schemapath)
if valid:
debug.info("config.json passes validation")
debug.error("INFO: config.json passes validation")
else:
debug.error("config.json fails validation: error: [{0}]".format(msg))
debug.error("Rerun the nhl_setup app to create a valid config.json")
debug.warning("WARN: config.json fails validation: error: [{0}]".format(msg))
debug.warning("WARN: Rerun the nhl_setup app to create a valid config.json")
sys.exit(1)

return reference_config
Expand Down
2 changes: 1 addition & 1 deletion src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def run():
#
if commandArgs.updatecheck:
data.UpdateRepo = commandArgs.updaterepo
checkupdate = UpdateChecker(data,scheduler)
checkupdate = UpdateChecker(data,scheduler,commandArgs.ghtoken)

if data.config.dimmer_enabled:
dimmer = Dimmer(data, matrix,scheduler)
Expand Down
Loading

0 comments on commit 4ad4449

Please sign in to comment.