fixed script. added menu when searching locations

This commit is contained in:
KeeganForelight 2023-01-13 20:42:42 -05:00
parent 4e40191ee9
commit bc31044771
10 changed files with 226 additions and 663 deletions

View File

@ -1,48 +0,0 @@
"113": "Sunny",
"116": "PartlyCloudy",
"119": "Cloudy",
"122": "VeryCloudy",
"143": "Fog",
"176": "LightShowers",
"179": "LightSleetShowers",
"182": "LightSleet",
"185": "LightSleet",
"200": "ThunderyShowers",
"227": "LightSnow",
"230": "HeavySnow",
"248": "Fog",
"260": "Fog",
"263": "LightShowers",
"266": "LightRain",
"281": "LightSleet",
"284": "LightSleet",
"293": "LightRain",
"296": "LightRain",
"299": "HeavyShowers",
"302": "HeavyRain",
"305": "HeavyShowers",
"308": "HeavyRain",
"311": "LightSleet",
"314": "LightSleet",
"317": "LightSleet",
"320": "LightSnow",
"323": "LightSnowShowers",
"326": "LightSnowShowers",
"329": "HeavySnow",
"332": "HeavySnow",
"335": "HeavySnowShowers",
"338": "HeavySnow",
"350": "LightSleet",
"353": "LightShowers",
"356": "HeavyShowers",
"359": "HeavyRain",
"362": "LightSleetShowers",
"365": "LightSleetShowers",
"368": "LightSnowShowers",
"371": "HeavySnowShowers",
"374": "LightSleetShowers",
"377": "LightSleet",
"386": "ThunderyShowers",
"389": "ThunderyHeavyRain",
"392": "ThunderySnowShowers",
"395": "HeavySnowShowers",

View File

@ -1,5 +0,0 @@
module weather
go 1.18
require github.com/joho/godotenv v1.4.0 // indirect

View File

@ -1,2 +0,0 @@
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=

View File

@ -1,112 +0,0 @@
package main
import (
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/joho/godotenv"
)
type Weather struct {
Temp float64
Humidity int
Icon rune
City string
LastPinged int64
}
type weathercode rune
const (
CLEAR_DAY weathercode = '\ue30d'
CLEAR_NIGHT weathercode = '\ue32b'
PARTLY_CLOUDY_DAY weathercode = '\ue302'
PARTLY_CLOUDY_NIGHT weathercode = '\ue379'
CLOUDY weathercode = '\ue312'
RAIN weathercode = '\ue318'
THUNDERSTORM weathercode = '\ue31d'
SNOW weathercode = '\ue31a'
FOG weathercode = '\ue313'
DEGREES_F weathercode = '\ue341'
HUMIDITY weathercode = '\ue373'
)
func (w *Weather) String() string {
return fmt.Sprintf(" %c %.1f%c %d%c in %s", w.Icon, w.Temp, DEGREES_F, w.Humidity, HUMIDITY, w.City) // Output as ICON ##.#*F ##% in City, ST where the rune is a degree sign
}
func main() {
// getting weather
if err := exec.Command(os.ExpandEnv("$HOME/.dotfiles/bin/weather/weather.sh")).Run(); err != nil {
panic(err)
}
// get up to date info
loc := os.ExpandEnv(fmt.Sprintf("$HOME/.dotfiles/bin/weather/.env.location"))
weath := os.ExpandEnv(fmt.Sprintf("$HOME/.dotfiles/bin/weather/.env.weather"))
if err := godotenv.Load(weath, loc); err != nil {
panic(err)
}
var humidity int
var temp float64
var err error
city := os.Getenv("CITY")
icon := getIcon(os.Getenv("ICON"))
h := os.Getenv("HUMIDITY")
t := os.Getenv("TEMP")
if h != "" {
hum, err := strconv.ParseInt(h, 10, 64)
if err != nil {
panic(err)
}
humidity = int(hum)
}
if t != "" {
temp, err = strconv.ParseFloat(t, 64)
if err != nil {
panic(err)
}
}
weather := &Weather{City: city, Icon: icon, Humidity: humidity, Temp: temp}
fmt.Print(weather)
}
func tod(day bool, dayrune weathercode, nightrune weathercode) rune {
if day {
return rune(dayrune)
}
return rune(nightrune)
}
func getIcon(code string) rune {
weather := strings.Trim(code, "nd") // trimming day or night tag
var day bool
if strings.Contains(code, "d") {
day = true
} else {
day = false
}
switch weather {
case "01":
return tod(day, CLEAR_DAY, CLEAR_NIGHT) // clear skies
case "02", "03":
return tod(day, PARTLY_CLOUDY_DAY, PARTLY_CLOUDY_NIGHT) // small clouds
case "04":
return rune(CLOUDY) // big clouds with sun
case "09", "10":
return rune(RAIN)
case "11":
return rune(THUNDERSTORM)
case "13":
return rune(SNOW)
case "50":
return rune(FOG)
default:
return '\uFFFD' // question mark
}
}

