Skip to content

Commit e202825

Browse files
authored
Merge pull request #54 from TheFinalJoke/dev
Push for Tag 0.4.0
2 parents 087b9de + b03d054 commit e202825

File tree

14 files changed

+227
-107
lines changed

14 files changed

+227
-107
lines changed

.vscode/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
{
22
"python.pythonPath": "/bin/python3",
3-
"workbench.colorTheme": "Atom One Dark"
3+
"workbench.colorTheme": "One Dark Pro"
44
}

lib/config/ohmyoled.conf

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,60 @@
11
[basic]
2+
testing = False
23
# Log Level for Python
34
# Critcal = 50
45
# Error = 40
56
# Warning = 30
67
# Info = 20
78
# Debug = 10
8-
loglevel = 10
9+
loglevel = 20
910
# Tokens will have to be Supported used with Approriate Modules
1011
#### Not Supported Yet #####
11-
# sport_token = 'SPORT_TOKEN'
12+
# sport_token =
1213
##############################
1314
# Stock Token based in FINN TOKEN https://finnhub.io/docs/api/introduction
14-
# stock_api_token = YOUR_FINN_TOKEN
15+
#stock_api_token =
1516

1617
# Open Weather Token in https://openweathermap.org/
17-
open_weather_token = 80ce462129470ef2f5d55e6f65d32eef
18+
# open_weather_token =
1819

1920
[matrix]
2021
chain_length = 1
2122
parallel = 1
2223
# Brightness from 0-100
23-
brightness = 60
24+
brightness = 20
2425
oled_slowdown = 3
2526

26-
[weather]
27+
[time]
2728
Run=True
29+
color = (255,255,255)
30+
31+
[weather]
32+
Run=False
2833
# Build the city as Dallas, US, For more accurate data, use zipcode
2934
current_location=True
3035
#city =
31-
zipcode =
36+
# zipcode =
3237
# Format
3338
# The Units, The options are standard, metric, imperial
3439
format = imperial
3540

3641
[stock]
3742
Run=False
38-
39-
# symbol=
40-
41-
# Runs Quote data for stocks
42-
# quote=True
43-
44-
# Historical and days need
45-
# historical=True
46-
# days_ago=30
43+
symbol=fb
4744

4845
##### Sports Not Supported it #####
49-
# [sport]
50-
# Run=False
46+
[sport]
47+
Run=False
5148
# football
5249
# baseball
5350
# hockey
5451
# basketball
5552
# formula 1
56-
# sport=baseball
53+
sport=baseball
5754
# For Team IDs Baseball https://dashboard.api-football.com/baseball/ids/teams
5855
# For Team IDs Basketball https://dashboard.api-football.com/basketball/ids/teams/USA
5956
# Only Support USA
60-
# team_id = 6
57+
team_id = 6
6158
# optional Will pull all data for all unless specified
6259

6360
# Baseball

lib/run.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
logger = logging.getLogger(__name__)
1717
logger.addHandler(sh)
1818
logger.addHandler(filehandler)
19-
logger.setLevel(logging.DEBUG)
2019

2120
class RunnerABS():
2221
"""
@@ -41,10 +40,10 @@ class Caller(object):
4140
logger = logging.getLogger(__name__)
4241
logger.addHandler(sh)
4342
logger.addHandler(filehandler)
44-
logger.setLevel(logging.DEBUG)
4543
def __init__(self) -> None:
4644
super().__init__()
4745
self.caller_logger = logger
46+
self.caller_logger.debug(f"Caller logger is set to {self.logger.getEffectiveLevel()}")
4847

4948
class Runner(RunnerABS):
5049
"""
@@ -53,11 +52,15 @@ class Runner(RunnerABS):
5352
logger = logging.getLogger(__name__)
5453
logger.addHandler(sh)
5554
logger.addHandler(filehandler)
56-
logger.setLevel(logging.DEBUG)
5755
def __init__(self, config):
5856
super().__init__()
5957
self.config = config
6058
self.runner_logger = logger
59+
if self.config['basic'].getboolean('testing'):
60+
self.logger.setLevel(self.config['basic'].getint('loglevel'))
61+
else:
62+
self.logger.setLevel(10)
63+
self.logger.debug(f"Runner logger is set to {self.logger.getEffectiveLevel()}")
6164
def run_non_async_request(self, url):
6265
response = requests.get(url)
6366
return response

