chutney/weather_display.py

60 lines
2.1 KiB
Python

import colors
import requests
from configparser import ConfigParser
class WeatherDisplay:
def __init__(self, characterDisplay, topRow, configFile):
self.characterDisplay = characterDisplay
self.topRow = topRow
self.currentTemperature = [9, 9]
self.color = colors.BLUE
config = ConfigParser()
config.read(configFile)
host = config['weather'].get('host')
user = config['weather'].get('user')
password = config['weather'].get('pass')
lat = config['weather'].get('lat')
lon = config['weather'].get('lon')
self.uri = f'https://{host}/api/weather?lat={lat}&lon={lon}&units=metric'
self.auth = (user, password)
def showWeather(self):
try:
self.showTemperature(
self.getTemperatureCharacters(self.getTemperature()))
except requests.exceptions.ConnectionError:
print("connection error", flush=True)
self.characterDisplay.clearRow(self.topRow)
except requests.exceptions.Timeout:
print("timeout", flush=True)
self.characterDisplay.clearRow(self.topRow)
def showTemperature(self, temperature):
if temperature != self.currentTemperature:
self.characterDisplay.clearRow(self.topRow)
start = 13 if (
len(temperature) == 2 and temperature[0] == '-') or len(temperature) == 1 else 9
for c in temperature:
if c == '-':
self.characterDisplay.displayNegative(
start-3, self.topRow, self.color)
else:
self.characterDisplay.displayDigit(
start, self.topRow, c, self.color)
start = start + 4
self.currentTemperature = temperature
def getTemperature(self):
return list(filter(lambda t: t["timestep"] == 'current', requests.get(self.uri, auth=self.auth, timeout=2).json()["tomorrow"]["data"]['timelines']))[0]["intervals"][0]["values"]["temperature"]
def getTemperatureCharacters(self, temperature):
return list(str(round(temperature)))