View File

@ -1,189 +0,0 @@
#!/bin/bash
#source "$HOME/.dotfiles/.priv/key"
#source "$HOME/.dotfiles/bin/weather/.env.location"
#source "$HOME/.dotfiles/bin/weather/.env.weather"
# API_KEY=$(cat "$HOME/.dotfiles/bin/weather/.priv/key")
# getting weather
CUR_TIMESTAMP=$(date +%s)
# only update weather every 30 seconds
if [[ $CUR_TIMESTAMP -gt $EXPIRATION || -z $EXPIRATION ]] ; then
WEATHER=$(curl --silent "http://wttr.in/${LOCATION}?format=j2" | gojq -r '.current_condition[0]')
echo $WEATHER
TEMP=$(echo $WEATHER | gojq -r '.temp_F')
HUMIDITY=$(echo $WEATHER | gojq -r '.humidity')
ICON=$(echo $WEATHER | gojq -r '.weatherCode')
EXPIRATION=$(($CUR_TIMESTAMP+30))
echo "TEMP: $TEMP HUMIDITY: $HUMIDITY ICON: $ICON"
#printf 'TEMP=%s\nHUMIDITY=%s\nICON=%s\nEXPIRATION=%s\n' "$TEMP" "$HUMIDITY" "$ICON" "$EXPIRATION" >"$HOME/.dotfiles/bin/weather/.env.weather"
fi
#!/usr/bin/env bash
WEATHER_DIR="${HOME}/.dotfiles/bin/weather"
usage() {
cat <<EOF
Usage: wttr [-s] [-d] [-u] [-i] [-f] [-h]
Queries the weather and outputs it in a Nerd Font compaitable way
Options:
-p, --print print the current weather information
-s, --setloc=<LOC> change location used for wttr.in query
will use IP if left blank
-d, --disploc=<LOC> show location used in query
-f, --force force refresh weather data
-h, --help Show this help message
EOF
}
get_wttr() {
if [[ -z "$ZONE" || ! -z "$UPDATE" ]] ; then
# getting grid points
url="https://api.weather.gov/points/$LATITUDE,$LONGITUDE"
GRID=$(curl --silent -fL "$url")
query="{\
zone: .properties.forecastZone,\
city: .properties.relativeLocation.properties.city,\
state: .properties.relativeLocation.properties.state}"
res=$(echo "$GRID" | gojq "$query")
echo "$res"
CITY=$(echo "$res" | gojq '.city')
STATE=$(echo "$res" | gojq '.state')
ZONE=$(echo "$res" | gojq '.zone' | tr -d '"')
fi
WEATHER=$(curl --silent -fL "$ZONE/observations" | gojq '.features[0].properties')
query="{\
temp: .temperature.value,\
humidity: .relativeHumidity.value,\
icon: .icon}"
PARSED=$(echo "$WEATHER" | gojq "$query")
TEMP=$(echo "$PARSED" | gojq '.temp')
TEMP=$(echo "$TEMP * (9/5) + 32" | bc -l)
HUMIDITY=$(echo "$PARSED" | gojq '.humidity')
TOD=$(echo "$PARSED" | gojq '.icon' | awk -F / '{print $6}')
ICON=$(echo "$PARSED" | gojq '.icon' | awk -F / '{print $7}' | awk -F ? '{print $1}')
EXPIRATION=$(($(date +%s) + 60))
printf 'TEMP=%s\nHUMIDITY=%s\nICON=%s\nLOCATION=%s\nZONE=%s\nCITY=%s\nSTATE=%s\nTOD=%s\nEXPIRATION=%s\n' "$TEMP" "$HUMIDITY" "$ICON" "$LOCATION" "$ZONE" "$CITY" "$STATE" "$TOD" "$EXPIRATION" > ${WEATHER_DIR}/.weather
####
# below is WTTR impl, using NWS above
####
# gets weather for $LOCATION and stores it into file with timestamp
# url="https://wttr.in/?format=j1&nonce=$RANDOM"
# FULL_WTTR=$(curl --silent -fL "$url")
# # parse relevant info
# query="{\
# temp_F: .current_condition[0].temp_F,\
# temp_C: .current_condition[0].temp_C,\
# humidity: .current_condition[0].humidity,\
# conditions: .current_condition[0].weatherCode,\
# location: .nearest_area[0].areaName[0].value,\
# sunset: .weather[0].astronomy[0].sunset,\
# sunrise: .weather[1].astronomy[0].sunrise}"
# WTTR=$(echo "$FULL_WTTR" | gojq "$query")
# # Parsing info
# TEMP=$(echo "$WTTR" | gojq .temp_"$UNITS")
# HUMIDITY=$(echo "$WTTR" | gojq '.humidity')
# CONDITIONS=$(echo "$WTTR" | gojq '.conditions')
# LOCATION=$(echo "$WTTR" | gojq '.location')
# # TOD info
# SUNSET=$(echo "$WTTR" | gojq '.sunset' | tr -d ' "')
# SUNRISE=$(echo "$WTTR" | gojq '.sunrise' | tr -d ' "')
# # getting TOD
# get_tod
# # setting symbol
# # updating weather info
# printf 'UNITS=%s\nTEMP=%s\nHUMIDITY=%s\nCONDITIONS=%s\nLOCATION=%s\nEXPIRATION=%s\nTOD=%s\n' "$UNITS" "$TEMP" "$HUMIDITY" "$CONDITIONS" "$LOCATION" "$EXPIRATION" "$TOD" > ${WEATHER_DIR}/.weather
}
set_location() {
# updates location of weather query to $new_loc, can be empty
LOCATION="$new_loc"
UPDATE="true"
url="https://v2.wttr.in/$LOCATION?format=j1"
query="{\
lat: .nearest_area[0].latitude,\
lon: .nearest_area[0].longitude}"
WTTR=$(curl --silent -fL "$url" | gojq "$query")
# Grabbing env vars
LATITUDE=$(echo "$WTTR" | gojq '.lat' | tr -d ' "')
LONGITUDE=$(echo "$WTTR" | gojq '.lon' | tr -d ' "')
get_wttr
}
display_location() {
# updates location to display to $disp_loc
printf 'Searching %s, (%s, %s)\n' "$LOCATION" "$CITY" "$STATE"
}
load_wttr() {
# loads and checks weather
if [[ ! -f ${WEATHER_DIR}/.weather ]] ; then
# file doesnt exist
UNITS="F" # defaults to farenheit
get_wttr
fi
# load env
source ${WEATHER_DIR}/.weather
# check for expiration
if [[ $(date +%s) -ge $EXPIRATION ]] ; then
get_wttr
fi
}
print_wttr() {
# stripping and reformatting quotations
query=$(printf '.%s.%s' $TOD $ICON)
SYMBOL=$(cat ${WEATHER_DIR}/symbols.json | gojq "$query" | tr -d '"')
UNIT=$(echo -e "\ufa04")
HUMID_SYMB=$(echo -e "\ue373")
printf '%s %.1f%s %0.1f %s in %s, %s\n' "$SYMBOL" "$TEMP" "$UNIT" "$HUMIDITY" "$HUMID_SYMB" "$CITY" "$STATE"
}
load_wttr
while [[ "$1" != "" ]]; do
case $1 in
-h | --help)
usage
;;
-p | --print)
print_wttr
;;
-s | --setloc)
shift
new_loc="$1"
set_location
;;
-d | --disploc)
shift
display_location
;;
-f | --force)
get_wttr
;;
*)
echo "Error: wttr $@"
usage
;;
esac
shift
done

