polybar-weather: make number of forecasts configurable

This commit is contained in:
Vincent Bernat 2021-08-10 17:13:31 +02:00
parent 93a0489385
commit 9e55aa23b9

View file

@ -24,22 +24,22 @@ def get_location():
return (data["lat"], data["lon"]) return (data["lat"], data["lon"])
def get_weather(apikey, latitude, longitude, endpoint): def get_weather(apikey, latitude, longitude, forecasts):
"""Return current weather data from openweathermap.""" """Return forecasts data from openweathermap."""
logger.debug("query openweathermap for %s, %s", latitude, longitude) logger.debug("query openweathermap for %s, %s", latitude, longitude)
r = requests.get( r = requests.get(
f"https://api.openweathermap.org/data/2.5/{endpoint}", "https://api.openweathermap.org/data/2.5/forecast",
params={ params={
"appid": apikey, "appid": apikey,
"lat": latitude, "lat": latitude,
"lon": longitude, "lon": longitude,
"units": "metric", "units": "metric",
"cnt": 3, "cnt": forecasts,
}, },
) )
r.raise_for_status() r.raise_for_status()
data = r.json() data = r.json()
logger.debug("%s data: %s", endpoint, data) logger.debug("forecast data: %s", data)
return data return data
@ -108,14 +108,19 @@ if __name__ == "__main__":
default=os.environ.get("OWM_API_KEY"), default=os.environ.get("OWM_API_KEY"),
help="OpenWeatherMap API key", help="OpenWeatherMap API key",
) )
parser.add_argument("--font", default=4, type=int, help="Weather Icons 1-index") parser.add_argument(
"--forecasts", default=3, type=int, help="Number of forecasts to fetch"
)
parser.add_argument(
"--font-index", default=4, type=int, help="Weather Icons 1-index"
)
parser.add_argument( parser.add_argument(
"--output", "--output",
default=f"{os.environ['XDG_RUNTIME_DIR']}/i3/weather.txt", default=f"{os.environ['XDG_RUNTIME_DIR']}/i3/weather.txt",
help="Output destination", help="Output destination",
) )
parser.add_argument( parser.add_argument(
"--timeout", "--online-timeout",
default=30, default=30,
type=int, type=int,
help="Wait up to TIMEOUT minutes to be online", help="Wait up to TIMEOUT minutes to be online",
@ -141,7 +146,7 @@ if __name__ == "__main__":
update_status("", options.output) update_status("", options.output)
if ( if (
subprocess.run( subprocess.run(
["nm-online", "-s", "-q", "-t", str(options.timeout * 60)] ["nm-online", "-s", "-q", "-t", str(options.online_timeout * 60)]
).returncode ).returncode
!= 0 != 0
): ):
@ -151,23 +156,21 @@ if __name__ == "__main__":
# Grab information. We only use forecast weather, otherwise, # Grab information. We only use forecast weather, otherwise,
# we may get something "late". # we may get something "late".
location = get_location() location = get_location()
forecast_weather = get_weather(options.owm_api_key, *location, "forecast") forecast_weather = get_weather(
options.owm_api_key, *location, options.forecasts
)
description = forecast_weather["list"][0]["weather"][0]["description"] description = forecast_weather["list"][0]["weather"][0]["description"]
logger.info(f"current weather: {description}") logger.info(f"current weather: {description}")
# Format output # Format output
forecasts = [ forecasts = [format_weather(data) for data in forecast_weather["list"]]
format_weather(forecast_weather["list"][0]),
format_weather(forecast_weather["list"][1]),
format_weather(forecast_weather["list"][2]),
]
while len(forecasts) >= 2: while len(forecasts) >= 2:
if forecasts[-1] == forecasts[-2]: if forecasts[-1] == forecasts[-2]:
forecasts.pop() forecasts.pop()
else: else:
break break
output = " ".join(forecasts) output = " ".join(forecasts)
output = output.replace("%{Tx}", "%%{T%d}" % options.font) output = output.replace("%{Tx}", "%%{T%d}" % options.font_index)
logger.debug("output: %s", output) logger.debug("output: %s", output)
update_status(output, options.output) update_status(output, options.output)