57 lines
1.7 KiB
Python
57 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'
|
|
self.persistTemperature('init')
|
|
|
|
def updateWeather(self):
|
|
try:
|
|
temperature = round(self.getTemperature())
|
|
self.persistTemperature(temperature)
|
|
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')
|
|
|
|
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, timeout=3).json()
|
|
|
|
def persistTemperature(self, temperature):
|
|
with open(self.weatherTempFile, 'w') as file:
|
|
file.write(str(temperature))
|
|
|
|
os.replace(self.weatherTempFile, self.weatherFile)
|