View File

@ -1,11 +0,0 @@
#!/usr/bin/env bash
# prints all symbols that can be used to test output with font
echo -e '\ue30d Clear (Day)'
echo -e '\ue32b Clear (Night)'
echo -e '\ue302 Partly Cloud (Day)'
echo -e '\ue379 Partly Cloudy (Night)'
echo -e '\ue312 Cloud'
echo -e '\ue318 Rain'
echo -e '\ue31d Thunderstorm'
echo -e '\ue31a Snow'
echo -e '\ue313 Fog'

View File

@ -1,56 +0,0 @@
package main
import "fmt"
var WeatherCodesDay map[string]rune
var WeatherCodesNight map[string]rune
func SymbolTest() {
WeatherCodesDay := map[string]rune{
"Unkown": '\ue374',
"Cloudy": '\ue302',
"Fog": '\ue303',
"HeavyRain": '\ue318',
"HeavyShowers": '\ue318',
"HeavySnow": '\ue31a',
"HeavySnowShowers": '\ue31a',
"LightRain": '\ue308',
"LightShowers": '\ue308',
"LightSleet": '\ue3aa',
"LightSleetShowers": '\ue3aa',
"LightSnow": '\ue30a',
"LightSnowShowers": '\ue30a',
"PartlyCloudy": '\ue37b',
"Sunny": '\ue30d',
"ThunderyHeavyRain": '\ue31d',
"ThunderyShowers": '\ue31d',
"ThunderySnowShowers": '\ue365',
"VeryCloudy": '\ue312',
}
WeatherCodesNight := map[string]rune{
"Unkown": '\ue374',
"Cloudy": '\ue37e',
"Fog": '\ue346',
"HeavyRain": '\ue318',
"HeavyShowers": '\ue318',
"HeavySnow": '\ue31a',
"HeavySnowShowers": '\ue31a',
"LightRain": '\ue325',
"LightShowers": '\ue325',
"LightSleet": '\ue3ac',
"LightSleetShowers": '\ue3ac',
"LightSnow": '\ue361',
"LightSnowShowers": '\ue361',
"PartlyCloudy": '\ue379',
"Sunny": '\ue32b',
"ThunderyHeavyRain": '\ue31d',
"ThunderyShowers": '\ue31d',
"ThunderySnowShowers": '\ue366',
"VeryCloudy": '\ue312',
}
for k, v := range WeatherCodesDay {
fmt.Printf("%s: %c %c\n", k, v, WeatherCodesNight[k])
}
}

