#!/usr/bin/env bash # tclock-weather — Open-Meteo weather widget for tclock. # # [[clock.widgets]] # title = "Weather" # command = ["tclock-weather", "--city", "Curitiba"] # refresh_secs = 900 # # Location: --city NAME (geocoded) or --lat/--lon. Units: --units metric|imperial. # Theme: --theme / TCLOCK_WIDGET_THEME (default|evangelion|nerv). Cache on by # default; disable with --no-cache or --cache-secs 0. set -euo pipefail GEOCODE_URL="https://geocoding-api.open-meteo.com/v1/search" FORECAST_URL="https://api.open-meteo.com/v1/forecast" DEFAULT_DAYS=3 DEFAULT_UNITS=metric DEFAULT_TIMEOUT=10 DEFAULT_CACHE_SECS=900 DEFAULT_THEME=default MAX_DAYS=16 CITY="" LAT="" LON="" DAYS="" UNITS="" THEME="" OUTPUT_JSON=0 CACHE_SECS="" NO_CACHE=0 TIMEOUT="" NO_COLOR_FLAG=0 CURRENT_ONLY=0 NORMALIZED="" FORECAST_JSON="" LOC_NAME="" LOC_LAT="" LOC_LON="" die() { printf 'tclock-weather: %s\n' "$1" >&2 exit 1 } usage() { cat <<'USAGE' tclock-weather — Open-Meteo weather widget for tclock Usage: tclock-weather --city NAME [--days N] [--units metric|imperial] [--current-only] tclock-weather --lat F --lon F [options] Options: --city NAME City to geocode (or TCLOCK_WEATHER_CITY) --lat F --lon F Explicit coordinates (skips geocoding) --days N Forecast days, 1-16 (default 3) --current-only Print only current conditions --units UNIT metric (default) or imperial --theme NAME default|evangelion|nerv (or TCLOCK_WIDGET_THEME) --json Print normalized JSON instead of a text block --cache-secs N Cache TTL in seconds (default 900; 0 disables) --no-cache Ignore and do not write the cache --no-color Do not emit ANSI color (NO_COLOR is also honored) --timeout N Network timeout in seconds (default 10) -h, --help Show this help USAGE } urlencode() { # LC_ALL=C makes ${s:i:1} iterate bytes, not codepoints, so multibyte # UTF-8 input percent-encodes correctly ("S%C3%A3o", never "S%E3o"). local LC_ALL=C local s=$1 out='' c h i for ((i = 0; i < ${#s}; i++)); do c=${s:i:1} case "$c" in [a-zA-Z0-9.~_-]) out+=$c ;; ' ') out+='+' ;; *) printf -v h '%%%02X' "'$c"; out+=$h ;; esac done printf '%s' "$out" } wmo_label() { case "$1" in 0) printf 'Clear' ;; 1) printf 'Mostly clear' ;; 2) printf 'Partly cloudy' ;; 3) printf 'Overcast' ;; 45 | 48) printf 'Fog' ;; 51 | 53 | 55) printf 'Drizzle' ;; 56 | 57) printf 'Freezing drizzle' ;; 61 | 63 | 65) printf 'Rain' ;; 66 | 67) printf 'Freezing rain' ;; 71 | 73 | 75) printf 'Snow' ;; 77) printf 'Snow grains' ;; 80 | 81 | 82) printf 'Rain showers' ;; 85 | 86) printf 'Snow showers' ;; 95) printf 'Thunderstorm' ;; 96 | 99) printf 'Thunderstorm with hail' ;; *) printf 'Unknown' ;; esac } wmo_glyph() { case "$1" in 0) printf '☀' ;; 1) printf '🌤' ;; 2) printf '⛅' ;; 3) printf '☁' ;; 45 | 48) printf '🌫' ;; 51 | 53 | 55 | 56 | 57) printf '🌦' ;; 61 | 63 | 65 | 66 | 67 | 80 | 81 | 82) printf '🌧' ;; 71 | 73 | 75 | 77 | 85 | 86) printf '❄' ;; 95 | 96 | 99) printf '⛈' ;; *) printf '·' ;; esac } # Zeller's congruence; prints 0=Sat, 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri. weekday_from_iso() { local rest=${1%-*} local y y=$((10#${rest%-*})) local m m=$((10#${rest##*-})) local d d=$((10#${1##*-})) case "$m" in 1 | 2) m=$((m + 12)) y=$((y - 1)) ;; esac local k=$((y % 100)) j=$((y / 100)) printf '%s' "$(((d + (13 * (m + 1)) / 5 + k + k / 4 + j / 4 + 5 * j) % 7))" } weekday_name() { case "$1" in 0) printf 'Sat' ;; 1) printf 'Sun' ;; 2) printf 'Mon' ;; 3) printf 'Tue' ;; 4) printf 'Wed' ;; 5) printf 'Thu' ;; 6) printf 'Fri' ;; esac } # Locale-independent rounding of an API decimal string (drops the fraction). round_number() { local v=$1 sign='' int='' frac='' d if [ -z "$v" ]; then printf '0' return 0 fi case "$v" in -*) sign='-' v=${v#-} ;; esac int=${v%%.*} case "$v" in *.*) frac=${v#*.} ;; esac if [ -z "$int" ]; then int=0; fi if [ -n "$frac" ]; then d=${frac:0:1} if [[ "$d" =~ [0-9] ]] && [ "$d" -ge 5 ]; then int=$((int + 1)); fi fi printf '%s%s' "$sign" "$int" } # read_lines NAME "$newline_separated" -> fills global array NAME (bash 3.2 safe) read_lines() { local name=$1 line i=0 eval "$name=()" while IFS= read -r line; do eval "$name[$i]=\$line" i=$((i + 1)) done <<<"$2" } parse_args() { CITY="${TCLOCK_WEATHER_CITY:-}" UNITS="${TCLOCK_WEATHER_UNITS:-$DEFAULT_UNITS}" THEME="${TCLOCK_WIDGET_THEME:-$DEFAULT_THEME}" DAYS=$DEFAULT_DAYS TIMEOUT=$DEFAULT_TIMEOUT CACHE_SECS=$DEFAULT_CACHE_SECS if [ -n "${NO_COLOR:-}" ]; then NO_COLOR_FLAG=1; fi while [ $# -gt 0 ]; do case "$1" in --city) if [ $# -lt 2 ]; then die "--city requires a value"; fi CITY=$2 shift 2 ;; --lat) if [ $# -lt 2 ]; then die "--lat requires a value"; fi LAT=$2 shift 2 ;; --lon) if [ $# -lt 2 ]; then die "--lon requires a value"; fi LON=$2 shift 2 ;; --days) if [ $# -lt 2 ]; then die "--days requires a value"; fi DAYS=$2 shift 2 ;; --units) if [ $# -lt 2 ]; then die "--units requires a value"; fi UNITS=$2 shift 2 ;; --theme) if [ $# -lt 2 ]; then die "--theme requires a value"; fi THEME=$2 shift 2 ;; --cache-secs) if [ $# -lt 2 ]; then die "--cache-secs requires a value"; fi CACHE_SECS=$2 shift 2 ;; --timeout) if [ $# -lt 2 ]; then die "--timeout requires a value"; fi TIMEOUT=$2 shift 2 ;; --current-only) CURRENT_ONLY=1 shift ;; --json) OUTPUT_JSON=1 shift ;; --no-cache) NO_CACHE=1 shift ;; --no-color) NO_COLOR_FLAG=1 shift ;; -h | --help) usage exit 0 ;; -*) die "unknown option '$1' (see --help)" ;; *) if [ -n "$CITY" ]; then die "unexpected argument '$1'"; fi CITY=$1 shift ;; esac done validate } validate() { if ! [[ "$DAYS" =~ ^[0-9]+$ ]] || [ "$DAYS" -lt 1 ] || [ "$DAYS" -gt "$MAX_DAYS" ]; then die "invalid --days '$DAYS': expected an integer from 1 to $MAX_DAYS" fi if ! [[ "$TIMEOUT" =~ ^[0-9]+$ ]] || [ "$TIMEOUT" -lt 1 ]; then die "invalid --timeout '$TIMEOUT': expected a positive integer" fi if ! [[ "$CACHE_SECS" =~ ^[0-9]+$ ]]; then die "invalid --cache-secs '$CACHE_SECS': expected a non-negative integer" fi case "$UNITS" in metric | imperial) ;; *) die "invalid --units '$UNITS': expected metric or imperial" ;; esac if [ -n "$LAT" ] || [ -n "$LON" ]; then if [ -z "$LAT" ] || [ -z "$LON" ]; then die "both --lat and --lon are required"; fi if ! [[ "$LAT" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then die "invalid --lat '$LAT': expected a number"; fi if ! [[ "$LON" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then die "invalid --lon '$LON': expected a number"; fi fi if [ -z "$CITY" ] && { [ -z "$LAT" ] || [ -z "$LON" ]; }; then die "no location: pass --city NAME or --lat/--lon" fi } have_jq() { command -v jq >/dev/null 2>&1; } json_object() { local out out=$(printf '%s' "$1" | tr -d '\n' | grep -oE "\"$2\"[[:space:]]*:[[:space:]]*\{[^}]*\}" | head -n1 | sed -E 's/^[^{]*\{//; s/\}[^{}]*$//') || true printf '%s' "$out" } json_field_from() { local out out=$(printf '%s' "$1" | grep -oE "\"$2\"[[:space:]]*:[[:space:]]*[^,}]*" | head -n1 | sed -E 's/^[^:]*:[[:space:]]*//; s/^"//; s/"[[:space:]]*$//; s/[[:space:]]*$//') || true printf '%s' "$out" } json_array_from() { local out out=$(printf '%s' "$1" | grep -oE "\"$2\"[[:space:]]*:[[:space:]]*\[[^]]*\]" | head -n1 | sed -E 's/^[^[]*\[//; s/\][^]]*$//' | tr ',' '\n' | sed -E 's/^[[:space:]]*"?//; s/"?[[:space:]]*$//') || true printf '%s' "$out" } json_first_result_field() { local out out=$(printf '%s' "$1" | tr -d '\n' | sed -E 's/.*"results"[[:space:]]*:[[:space:]]*\[//' | grep -oE "\"$2\"[[:space:]]*:[[:space:]]*[^,}]*" | head -n1 | sed -E 's/^[^:]*:[[:space:]]*//; s/^"//; s/"[[:space:]]*$//; s/[[:space:]]*$//') || true printf '%s' "$out" } extract_geocode_field() { if have_jq; then printf '%s' "$1" | jq -r ".results[0].$2 // empty" else json_first_result_field "$1" "$2" fi } get_current_field() { if have_jq; then printf '%s' "$1" | jq -r ".current.$2 // empty" else json_field_from "$(json_object "$1" current)" "$2" fi } get_daily_array() { if have_jq; then printf '%s' "$1" | jq -r ".daily.$2[]? | tostring" else json_array_from "$(json_object "$1" daily)" "$2" fi } get_location_field() { if have_jq; then printf '%s' "$1" | jq -r ".location.$2 // empty" else json_field_from "$(json_object "$1" location)" "$2" fi } json_quote() { local s=$1 s=${s//\\/\\\\} s=${s//\"/\\\"} printf '"%s"' "$s" } http_get() { curl --fail --silent --show-error --max-time "$TIMEOUT" "$1" } resolve_location() { if [ -n "$LAT" ] && [ -n "$LON" ]; then LOC_LAT=$LAT LOC_LON=$LON if [ -n "$CITY" ]; then LOC_NAME=$CITY; else LOC_NAME="$LAT,$LON"; fi return 0 fi local url response name lat lon url="$GEOCODE_URL?name=$(urlencode "$CITY")&count=1&language=en&format=json" response=$(http_get "$url") || die "could not reach Open-Meteo geocoding (timeout ${TIMEOUT}s); check your network" name=$(extract_geocode_field "$response" name) lat=$(extract_geocode_field "$response" latitude) lon=$(extract_geocode_field "$response" longitude) if [ -z "$lat" ] || [ -z "$lon" ]; then die "city '$CITY' not found; check the spelling or pass --lat/--lon" fi LOC_NAME=${name:-$CITY} LOC_LAT=$lat LOC_LON=$lon } fetch_forecast() { local params params="latitude=$LOC_LAT&longitude=$LOC_LON&timezone=auto" params="$params¤t=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m" if [ "$CURRENT_ONLY" -eq 0 ]; then params="$params&daily=weather_code,temperature_2m_max,temperature_2m_min&forecast_days=$DAYS" fi if [ "$UNITS" = imperial ]; then params="$params&temperature_unit=fahrenheit&wind_speed_unit=mph" else params="$params&temperature_unit=celsius&wind_speed_unit=kmh" fi FORECAST_JSON=$(http_get "$FORECAST_URL?$params") || die "could not reach Open-Meteo forecast (timeout ${TIMEOUT}s); check your network" } build_daily_json() { local dates codes maxs mins dates=$(get_daily_array "$FORECAST_JSON" time) codes=$(get_daily_array "$FORECAST_JSON" weather_code) maxs=$(get_daily_array "$FORECAST_JSON" temperature_2m_max) mins=$(get_daily_array "$FORECAST_JSON" temperature_2m_min) [ -n "$dates" ] || die "unexpected response from Open-Meteo (no daily forecast); check the service or retry" local D C X N i n wd read_lines D "$dates" read_lines C "$codes" read_lines X "$maxs" read_lines N "$mins" n=${#D[@]} local out_t='' out_w='' out_c='' out_x='' out_n='' for ((i = 0; i < n; i++)); do if [ "$i" -eq 0 ]; then wd=Today; else wd=$(weekday_name "$(weekday_from_iso "${D[$i]}")"); fi if [ "$i" -gt 0 ]; then out_t+=', '; out_w+=', '; out_c+=', '; out_x+=', '; out_n+=', ' fi out_t+="$(json_quote "${D[$i]}")" out_w+="$(json_quote "$wd")" out_c+="${C[$i]:-0}" out_x+="${X[$i]:-0}" out_n+="${N[$i]:-0}" done printf '{"time": [%s], "weekday": [%s], "weather_code": [%s], "temperature_2m_max": [%s], "temperature_2m_min": [%s]}' \ "$out_t" "$out_w" "$out_c" "$out_x" "$out_n" } build_normalized() { local temp app hum code wind temp=$(get_current_field "$FORECAST_JSON" temperature_2m) app=$(get_current_field "$FORECAST_JSON" apparent_temperature) hum=$(get_current_field "$FORECAST_JSON" relative_humidity_2m) code=$(get_current_field "$FORECAST_JSON" weather_code) wind=$(get_current_field "$FORECAST_JSON" wind_speed_10m) if [ -z "$temp" ] || [ -z "$code" ]; then die "unexpected response from Open-Meteo; check the service or retry" fi local daily='{"time": [], "weekday": [], "weather_code": [], "temperature_2m_max": [], "temperature_2m_min": []}' if [ "$CURRENT_ONLY" -eq 0 ]; then daily=$(build_daily_json) fi printf '{\n' printf ' "location": {"name": %s, "latitude": %s, "longitude": %s},\n' \ "$(json_quote "$LOC_NAME")" "$LOC_LAT" "$LOC_LON" printf ' "current": {"temperature_2m": %s, "apparent_temperature": %s, "relative_humidity_2m": %s, "weather_code": %s, "wind_speed_10m": %s},\n' \ "$temp" "$app" "$hum" "$code" "$wind" printf ' "daily": %s\n' "$daily" printf '}\n' } theme_code() { case "$1:$2" in evangelion:title) printf '\033[1;35m' ;; evangelion:accent) printf '\033[38;5;150m' ;; nerv:title) printf '\033[1;31m' ;; nerv:accent) printf '\033[32m' ;; *:title) printf '\033[1;36m' ;; *:accent) printf '\033[1;33m' ;; *) printf '\033[0m' ;; esac } color_for() { if [ "$NO_COLOR_FLAG" -eq 1 ]; then printf '' return 0 fi theme_code "$1" "$2" } render() { local temp app hum code wind cond glyph name unit wunit temp=$(get_current_field "$NORMALIZED" temperature_2m) app=$(get_current_field "$NORMALIZED" apparent_temperature) hum=$(get_current_field "$NORMALIZED" relative_humidity_2m) code=$(get_current_field "$NORMALIZED" weather_code) wind=$(get_current_field "$NORMALIZED" wind_speed_10m) name=$(get_location_field "$NORMALIZED" name) cond=$(wmo_label "$code") glyph=$(wmo_glyph "$code") unit='°C' wunit='km/h' if [ "$UNITS" = imperial ]; then unit='°F' wunit='mph' fi local title accent reset title=$(color_for "$THEME" title) accent=$(color_for "$THEME" accent) reset=$(color_for "$THEME" reset) printf '%s%s%s %s%s%s · feels %s · %s %s\n' \ "$title" "$name" "$reset" \ "$accent" "$(round_number "$temp")$unit" "$reset" \ "$(round_number "$app")$unit" "$cond" "$glyph" printf 'Humidity %s%% · Wind %s %s\n' "$(round_number "$hum")" "$(round_number "$wind")" "$wunit" if [ "$CURRENT_ONLY" -eq 0 ]; then local dates wds codes maxs mins D W C X N i n dates=$(get_daily_array "$NORMALIZED" time) wds=$(get_daily_array "$NORMALIZED" weekday) codes=$(get_daily_array "$NORMALIZED" weather_code) maxs=$(get_daily_array "$NORMALIZED" temperature_2m_max) mins=$(get_daily_array "$NORMALIZED" temperature_2m_min) read_lines D "$dates" read_lines W "$wds" read_lines C "$codes" read_lines X "$maxs" read_lines N "$mins" n=${#D[@]} for ((i = 0; i < n; i++)); do printf '%s%-7s%s %s/%s %s\n' \ "$accent" "${W[$i]}" "$reset" \ "$(round_number "${X[$i]}")°" "$(round_number "${N[$i]}")°" \ "$(wmo_label "${C[$i]}")" done fi } file_mtime() { local m m=$(stat -c %Y "$1" 2>/dev/null) || m=$(stat -f %m "$1" 2>/dev/null) || m=0 case "$m" in '' | *[!0-9]*) m=0 ;; esac printf '%s' "$m" } cache_file() { local base if [ -n "$LAT" ] && [ -n "$LON" ]; then base="${LAT}_${LON}"; else base="$CITY"; fi base=$(printf '%s' "$base" | tr -c 'A-Za-z0-9._-' '_') printf '%s/tclock-weather/%s_%s_%s_%s.json' "${XDG_CACHE_HOME:-$HOME/.cache}" "$base" "$DAYS" "$UNITS" "$CURRENT_ONLY" } cache_get() { if [ "$NO_CACHE" -eq 1 ]; then return 1; fi if [ "$CACHE_SECS" -le 0 ]; then return 1; fi local file mtime now file=$(cache_file) if [ ! -f "$file" ]; then return 1; fi mtime=$(file_mtime "$file") now=$(date +%s) if [ $((now - mtime)) -ge "$CACHE_SECS" ]; then return 1; fi cat "$file" } cache_put() { if [ "$NO_CACHE" -eq 1 ]; then return 0; fi if [ "$CACHE_SECS" -le 0 ]; then return 0; fi local file file=$(cache_file) mkdir -p "$(dirname "$file")" 2>/dev/null || return 0 printf '%s' "$1" >"$file" 2>/dev/null || true } main() { parse_args "$@" local cached if cached=$(cache_get); then NORMALIZED=$cached else resolve_location fetch_forecast NORMALIZED=$(build_normalized) cache_put "$NORMALIZED" fi if [ "$OUTPUT_JSON" -eq 1 ]; then printf '%s\n' "$NORMALIZED" else render fi } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then main "$@" fi