2022-12-25 11:01:48 -05:00
|
|
|
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')
|
2022-12-25 11:01:48 -05:00
|
|
|
|
|
|
|
def updateWeather(self):
|
|
|
|
try:
|
|
|
|
temperature = round(self.getTemperature())
|
|
|
|
self.persistTemperature(temperature)
|
2022-12-25 12:33:06 -05:00
|
|
|
except requests.exceptions.ConnectionError as e:
|
|
|
|
print(e, flush=True)
|
|
|
|
self.persistTemperature('error')
|
|
|
|
except requests.exceptions.Timeout as e:
|
|
|
|
print(e, flush=True)
|
|
|
|
self.persistTemperature('error')
|
|
|
|
|
|
|
|
def clearWeather(self):
|
|
|
|
self.persistTemperature('halted')
|
2022-12-25 11:01:48 -05:00
|
|
|
|
|
|
|
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()
|
2022-12-25 11:01:48 -05:00
|
|
|
|
|
|
|
def persistTemperature(self, temperature):
|
|
|
|
with open(self.weatherTempFile, 'w') as file:
|
|
|
|
file.write(str(temperature))
|
|
|
|
|
|
|
|
os.replace(self.weatherTempFile, self.weatherFile)
|