View File

@ -1,143 +0,0 @@
#!/usr/bin/env bash
usage() {
cat <<EOF
Usage: wttr [-s] [-d] [-u] [-i] [-f] [-h]
Queries the weather and outputs it in a Nerd Font compaitable way
Options:
-p, --print print the current weather information
-s, --setloc=<LOC> change location used for wttr.in query
will use IP if left blank
-d, --disploc=<LOC> show location used in query
-f, --force force refresh weather data
-h, --help Show this help message
EOF
}
WORKING_DIR="$HOME/.local/share/weather"
WEATHER_FILE="$WORKING_DIR/.weather"
SYMBOL_FILE="$WORKING_DIR/symbols.json"
# timeout in seconds
TIMEOUT=60
get_wttr() {
if [[ -n "$ZONE_URL" && -z "$UPDATE" ]] ; then
# will default to IP
set_location
fi
if [[ -z "$ZONE_URL" || -n "$UPDATE" ]] ; then
# getting grid points if update or zone is empty
url="https://api.weather.gov/points/$LATITUDE,$LONGITUDE"
GRID=$(curl --silent -fL "$url")
query="{\
station: .properties.observationStations,\
city: .properties.relativeLocation.properties.city,\
state: .properties.relativeLocation.properties.state}"
res=$(echo "$GRID" | gojq "$query")
CITY=$(echo "$res" | gojq '.city')
STATE=$(echo "$res" | gojq '.state')
STATION_URL=$(echo "$res" | gojq '.station' | tr -d '"')
OBSERVATION_URL=$(curl --silent -fL "$STATION_URL" | gojq '.observationStations[0]' | tr -d '"')
fi
WEATHER=$(curl --silent -fL "$OBSERVATION_URL/observations/latest" | gojq '.features[]')
echo "$WEATHER" | gojq '.'
query="{\
temp: .temperature.value,\
humidity: .relativeHumidity.value,\
icon: .icon}"
PARSED=$(echo "$WEATHER" | gojq "$query")
TEMP=$(echo "$PARSED" | gojq '.temp')
# C -> F, unit check eventually
TEMP=$(echo "$TEMP * (9/5) + 32" | bc -l)
HUMIDITY=$(echo "$PARSED" | gojq '.humidity')
#echo "$PARSED" | gojq '.'
TOD=$(echo "$PARSED" | gojq '.icon' | awk -F / '{print $6}')
ICON=$(echo "$PARSED" | gojq '.icon' | awk -F / '{print $7}' | awk -F ? '{print $1}')
EXPIRATION=$(($(date +%s) + $TIMEOUT))
printf 'TEMP=%s\nHUMIDITY=%s\nICON=%s\nLOCATION=%s\nZONE_URL=%s\nCITY=%s\nSTATE=%s\nTOD=%s\nEXPIRATION=%s\n' "$TEMP" "$HUMIDITY" "$ICON" "$LOCATION" "$ZONE_URL" "$CITY" "$STATE" "$TOD" "$EXPIRATION" > "$WEATHER_FILE"
}
set_location() {
# updates location of weather query to $new_loc, can be empty
LOCATION="$1"
UPDATE="true"
url="https://v2.wttr.in/$LOCATION?format=j1"
query="{\
lat: .nearest_area[0].latitude,\
lon: .nearest_area[0].longitude}"
WTTR=$(curl --silent -fL "$url" | gojq "$query")
# Grabbing env vars
LATITUDE=$(echo "$WTTR" | gojq '.lat' | tr -d ' "')
LONGITUDE=$(echo "$WTTR" | gojq '.lon' | tr -d ' "')
get_wttr
}
display_location() {
# updates location to display to $disp_loc
printf 'Searching %s, (%s, %s)\n' "$LOCATION" "$CITY" "$STATE"
}
load_wttr() {
# loads and checks weather
# load env, error on new install
source "$WEATHER_FILE" 2>/dev/null
# check for expiration
if [[ $(date +%s) -ge $EXPIRATION ]] ; then
get_wttr
fi
}
print_wttr() {
# stripping and reformatting quotations
if [[ -n "$TOD" && -n "$ICON" ]] ; then
query=$(printf '.%s.%s' $TOD $ICON)
SYMBOL=$(cat "$SYMBOL_FILE" | gojq "$query" | tr -d '"')
fi
UNIT=$(echo -e "\ufa04")
HUMID_SYMB=$(echo -e "\ue373")
printf '%s %.1f%s %0.1f %s in %s, %s\n' "$SYMBOL" "$TEMP" "$UNIT" "$HUMIDITY" "$HUMID_SYMB" "$CITY" "$STATE"
}
load_wttr
while [[ "$1" != "" ]]; do
case $1 in
-h | --help)
usage
;;
-p | --print)
print_wttr
;;
-s | --setloc)
shift
set_location "$1"
;;
-d | --disploc)
shift
display_location
;;
-f | --force)
get_wttr
;;
*)
echo "Error: wttr $@"
usage
;;
esac
shift
done

