Skip to content

Commit 5dbc884

Browse files
authored
Merge pull request #61 from TheFinalJoke/weather_all_async
Built out the rest of the weather app
2 parents a23425d + 5be6fe7 commit 5dbc884

File tree

10 files changed

+50
-22
lines changed

10 files changed

+50
-22
lines changed

lib/weather/weather.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
#!/usr/bin/env python3
22

3+
import asyncio
4+
from logging import currentframe
35
from lib.run import Runner, Caller
6+
from lib.asynclib import make_async
47
import sys
58
import os
69
import json
@@ -12,6 +15,7 @@
1215
def get_weather_csv() -> List[Dict[str, str]]:
1316
csv_path = '/etc/ohmyoled/ecIcons_utf8.csv'
1417
return list(csv.DictReader(open(csv_path)))
18+
1519
def build_weather_icons() -> str:
1620
csv = get_weather_csv()
1721
icon = {}
@@ -92,7 +96,8 @@ async def get_long_and_lat(self, location: str=None, zipcode: int=None) -> Tuple
9296
except Exception as e:
9397
self.logger.critical(e)
9498
sys.exit("No City Found")
95-
99+
100+
@make_async
96101
def get_current_location(self) -> Dict[str, str]:
97102
url = 'http://ipinfo.io/json'
98103
response = self.run_non_async_request(url)
@@ -104,14 +109,14 @@ async def url_builder(self, location=None, zipcode=None, current_location=False)
104109
"""
105110
self.logger.debug("Building Weather url...")
106111
if current_location:
107-
ip_json: Dict[str, str] = self.get_current_location()
112+
ip_json: Dict[str, str] = await self.get_current_location()
108113
lon, lat = ip_json['loc'].split(',')[1], ip_json['loc'].split(',')[0]
109114
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={self.token}&units={self.weather.get('format')}"
110115
elif location:
111116
lon, lat = await self.get_long_and_lat(location)
112117
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={self.token}&units={self.weather.get('format')}"
113118
else:
114-
ip_json = self.get_current_location()
119+
ip_json = await self.get_current_location()
115120
lon, lat = ip_json['loc'].split(',')[1], ip_json['loc'].split(',')[0]
116121
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={self.token}&units={self.weather.get('format')}"
117122
return url
@@ -120,7 +125,8 @@ async def run(self) -> Dict:
120125
self.logger.info("Running Api for Weather")
121126
args = await self.parse_args()
122127
api_data = await self.get_data(args)
123-
api_data['name'] = self.get_current_location()['city']
128+
current_data = await self.get_current_location()
129+
api_data['name'] = current_data['city']
124130
return api_data
125131

126132
class Weather(Caller):

main.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,18 @@
22

33
import asyncio
44
import configparser
5-
import sys
5+
import time
66
from rgbmatrix import (
77
RGBMatrixOptions,
88
RGBMatrix
99
)
1010
from lib.weather.weather import WeatherApi
1111
from matrix.stock.stockmatrix import StockMatrix
12-
from matrix.stock.historicalstockmatrix import HistoricalStockMatrix
13-
from lib.stock.stocks import StockApi, Stock
14-
from lib.sports.sports import SportApi, Sport
15-
from matrix.matrix import Matrix
12+
from lib.stock.stocks import StockApi
13+
from lib.sports.sports import SportApi
1614
from matrix.time import TimeMatrix
1715
from matrix.weathermatrix import WeatherMatrix
1816
from matrix.sport.sportmatrix import SportMatrix
19-
from abc import abstractmethod
20-
import requests
2117
import logging
2218

2319

@@ -123,15 +119,17 @@ async def main_run(self, loop):
123119
first_poll = True
124120
while True:
125121
for index, matrix in enumerate(matrixes):
122+
matrix_start_time = time.perf_counter()
126123
if first_poll:
127124
self.poll = await matrix.poll_api()
128125
first_poll = False
129126
if index + 1 >= len(matrixes):
130127
tasks = [asyncio.create_task(matrix.render(self.poll, loop)), asyncio.create_task(matrixes[0].poll_api())]
131128
else:
132-
# Each one build a new function that can be called asynchrounously
133129
tasks = [asyncio.create_task(matrix.render(self.poll, loop)), asyncio.create_task(matrixes[index+1].poll_api())]
134130
_, self.poll = await asyncio.gather(*tasks)
131+
matrix_finish_time = time.perf_counter()
132+
logger.info(f"{matrix} rendered for {matrix_finish_time - matrix_start_time:0.4f}s")
135133
except Exception as E:
136134
logger.error(E)
137135
loop.stop()

matrix/__init__.py

Whitespace-only changes.

matrix/sport/__init__.py

Whitespace-only changes.

matrix/sport/sportmatrix.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import time
66
import urllib.request
77
from datetime import datetime
8-
from typing import List, Dict, Tuple, Bool
8+
from typing import List, Dict, Tuple
99
from collections import deque
1010
from PIL import ImageFont, Image, ImageDraw
1111
from lib.sports.sports import Sport
@@ -16,6 +16,8 @@ def __init__(self, matrix, api: Sport, logger: Logger) -> None:
1616
self.matrix = matrix
1717
self.api = api
1818
self.logger = logger
19+
def __str__(self) -> str:
20+
return "SportMatrix"
1921
async def poll_api(self) -> Sport:
2022
return Sport(await self.api.run())
2123

@@ -66,7 +68,7 @@ def build_in_game_image(self, nextgame: Dict):
6668
self.logger.debug(f"status: {status}")
6769
score = (nextgame['teams']['home']['total'], nextgame['teams']['away']['total'])
6870
self.logger.debug(f"Score: {score}")
69-
middle_draw.multiline_text((12,0), f" {status}\n{score[0]}-{score[1]}", font=font)
71+
middle_draw.multiline_text((12,0), f"{status}\n{score[0]}-{score[1]}", font=font)
7072
return middle_image, (15, 0)
7173

7274
def build_finished_game_image(self, nextgame):
@@ -75,7 +77,7 @@ def build_finished_game_image(self, nextgame):
7577
font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
7678
status = nextgame['status']
7779
score = (nextgame['teams']['home']['total'], nextgame['teams']['away']['total'])
78-
middle_draw.multiline_text((12,0), f" {status}\n{score[0]}-{score[1]}", font=font)
80+
middle_draw.multiline_text((12,0), f"{status}\n{score[0]}-{score[1]}", font=font)
7981
return middle_image, (15, 0)
8082

8183
def check_offseason(self, api) -> bool:
@@ -200,7 +202,7 @@ async def render(self, api, loop):
200202
xpos_for_top += 1
201203
if xpos_for_top == 100:
202204
xpos_for_top = 0
203-
time.sleep(3) if xpos == 1 else time.sleep(.03)
205+
time.sleep(3) if xpos == 1 else time.sleep(.001)
204206
else:
205207
font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14)
206208
self.draw_multiline_text((0, 0), "Basketball\nOffseason", font=font)
@@ -229,7 +231,7 @@ async def render(self, api, loop):
229231
xpos_for_top += 1
230232
if xpos_for_top == 100:
231233
xpos_for_top = 0
232-
time.sleep(3) if xpos == 1 else time.sleep(.05)
234+
time.sleep(3) if xpos == 1 else time.sleep(.01)
233235
else:
234236
font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14)
235237
self.draw_multiline_text((0, 0), "Basketball\nOffseason", font=font)

matrix/stock/__init__.py

Whitespace-only changes.

matrix/stock/stockmatrix.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ def __init__(self, matrix, api, logger) -> None:
1212
self.matrix = matrix
1313
self.api = api
1414
self.logger = logger
15-
15+
def __str__(self) -> str:
16+
return "StockMatrix"
17+
1618
async def poll_api(self) -> Stock:
1719
return Stock(await self.api.run())
1820

matrix/test.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
2+
"""
23
import time
34
import sys
45
import datetime
@@ -70,6 +71,7 @@
7071
scrolling_matrix.SetImage(master_image)
7172
# Image within an image
7273
"""
74+
"""
7375
scrolling_font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8)
7476
scrolling_matrix = RGBMatrix(options=bottom_options)
7577
img1_text = Image.new("RGB", (22, 5))
@@ -176,4 +178,17 @@
176178
177179
time.sleep(.05)
178180
"""
179-
time.sleep(30)
181+
#time.sleep(30)
182+
183+
import asyncio
184+
from setuptools import find_packages, setup
185+
breakpoint()
186+
#@make_async
187+
def test1(arg1, arg2):
188+
print(arg1, arg2)
189+
190+
def test2(arg1, arg2):
191+
print(arg1, arg2)
192+
193+
194+
asyncio.run(test1("hello", "world"))

matrix/time.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,18 @@ def __init__(self, matrix, config) -> None:
1616
self.matrix = matrix
1717
self.config = config
1818
self.logger.debug("Time Matrix Initalized")
19-
19+
20+
def __str__(self) -> str:
21+
return "TimeMatrix"
22+
2023
def return_time(self, fmt: str) -> datetime:
2124
return datetime.now().strftime(fmt)
2225

2326
async def poll_api(self) -> None:
2427
"""
2528
Function that does not poll since this a time
2629
"""
27-
self.logger.info("No Api call reqiured for time module")
30+
self.logger.info("No Api call required for time module")
2831
return None
2932

3033
def build_fmt(self) -> str:

matrix/weathermatrix.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ def __init__(self, matrix, api: Dict, logger) -> None:
1717
self.logger = logger
1818
self.icons = build_weather_icons()
1919

20+
def __str__(self) -> str:
21+
return "WeatherMatrix"
2022
async def poll_api(self) -> Weather:
2123
return Weather(await self.api.run())
2224

0 commit comments

Comments
 (0)