chutney/weather_updater.py

54 lines
1.6 KiB
Python
Raw Normal View History

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'
2022-12-25 12:33:06 -05:00
self.persistTemperature('init')
def updateWeather(self):
try:
temperature = round(self.getTemperature())
self.persistTemperature(temperature)
2022-12-28 18:37:32 -05:00
except Exception as e:
2022-12-25 12:33:06 -05:00
print(e, flush=True)
self.persistTemperature('error')
def clearWeather(self):
self.persistTemperature('halted')
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):
2022-12-26 19:37:50 -05:00
return requests.get(self.uri, auth=self.auth, timeout=3).json()
def persistTemperature(self, temperature):
with open(self.weatherTempFile, 'w') as file:
file.write(str(temperature))
os.replace(self.weatherTempFile, self.weatherFile)