View File

@ -3,25 +3,44 @@
# client version, calls server for actual API info
usage() {
cat <<EOF
usage: $0 [-c COORD_PAIR][-s QUERY][-z ZIPCODE][-u <c|f>]
usage: $0 [-p][-s QUERY | -z ZIPCODE][-u <c|f>][-i][-h]
Queries OpenWeatherMapAPI for weather or lat/long
options:
-c, --coords searches for weather based on COORD_PAIR
-z, --zipcode returns the coordinate pair(s) for given zipcode
-s, --search returns the coordinate pair(s) for QUERY
-p, --pretty enables nerdfont symbols
-z, --zipcode returns the weather for ZIPCODE
-s, --search returns the weather for QUERY
-u, --units sets the temperature units
-i, --icon_test tests the icons used
-h, --help displays this message
COORD_PAIR is a string of the format "LAT,LON"
QUERY is a city, state or city to search
ZIPCODE sets the location to the given zipcode
to narrow results, include the ISO country code
ex) -z "02139,US"
QUERY sets the location to the search
QUERY format is "CITY,REGION,COUNTRY" where
CITY is any city
REGION is Region or State
COUNTRY is ISO Country Code
to narrow results, try more specific searches
ex) -s "Cambridge" will return places in the UK
ex) -s "Cambridge,US" will return Cambridge, MA
EOF
exit $1
}
WORKING_DIR="$HOME/.local/share/weather"
WEATHER_FILE="$WORKING_DIR/.env"
WEATHER_CALL="ssh spinach@git.keegandeppe.com weather"
TIMEOUT=60 # timeout for info
TIME=$(date +%s)
if [[ ! -d "$WORKING_DIR" ]] ; then
mkdir -p "$WORKING_DIR"
fi
print_weather() {
# prints the weather
@ -29,7 +48,28 @@ print_weather() {
# check to see if it is expired
check_expiration
print "$TEMPERATURE $HUMIDITY in $CITY, $STATE\n"
ST="$STATE"
if [[ $(wc -c <<<"$STATE") -gt 4 ]] ; then
ST=$(printf '%s.' $(head -c 4 <<<"$STATE"))
fi
# trimming state
if [[ "$PRETTY" = true ]] ; then
# print with NF icons
icon=$(get_icon "$WEATHER_ICON")
# checking units
if [[ "$UNIT" == "C" ]] ; then
temp_icon=$(echo -e '\ufa03')
else
temp_icon=$(echo -e '\ufa04')
fi
# printing
printf '%s %.1f%s%d\ue373 in %s, %s\n' $icon $TEMPERATURE "$temp_icon" "$HUMIDITY" "$CITY" "$ST"
else
# default printing
printf "%.1f *$UNIT %d%% Humidity in %s, %s\n" $TEMPERATURE $HUMIDITY "$CITY" "$ST"
fi
# save before exiting
save_info
@ -37,19 +77,68 @@ print_weather() {
check_expiration() {
# checks if the info is expired
get_weather
if [[ $TIME -gt $EXPIRATION ]] ; then
# expired
get_weather
fi
}
get_location() {
# no search, use IP
if [[ -n "$SEARCH" ]] ; then
# searching for user location
if [[ -n "$QUERY" ]] ; then
# search
echo "$SEARCH"
elif [[ -n "$ZIPCODE" ]] ; then
# zipcode
echo "$ZIPCODE"
RESULTS=$($WEATHER_CALL $QUERY | gojq "del(.[].local_names)")
NUM_RESULTS=$(echo "$RESULTS" | gojq '. | length')
SELECTION=0
if [[ $NUM_RESULTS -gt 1 ]] ; then
# create menu for user
for ((i=0; i < $NUM_RESULTS; i++)); do
# adding options
res=$(echo "$RESULTS" | gojq ".[$i]")
name=$(echo "$res" | gojq '.name' | tr -d '"')
state=$(echo "$res" | gojq '.state' | tr -d '"')
country=$(echo "$res" | gojq '.country' | tr -d '"')
opt=$(printf '%s %s, %s' "$name" "$state" "$country")
OPTIONS+=($(($i+1)) "$opt")
done
# executing dialog menu
exec 3>&1
SELECTION=$(dialog \
--title 'Multiple Locations Found!' \
--clear \
--cancel-label 'Exit' \
--ok-label 'Select' \
--menu 'Please select the desired location. If none of the options look correct, try making refining your search by including a country code and/or region' 0 0 4 \
"${OPTIONS[@]}" \
2>&1 1>&3)
exit_status=$?
exec 3>&-
clear
if [[ $exit_status -eq 1 || $exit_satus -eq 255 ]] ; then
# canceled or escaped
echo "Try again: $0 -s 'CITY,REGION,COUNTRY'"
exit 0
fi
# fix index
SELECTION=$(($SELECTION - 1))
fi
# Update info
LAT=$(echo "$RESULTS" | gojq ".[$SELECTION].lat")
LON=$(echo "$RESULTS" | gojq ".[$SELECTION].lon")
CITY=$(echo "$RESULTS" | gojq ".[$SELECTION].name" | tr -d '"')
STATE=$(echo "$RESULTS" | gojq ".[$SELECTION].state" | tr -d '"')
else
# default to IP
# no search, default to user IP
url="http://ip-api.com/csv/?fields=252"
res=$(curl --silent -fL "$url")
LAT=$(awk -F , '{print $5}' <<<"$res")
@ -57,32 +146,41 @@ get_location() {
CITY=$(awk -F , '{print $3}' <<<"$res")
STATE=$(awk -F , '{print $1}' <<<"$res")
fi
# check
if [[ -z "$LAT" || -z "$LON" ]] ; then
echo "No location found!"
exit 1
fi
# force refresh
EXPIRED=0
}
get_weather() {
# calls server for weather based on $LAT, $LONG
# only update weather every 30 seconds
if [[ "$UNITS" =~ ^[Cc]$ ]] ; then
# units set to celsius
UNITS="metric"
else
# imperial
UNITS="imperial"
fi
if [[ -z "$LAT" || -z "$LON" ]] ; then
# no lat or lon
get_location
fi
# only update weather every 30 seconds
if [[ "$UNIT" =~ ^[Cc]$ ]] ; then
# units set to celsius
UNIT="C"
UNITS="metric"
else
# imperial
UNIT="F"
UNITS="imperial"
fi
WEATHER=$($WEATHER_CALL "-c $LAT,$LON -u $UNITS")
echo "$WEATHER" | gojq '.'
TEMPERATURE=$(echo $WEATHER | gojq -r '.main.temp')
HUMIDITY=$(echo $WEATHER | gojq -r '.main.humidity')
WEATHER_ICON=$(echo $WEATHER | gojq -r '.weather[0].icon')
EXPIRATION=$(($(date +%s)+$TIMEOUT))
EXPIRATION=$(($TIME+$TIMEOUT))
}
save_info() {
@ -93,14 +191,91 @@ save_info() {
"CITY=$CITY" \
"STATE=$STATE" \
"TEMPERATURE=$TEMPERATURE" \
"TEMPERATURE_ICON=$TEMPERATURE_ICON" \
"HUMIDITY=$HUMIDITY" \
"WEATHER_ICON=$WEATHER_ICON" \
"EXPIRATION=$EXPIRATION"
"EXPIRATION=$EXPIRATION" > "$WEATHER_FILE"
}
load_info() {
if [[ -e "$
# loads env vars
if [[ ! -e "$WEATHER_FILE" ]] ; then
# generates blank info
save_info
fi
source $WEATHER_FILE
}
get_icon() {
# sets NF symbols
tod=$(echo "$1" | sed --expression='s/[0-9]//g')
conditions=$(echo "$1" | sed --expression='s/[^0-9]//g')
# getting icon
if [[ "$tod" == "d" ]] ; then
# day icons
case "$conditions" in
"01") echo -e '\ue30d' ;; # clear
"02") echo -e '\ue30c' ;; # scattered clouds
"03") echo -e '\ue302' ;; # broken clouds
"04") echo -e '\ue312' ;; # cloudy
"09") echo -e '\ue309' ;; # showers
"10") echo -e '\ue308' ;; # rain
"11") echo -e '\ue30f' ;; # thunderstorm
"13") echo -e '\uf2dc' ;; # snow
"50") echo -e '\ue303' ;; # mist
* ) echo -e '\ue374' ;; # unknown
esac
elif [[ "$tod" == "n" ]] ; then
# night icons
case "$conditions" in
"01") echo -e '\ue32b' ;; # clear
"02") echo -e '\ue379' ;; # scattered clouds
"03") echo -e '\ue37e' ;; # broken clouds
"04") echo -e '\ue312' ;; # cloudy
"09") echo -e '\ue326' ;; # showers
"10") echo -e '\ue325' ;; # rain
"11") echo -e '\ue32a' ;; # thunderstorm
"13") echo -e '\uf2dc' ;; # snow
"50") echo -e '\ue346' ;; # mist
* ) echo -e '\ue374' ;; # unknown
esac
else
echo "TOD not recognized"
exit 1
fi
}
icon_test() {
#tests icons
printf 'Testing weather icons\nIf any look broken, check that NerdFont is installed\n'
printf '\nDay:\n'
printf 'Clear: \ue30d\n'
printf 'Partly Cloudy: \ue30c\n'
printf 'Cloudy: \ue302\n'
printf 'Very Cloudy: \ue312\n'
printf 'Showers: \ue309\n'
printf 'Rain: \ue308\n'
printf 'Thunderstorm: \ue30f\n'
printf 'Snow: \uf2dc\n'
printf 'Fog: \ue303\n'
# night icons
printf '\nNight:\n'
printf 'Clear: \ue32b\n'
printf 'Partly Cloudy: \ue379\n'
printf 'Cloudy: \ue37e\n'
printf 'Very Cloudy: \ue312\n'
printf 'Showers: \uf2dc\n'
printf 'Rain: \ue325\n'
printf 'Thunderstorm: \ue32a\n'
printf 'Snow: \uf2dc\n'
printf 'Fog: \ue346\n'
printf '\nAssorted:\n'
printf 'Degrees (F) \ufa04\n'
printf 'Degrees (C) \ufa03\n'
printf '%% Humidity \ue373\n'
}
# shifting longform
for arg in "$@"; do
@ -110,29 +285,43 @@ for arg in "$@"; do
'--coords') set -- "$@" "-c" ;;
'--search') set -- "$@" "-s" ;;
'--units') set -- "$@" "-u" ;;
'--pretty') set -- "$@" "-p" ;;
'--icon_test') set -- "$@" "-i" ;;
'--help') set -- "$@" "-h" ;;
*) set -- "$@" "$arg" ;;
esac
done
while getopts "z:c:s:u:h" opt; do
while getopts "chpiz:s:u:" opt; do
case "$opt" in
'u' )
UNITS="$OPTARG"
UNIT="$OPTARG"
;;
'z' )
ZIPCODE="$OPTARG"
[ -n "$QUERY" ] && usage 1 || QUERY="-z $OPTARG"
;;
's' )
SEARCH="$OPTARG"
[ -n "$QUERY" ] && usage 1 || QUERY="-s $OPTARG"
;;
'p' )
PRETTY=true
;;
'i' )
icon_test
exit 0
;;
'h' )
usage
exit 0
usage 0
;;
'?' )
usage 1
;;
esac
done
if [[ -n "$SEARCH" || -n "$ZIPCODE" ]] ; then
load_info
if [[ -n "$QUERY" ]] ; then
# perform search
get_location
fi