lib/sports/sports.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import json
99
import sys
1010

11+
# TODO @thefinaljoke More abstract to use different apis
1112
class SportApi(Runner):
1213
def __init__(self, config):
1314
super().__init__(config)
@@ -99,9 +100,15 @@ def __repr__(self):
99100
def build_standings(self):
100101
#counter = 0
101102
position = []
103+
regular_season_check = (
104+
"MLB - Regular Season",
105+
"NBA - Regular Season",
106+
"NHL - Regular Season",
107+
"NFL - Regular Season"
108+
)
102109
# Can Be Empty Must try and except for that
103110
for pos in self.main_sport['standings'].get('response')[0]:
104-
if pos.get('stage') != "MLB - Regular Season" or pos.get('stage') != "NBA - Regular Season":
111+
if not pos.get('stage') in regular_season_check:
105112
continue
106113
position.append({'name': pos.get('team').get('name'),
107114
'position': pos.get('position'),

lib/stock/stockquote.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ async def run(self) -> Dict:
2626
"""
2727
returns current stock Quotes and Price
2828
"""
29+
self.logger.info("Running Stock Data")
2930
symbol = self.config.get('symbol')
3031
api_data = await self.get_data(self.url_builder(symbol=symbol))
3132
api_data['symbol'] = symbol

lib/weather/ecIcons_utf8.csv

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,5 @@ UTF8,92,92,902,Rising,Day and Night Conditions,f057,
4646
UTF8,93,93,903,Falling,Day and Night Conditions,f088,
4747
UTF8,94,94,904,Steady,Day and Night Conditions,f04d,
4848
UTF8,1,5,800,Clear,Day Conditions Only,f00d,
49-
UTF8,3,3,801,Cloudy Periods,Day Conditions Only,f013,
49+
UTF8,3,3,801,Cloudy Periods,Day Conditions Only,f013,
50+
UTF8,31,31,806,Mainly Clear,Night Conditions Only,f02e,

lib/weather/weather.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,8 @@
44
import sys
55
import os
66
import json
7-
from requests import Response
8-
import geocoder
97
from typing import Dict, Tuple
108
from datetime import datetime
11-
from enum import Enum
129
import csv
1310

1411
def get_weather_csv():
@@ -80,6 +77,7 @@ async def get_long_and_lat(self, location: str=None, zipcode: int=None) -> Tuple
8077
"""
8178
Searches for Longitude and latitude for Given City
8279
"""
80+
self.logger.debug("Getting Lat and Long")
8381
try:
8482
if location:
8583
self.logger.debug("Getting Longitude and Latitude")
@@ -102,6 +100,7 @@ async def url_builder(self, location=None, zipcode=None, current_location=False)
102100
"""
103101
Builds Url to poll the Api
104102
"""
103+
self.logger.debug("Building url...")
105104
if current_location:
106105
ip_json = self.get_current_location()
107106
lon, lat = ip_json['loc'].split(',')[1], ip_json['loc'].split(',')[0]

main.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import requests
2121
import logging
2222

23+
2324
stream_formatter = logging.Formatter(
2425
"%(levelname)s:%(asctime)s:%(module)s:%(message)s"
2526
)
@@ -30,12 +31,16 @@
3031
logger = logging.getLogger(__name__)
3132
logger.addHandler(sh)
3233
logger.addHandler(filehandler)
33-
logger.setLevel(logging.DEBUG)
3434

3535
class Main():
3636
def __init__(self, config) -> None:
3737
self.config = config
3838
self.logger = logger
39+
if self.config['basic'].getboolean('testing'):
40+
self.logger.setLevel(self.config['basic'].getint('loglevel'))
41+
else:
42+
self.logger.setLevel(10)
43+
self.logger.debug(f"Logger is set to {self.logger.getEffectiveLevel()}")
3944
def parse_config_file(self):
4045
module = {}
4146
self.logger.info("Parsing config file")
@@ -50,6 +55,9 @@ def get_modules_to_run(self):
5055
self.logger.info("Getting Modules")
5156
for section, runtime in parsed.items():
5257
if runtime:
58+
if section == 'time':
59+
self.logger.debug("Time midule selected from config")
60+
api_modules.update({'time': " "})
5361
if section == 'weather':
5462
self.logger.debug("Weather Module Selected From Config")
5563
api_modules.update({'weather': WeatherApi(self.config)})
@@ -74,8 +82,11 @@ def poll_rgbmatrix(self):
7482
return rgboptions
7583

7684
async def init_matrix(self, matrix):
77-
verified_modules = [TimeMatrix(matrix)]
85+
verified_modules = []
7886
modules = self.get_modules_to_run()
87+
if 'time' in modules:
88+
self.logger.debug("Initialized Time")
89+
verified_modules.append(TimeMatrix(matrix, self.config['time']))
7990
if 'weather' in modules:
8091
self.logger.debug("Initialized Weather")
8192
verified_modules.append(WeatherMatrix(matrix, modules['weather'], logger))
@@ -112,5 +123,7 @@ async def main_run(self):
112123
loop.run_forever()
113124
except KeyboardInterrupt:
114125
logger.critical("Key Interrupt")
126+
except Exception as e:
127+
logger.critical(e)
115128
finally:
116129
loop.stop()

matrix/matrix.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@
2626
logger = logging.getLogger(__name__)
2727
logger.addHandler(sh)
2828
logger.addHandler(filehandler)
29-
logger.setLevel(logging.DEBUG)
30-
29+
logger.setLevel(logging.INFO)
3130
class ABSMatrix():
3231
def __init__(self) -> None:
3332
pass
@@ -50,7 +49,7 @@ class Matrix(ABSMatrix):
5049
def __init__(self, config) -> None:
5150
self.config = config
5251
self.logger = logger
53-
52+
self.logger.debug(f"Logger is set to {self.logger.getEffectiveLevel()}")
5453
def get_font_graphics(self, font_file):
5554
font = graphics.Font()
5655
font.LoadFont(f"/etc/ohmyoled/fonts/{font_file}")

matrix/sport/sportmatrix.py

Lines changed: 17 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -15,37 +15,6 @@
1515
from lib.sports.basketball.basketball import Basketball
1616
from lib.sports.hockey.hockey import Hockey
1717
from matrix.sport.team_mapping import BASEBALL_TEAMS, BASKETBALL_TEAMS
18-
class BaseballMatrix(Matrix):
19-
def __init__(self, matrix, api, logger) -> None:
20-
self.matrix = matrix
21-
self.api = api
22-
self.logger = logger
23-
def render_standings(self):
24-
"""
25-
Split the screen and then Roll the screen
26-
"""
27-
self.draw_rectangle()
28-
def render_sport(self):
29-
self.render_standings()
30-
time.sleep(10)
31-
32-
class BasketballMatrix(Matrix):
33-
def __init__(self, matrix, api, logger) -> None:
34-
self.matrix = matrix
35-
self.api = api
36-
self.logger = logger
37-
38-
def render_sport(self):
39-
return
40-
41-
class HockeyMatrix(Matrix):
42-
def __init__(self, matrix, api, logger) -> None:
43-
self.matrix = matrix
44-
self.api = api
45-
self.logger = logger
46-
47-
def render_sport(self):
48-
return
4918

5019
class SportMatrix(Matrix):
5120
def __init__(self, matrix, api, logger) -> None:
@@ -70,10 +39,12 @@ def determine_nextgame(self, nextgame_api):
7039
status = ("FT", "ABD")
7140
for game in nextgame_api:
7241
if "IN" in game['status']:
42+
self.logger.debug(f"In Game")
7343
# During the game
7444
return game
7545
if game['status'] == "FT" and datetime.fromtimestamp(game['timestamp']).date() == datetime.today().date():
7646
# Same Day will display for the rest of the day
47+
self.logger.debug("Game is finished but still same day")
7748
return game
7849
if game['status'] not in status:
7950
return game
@@ -98,16 +69,18 @@ def build_in_game_image(self, nextgame):
9869
middle_draw = ImageDraw.Draw(middle_image)
9970
font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
10071
status = nextgame['status']
72+
self.logger.debug(f"status: {status}")
10173
score = (nextgame['teams']['home']['total'], nextgame['teams']['away']['total'])
102-
middle_draw.multiline_text((10,0), f"{status}\n{score[0]}-{score[1]}", font=font)
74+
self.logger.debug(f"Score: {score}")
75+
middle_draw.multiline_text((12,0), f" {status}\n{score[0]}-{score[1]}", font=font)
10376
return middle_image, (15, 0)
10477
def build_finished_game_image(self, nextgame):
10578
middle_image = self.make_new_image((34,16))
10679
middle_draw = ImageDraw.Draw(middle_image)
10780
font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
10881
status = nextgame['status']
10982
score = (nextgame['teams']['home']['total'], nextgame['teams']['away']['total'])
110-
middle_draw.multiline_text((10,0), f"{status}\n{score[0]}-{score[1]}", font=font)
83+
middle_draw.multiline_text((12,0), f" {status}\n{score[0]}-{score[1]}", font=font)
11184
return middle_image, (15, 0)
11285

11386
def check_offseason(self, api):
@@ -122,16 +95,23 @@ def build_next_game_image(self, nextgame):
12295
middle_draw = ImageDraw.Draw(middle_image)
12396
font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
12497
time = datetime.fromtimestamp(nextgame['timestamp']).strftime("%I:%M%p %a")
125-
time = "\n ".join(time.split())
98+
formatted_time = time.split()
99+
formatted_time[0] = f" {formatted_time[0]}"
100+
time = "\n ".join(formatted_time)
126101
middle_draw.multiline_text((0,0), f'{time}', font=font)
127102
return middle_image, (15, 0)
128103

129104
def build_home_away_image(self, nextgame):
105+
self.logger.debug(f"Building Home away image")
130106
home_data = self.home_team(nextgame)
107+
self.logger.debug(f"Home Data {home_data}")
131108
home_logo = Image.open(self.get_logo(home_data['logo'], home_data['id']))
109+
self.logger.debug(f"Got Logo {home_logo}")
132110
home_logo.thumbnail((16,16))
133111
away_data = self.away_team(nextgame)
112+
self.logger.debug(f"Away Data: {away_data}")
134113
away_logo = Image.open(self.get_logo(away_data['logo'], away_data['id']))
114+
self.logger.debug(f"Away Logo {away_logo}")
135115
away_logo.thumbnail((16,16))
136116
return (home_logo, (-2,0)), (away_logo, (50, 0))
137117

@@ -190,7 +170,6 @@ def build_standings_image(self, api, xpos) -> Tuple[int, int]:
190170
american, national = self.baseball_divisions(api.standings)
191171
american.extend(national)
192172
text = " ".join(american)
193-
img_width, img_height = self.get_text_size(text)
194173
standings_draw.text(
195174
(-xpos, 0),
196175
text,
@@ -225,7 +204,7 @@ def render(self, api):
225204
xpos_for_top += 1
226205
if xpos_for_top == 100:
227206
xpos_for_top = 0
228-
time.sleep(3) if xpos == 1 else time.sleep(.05)
207+
time.sleep(3) if xpos == 1 else time.sleep(.03)
229208
else:
230209
font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14)
231210
self.draw_multiline_text((0, 0), "Basketball\nOffseason", font=font)
@@ -263,7 +242,8 @@ def render(self, api):
263242
if 'hockey' in api.sport:
264243
self.logger.info("Found Hockey, Displaying Hockey Matrix")
265244
if self.check_offseason(api):
266-
sportmatrix = HockeyMatrix(self.matrix, api, self.logger)
245+
pass
246+
#sportmatrix = HockeyMatrix(self.matrix, api, self.logger)
267247
else:
268248
font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14)
269249
self.draw_multiline_text((0, 0), "Hockey\nOffseason", font=font)

0 commit comments

Comments
 (0)