summaryrefslogtreecommitdiff
path: root/set.sh
blob: 3cd3551b9caf817511734521865a15343bd26113 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$(realpath "$0")")"

source functions.sh

read_vars

if [[ ! -f lights.txt ]]; then
  echo >&2 'First run:'
  echo >&2 '$ ./get_lights.sh >lights.txt'
  exit 1
fi

if [[ $# -eq 0 || ($1 = "-h" || $1 = "--help") ]]; then
  echo >&2 "Usage: $0 <light name> [commands...]"
  echo >&2 "The light name is case-insensitive and may be any unambiguous substring of the full name."
  echo >&2 "Commands:"
  echo >&2 "- on:  turn on the light"
  echo >&2 "- off:  turn off the light"
  echo >&2 "- switch <n>:  turn on if n=1, off if n=0"
  echo >&2 "- br <n>:  set brightness; n in [0, 100]"
  [[ $# -eq 0 ]] && exit 1
  exit 0
fi

namesubstr=$1

matches=$(cut -d' ' -f2- lights.txt | grep -niF "$namesubstr" | cut -d: -f1 || true)
[[ -z $matches ]] && { echo >&2 "Light not found"; exit 1; }
[[ $(wc -l <<<"$matches") -gt 1 ]] && { echo >&2 "Multiple lights matched, name must be unambiguous"; exit 1; }
lightid=$(sed -n "$matches s/ .*//p" <lights.txt)

shift

commandstr="{}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    on) commandstr="$commandstr * {on:{on:true}}"; shift ;;
    off) commandstr="$commandstr * {on:{on:false}}"; shift ;;

    switch)
      [[ $# -lt 2 ]] && { echo >&2 "Not enough arguments to 'switch' command"; exit 1; }
      if   [[ $2 = '1' ]]; then commandstr="$commandstr * {on:{on:true}}"
      elif [[ $2 = '0' ]]; then commandstr="$commandstr * {on:{on:false}}"
      else echo >&2 "Invalid argument to 'switch' command"; exit 1
      fi
      shift 2
      ;;

    br)
      [[ $# -lt 2 ]] && { echo >&2 "Not enough arguments to 'br' command"; exit 1; }
      commandstr="$commandstr * {dimming:{brightness:$2}}"
      shift 2
      ;;

    *)
      echo >&2 "Unrecognised command: '$1'"
      exit 1
  esac
done

hue_request resource/light/"$lightid" PUT "$(jq "$commandstr" <<<0)" >/dev/null