chutney/weather_updater.py

55 lines
1.7 KiB
Python

import os
import requests
from configparser import ConfigParser
class WeatherUpdater:
def __init__(self, configFile):
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)
self.weatherTempFile = 'weather.tmp'
self.weatherFile = 'weather.txt'
# TODO - clear weather file on init and on failure
def updateWeather(self):
try:
temperature = round(self.getTemperature())
self.persistTemperature(temperature)
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 getTemperature(self):
weather = self.getWeather()
currentWeather = list(
filter(
lambda t: t['timestep'] == 'current',
weather['tomorrow']['data']['timelines']
)
)
return currentWeather[0]['intervals'][0]['values']['temperature']
def getWeather(self):
return requests.get(self.uri, auth=self.auth).json()
def persistTemperature(self, temperature):
with open(self.weatherTempFile, 'w') as file:
file.write(str(temperature))
os.replace(self.weatherTempFile, self.weatherFile)