From 5be6fe738657f05e44206effc361b7a43248808b Mon Sep 17 00:00:00 2001 From: Nick Shorter Date: Sat, 2 Oct 2021 00:03:04 -0500 Subject: [PATCH] Built out the rest of the weather app --- lib/weather/weather.py | 14 ++++++++++---- main.py | 14 ++++++-------- matrix/__init__.py | 0 matrix/sport/__init__.py | 0 matrix/sport/sportmatrix.py | 12 +++++++----- matrix/stock/__init__.py | 0 matrix/stock/stockmatrix.py | 4 +++- matrix/test.py | 19 +++++++++++++++++-- matrix/time.py | 7 +++++-- matrix/weathermatrix.py | 2 ++ 10 files changed, 50 insertions(+), 22 deletions(-) create mode 100644 matrix/__init__.py create mode 100644 matrix/sport/__init__.py create mode 100644 matrix/stock/__init__.py diff --git a/lib/weather/weather.py b/lib/weather/weather.py index a5e8d7b..dec13df 100755 --- a/lib/weather/weather.py +++ b/lib/weather/weather.py @@ -1,6 +1,9 @@ #!/usr/bin/env python3 +import asyncio +from logging import currentframe from lib.run import Runner, Caller +from lib.asynclib import make_async import sys import os import json @@ -12,6 +15,7 @@ def get_weather_csv() -> List[Dict[str, str]]: csv_path = '/etc/ohmyoled/ecIcons_utf8.csv' return list(csv.DictReader(open(csv_path))) + def build_weather_icons() -> str: csv = get_weather_csv() icon = {} @@ -92,7 +96,8 @@ async def get_long_and_lat(self, location: str=None, zipcode: int=None) -> Tuple except Exception as e: self.logger.critical(e) sys.exit("No City Found") - + + @make_async def get_current_location(self) -> Dict[str, str]: url = 'http://ipinfo.io/json' response = self.run_non_async_request(url) @@ -104,14 +109,14 @@ async def url_builder(self, location=None, zipcode=None, current_location=False) """ self.logger.debug("Building Weather url...") if current_location: - ip_json: Dict[str, str] = self.get_current_location() + ip_json: Dict[str, str] = await self.get_current_location() lon, lat = ip_json['loc'].split(',')[1], ip_json['loc'].split(',')[0] url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={self.token}&units={self.weather.get('format')}" elif location: lon, lat = await self.get_long_and_lat(location) url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={self.token}&units={self.weather.get('format')}" else: - ip_json = self.get_current_location() + ip_json = await self.get_current_location() lon, lat = ip_json['loc'].split(',')[1], ip_json['loc'].split(',')[0] url = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={self.token}&units={self.weather.get('format')}" return url @@ -120,7 +125,8 @@ async def run(self) -> Dict: self.logger.info("Running Api for Weather") args = await self.parse_args() api_data = await self.get_data(args) - api_data['name'] = self.get_current_location()['city'] + current_data = await self.get_current_location() + api_data['name'] = current_data['city'] return api_data class Weather(Caller): diff --git a/main.py b/main.py index 02310f4..405f7bc 100755 --- a/main.py +++ b/main.py @@ -2,22 +2,18 @@ import asyncio import configparser -import sys +import time from rgbmatrix import ( RGBMatrixOptions, RGBMatrix ) from lib.weather.weather import WeatherApi from matrix.stock.stockmatrix import StockMatrix -from matrix.stock.historicalstockmatrix import HistoricalStockMatrix -from lib.stock.stocks import StockApi, Stock -from lib.sports.sports import SportApi, Sport -from matrix.matrix import Matrix +from lib.stock.stocks import StockApi +from lib.sports.sports import SportApi from matrix.time import TimeMatrix from matrix.weathermatrix import WeatherMatrix from matrix.sport.sportmatrix import SportMatrix -from abc import abstractmethod -import requests import logging @@ -123,15 +119,17 @@ async def main_run(self, loop): first_poll = True while True: for index, matrix in enumerate(matrixes): + matrix_start_time = time.perf_counter() if first_poll: self.poll = await matrix.poll_api() first_poll = False if index + 1 >= len(matrixes): tasks = [asyncio.create_task(matrix.render(self.poll, loop)), asyncio.create_task(matrixes[0].poll_api())] else: - # Each one build a new function that can be called asynchrounously tasks = [asyncio.create_task(matrix.render(self.poll, loop)), asyncio.create_task(matrixes[index+1].poll_api())] _, self.poll = await asyncio.gather(*tasks) + matrix_finish_time = time.perf_counter() + logger.info(f"{matrix} rendered for {matrix_finish_time - matrix_start_time:0.4f}s") except Exception as E: logger.error(E) loop.stop() diff --git a/matrix/__init__.py b/matrix/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/matrix/sport/__init__.py b/matrix/sport/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/matrix/sport/sportmatrix.py b/matrix/sport/sportmatrix.py index f218c5d..49b01cb 100755 --- a/matrix/sport/sportmatrix.py +++ b/matrix/sport/sportmatrix.py @@ -5,7 +5,7 @@ import time import urllib.request from datetime import datetime -from typing import List, Dict, Tuple, Bool +from typing import List, Dict, Tuple from collections import deque from PIL import ImageFont, Image, ImageDraw from lib.sports.sports import Sport @@ -16,6 +16,8 @@ def __init__(self, matrix, api: Sport, logger: Logger) -> None: self.matrix = matrix self.api = api self.logger = logger + def __str__(self) -> str: + return "SportMatrix" async def poll_api(self) -> Sport: return Sport(await self.api.run()) @@ -66,7 +68,7 @@ def build_in_game_image(self, nextgame: Dict): self.logger.debug(f"status: {status}") score = (nextgame['teams']['home']['total'], nextgame['teams']['away']['total']) self.logger.debug(f"Score: {score}") - middle_draw.multiline_text((12,0), f" {status}\n{score[0]}-{score[1]}", font=font) + middle_draw.multiline_text((12,0), f"{status}\n{score[0]}-{score[1]}", font=font) return middle_image, (15, 0) def build_finished_game_image(self, nextgame): @@ -75,7 +77,7 @@ def build_finished_game_image(self, nextgame): font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8) status = nextgame['status'] score = (nextgame['teams']['home']['total'], nextgame['teams']['away']['total']) - middle_draw.multiline_text((12,0), f" {status}\n{score[0]}-{score[1]}", font=font) + middle_draw.multiline_text((12,0), f"{status}\n{score[0]}-{score[1]}", font=font) return middle_image, (15, 0) def check_offseason(self, api) -> bool: @@ -200,7 +202,7 @@ async def render(self, api, loop): xpos_for_top += 1 if xpos_for_top == 100: xpos_for_top = 0 - time.sleep(3) if xpos == 1 else time.sleep(.03) + time.sleep(3) if xpos == 1 else time.sleep(.001) else: font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14) self.draw_multiline_text((0, 0), "Basketball\nOffseason", font=font) @@ -229,7 +231,7 @@ async def render(self, api, loop): xpos_for_top += 1 if xpos_for_top == 100: xpos_for_top = 0 - time.sleep(3) if xpos == 1 else time.sleep(.05) + time.sleep(3) if xpos == 1 else time.sleep(.01) else: font = ImageFont.truetype("/usr/share/fonts/fonts/04b24.otf", 14) self.draw_multiline_text((0, 0), "Basketball\nOffseason", font=font) diff --git a/matrix/stock/__init__.py b/matrix/stock/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/matrix/stock/stockmatrix.py b/matrix/stock/stockmatrix.py index 0bfeacf..fba082a 100755 --- a/matrix/stock/stockmatrix.py +++ b/matrix/stock/stockmatrix.py @@ -12,7 +12,9 @@ def __init__(self, matrix, api, logger) -> None: self.matrix = matrix self.api = api self.logger = logger - + def __str__(self) -> str: + return "StockMatrix" + async def poll_api(self) -> Stock: return Stock(await self.api.run()) diff --git a/matrix/test.py b/matrix/test.py index 688e808..9f08ffd 100755 --- a/matrix/test.py +++ b/matrix/test.py @@ -1,4 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 +""" import time import sys import datetime @@ -70,6 +71,7 @@ scrolling_matrix.SetImage(master_image) # Image within an image """ +""" scrolling_font = ImageFont.truetype("/usr/share/fonts/fonts/04B_03B_.TTF", 8) scrolling_matrix = RGBMatrix(options=bottom_options) img1_text = Image.new("RGB", (22, 5)) @@ -176,4 +178,17 @@ time.sleep(.05) """ -time.sleep(30) \ No newline at end of file +#time.sleep(30) + +import asyncio +from setuptools import find_packages, setup +breakpoint() +#@make_async +def test1(arg1, arg2): + print(arg1, arg2) + +def test2(arg1, arg2): + print(arg1, arg2) + + +asyncio.run(test1("hello", "world")) \ No newline at end of file diff --git a/matrix/time.py b/matrix/time.py index dfd5691..7985206 100755 --- a/matrix/time.py +++ b/matrix/time.py @@ -16,7 +16,10 @@ def __init__(self, matrix, config) -> None: self.matrix = matrix self.config = config self.logger.debug("Time Matrix Initalized") - + + def __str__(self) -> str: + return "TimeMatrix" + def return_time(self, fmt: str) -> datetime: return datetime.now().strftime(fmt) @@ -24,7 +27,7 @@ async def poll_api(self) -> None: """ Function that does not poll since this a time """ - self.logger.info("No Api call reqiured for time module") + self.logger.info("No Api call required for time module") return None def build_fmt(self) -> str: diff --git a/matrix/weathermatrix.py b/matrix/weathermatrix.py index 0d6a152..a7b2b2b 100755 --- a/matrix/weathermatrix.py +++ b/matrix/weathermatrix.py @@ -17,6 +17,8 @@ def __init__(self, matrix, api: Dict, logger) -> None: self.logger = logger self.icons = build_weather_icons() + def __str__(self) -> str: + return "WeatherMatrix" async def poll_api(self) -> Weather: return Weather(await self.api.run())