Reworked option parsing.

This commit is contained in:
Shy 2024-08-07 18:19:19 +02:00
parent eb1e69e05d
commit e2eeccd34f

42
wled
View file

@ -10,6 +10,9 @@ NAME="wled.sh"
COMMAND="wled"
VERSION="0.1.3"
exit_code=0
host_list=
# Make the exit status of command pipelines the status of the last command
# with non-zero exit status - if supported by this shell.
(set -o pipefail 2>/dev/null) && set -o pipefail
@ -67,16 +70,9 @@ current_brightness() {
sed -n 's/.*"state"[[:space:]]*:[[:space:]]*{[^}]*"bri"[[:space:]]*:[[:space:]]*\([0-9]\{1,3\}\).*/\1/p'
}
arg_inst="$1"
arg_cmnd="$2"
arg_param="$3"
exit_code=0
# Clear positional arguments.
set --
# Parse instance argument and store hostnames as positional arguments.
case "$arg_inst" in
# Parse instance argument and store hostnames.
while test $# -gt 0; do
case "$1" in
""|-h|--help) # Missing instance parameter.
print_help
exit 0
@ -86,25 +82,27 @@ case "$arg_inst" in
exit 0
;;
-a|--all)
set -- 'wled-fnordcenter.local' \
'wled-wohnzimmer.local'
host_list="wled-fnordcenter.local wled-wohnzimmer.local"
;;
-f|--fnordcenter)
set -- 'wled-fnordcenter.local'
host_list="$host_list wled-fnordcenter.local"
;;
-w|--wohnzimmer)
set -- 'wled-wohnzimmer.local'
host_list="$host_list wled-wohnzimmer.local"
;;
*) # Unknown instance parameter.
echo "Error: unknown instance \"$arg_inst\"." >&2
test -n "$host_list" && break
echo "Error: not a valid instance option (\"$1\")." >&2
print_usage
exit 1
;;
esac
esac
shift
done
# Parse and execute command argument against given instances.
for wled_host; do
case "$arg_cmnd" in
for wled_host in $host_list; do
case "$1" in
on) # Switch on.
api_resp=$(curl_send '{"on":true}' "http://$wled_host/json")
;;
@ -112,13 +110,13 @@ for wled_host; do
api_resp=$(curl_send '{"on":false}' "http://$wled_host/json")
;;
-b|--brightness) # Set brightness.
if test -z "$arg_param"; then
if test -z "$2"; then
# No parameter given. Print current brightness.
echo "Brightness of $wled_host:"
current_brightness "$wled_host"
else
# Try to convert 3rd parameter to an integer between 1 an 255.
bright=$(printf '%u' "$arg_param" 2>/dev/null)
bright=$(printf '%u' "$2" 2>/dev/null)
if test $? -gt 0; then # Conversion failed.
echo "Error: unable to parse parameter for brightness." >&2
exit 1
@ -130,7 +128,7 @@ for wled_host; do
fi
;;
[1-9]|1[0-7]) # Switch to preset.
api_resp=$(curl_send "{'ps':$arg_cmnd}" "http://$wled_host/json")
api_resp=$(curl_send "{'ps':$1}" "http://$wled_host/json")
;;
l|list) # List presets.
printf "loading ...\r"
@ -164,7 +162,7 @@ for wled_host; do
exit 1
;;
*) # Unknown command.
echo "Error: unknown command \"$arg_cmnd\"." >&2
echo "Error: unknown command \"$1\"." >&2
print_usage
exit 1
;;