View File

@ -1,60 +0,0 @@
{
"day": {
"Unknown": "",
"bkn": "",
"wind_bkn": "",
"fog": "",
"rain": "",
"rain_showers": "",
"rain_showers_hi": "",
"rain_snow": "",
"rain": "",
"sleet": "",
"rain_sleet": "",
"fzra": "",
"rain_fzra": "",
"snow_sleet": "",
"snow_frza": "",
"snow": "",
"sct": "",
"few": "",
"wind_sct": "",
"wind_few": "",
"skc": "",
"wind_skc": "",
"trsa": "",
"trsa_sct": "",
"trsa_hi": "",
"ovc": "",
"wind_ovc": ""
},
"night": {
"Unknown": "",
"bkn": "",
"wind_bkn": "",
"fog": "",
"rain": "",
"rain_showers": "",
"rain_showers_hi": "",
"rain_snow": "",
"rain": "",
"rain_showers": "",
"rain_showers_hi": "",
"sleet": "",
"snow_sleet": "",
"snow_frza": "",
"snow": "",
"sct": "",
"few": "",
"wind_sct": "",
"wind_few": "",
"skc": "",
"wind_skc": "",
"trsa": "",
"trsa_sct": "",
"trsa_hi": "",
"ovc": "",
"wind_ovc": ""
}
}