Skip to content

Built out the rest of the weather app #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions lib/weather/weather.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 = {}
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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):
Expand Down
14 changes: 6 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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()
Expand Down
Empty file added matrix/__init__.py
Empty file.
Empty file added matrix/sport/__init__.py
Empty file.
12 changes: 7 additions & 5 deletions matrix/sport/sportmatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())

Expand Down Expand Up @@ -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):
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Empty file added matrix/stock/__init__.py
Empty file.
4 changes: 3 additions & 1 deletion matrix/stock/stockmatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down
19 changes: 17 additions & 2 deletions matrix/test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""
import time
import sys
import datetime
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -176,4 +178,17 @@

time.sleep(.05)
"""
time.sleep(30)
#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"))
7 changes: 5 additions & 2 deletions matrix/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ 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)

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:
Expand Down
2 changes: 2 additions & 0 deletions matrix/weathermatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down