summaryrefslogtreecommitdiff
path: root/functions.sh
blob: 2c21a41ebc71958edf5a0c2b836261a2a3bd05cd (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
# This file is meant to be `source`d.

function read_vars() {
  local key value
  while read -r line; do
    key=${line%%=*}
    value=${line#*=}
    if   [[ $key = ip ]]; then bridge_ip=$value
    elif [[ $key = bridgeid ]]; then bridge_id=$value
    elif [[ $key = username ]]; then bridge_username=$value
    fi
  done <my_bridge.txt
}

# arguments:
# - API v2 path: "resource/light" for /clip/v2/resource/light
# - (optional) HTTP method (default GET)
# - (optional) data to send as HTTP body
function hue_request() {
  local path=$1 method=GET body=''
  [[ -z $path ]] && { echo >&2 "functions.sh(hue_request): path required"; exit 1; }
  [[ $# -ge 2 ]] && method=$2
  [[ $# -ge 3 ]] && body=$3
  [[ $# -ge 4 ]] && { echo >&2 "functions.sh(hue_request): too many arguments"; exit 1; }

  local data_args=()
  if [[ -n $body ]]; then
    data_args=( -d "$body" )
  fi

  json=$(
    curl -s --cacert signify_root_cert.pem \
         --resolve "$bridge_id:443:$bridge_ip" -H "hue-application-key: $bridge_username" \
         -X "$method" "${data_args[@]}" \
         https://"$bridge_id"/clip/v2/"$path"
  )

  errors=$(jq -r 'if has("errors") then .errors.[] | "- " + .description else empty end' <<<"$json")
  if [[ -n $errors ]]; then
    echo >&2 "Errors from Hue bridge:"
    echo >&2 "$errors"
    exit 1
  fi

  echo "$json"
}