aboutsummaryrefslogtreecommitdiff
path: root/.local/share/bin/scene
blob: c7faff64c6305847008c4cebd40b0fd105612cac (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
#!/bin/sh
CACHE_FILE="$XDG_CACHE_HOME/hass-scenes"
TAB="$(printf '\t')"

update_cache() {
	rm -f "$CACHE_FILE"
	curl -s -X GET \
		-H "Authorization: Bearer $HASS_TOKEN" \
		-H "Content-Type: application/json" \
		"$HASS_SERVER/api/states" |\
	jq --raw-output '
		.[] |
		select(.entity_id | startswith("scene.")) |
		"\(.attributes.friendly_name)\t\(.entity_id)"
	' > "$CACHE_FILE"
}

# update cache if it does not exist
[ ! -e "$CACHE_FILE" ] && update_cache

# update the cache if requested explicitly
[ "$1" = "--update" ] && {
	update_cache
	exit
}

# update the cache if it is older than
MAX_CACHE_AGE=$(( 60 * 60 * 24 )) # one day
[ $(( $(date +%s) - $MAX_CACHE_AGE )) -gt $(date -r "$CACHE_FILE" +%s) ] && update_cache

if [ $# -eq 0 ] ; then
	# pick a scene using rofi in dmenu mode
	scene="$(cat "$CACHE_FILE" |\
		rofi \
			-dmenu \
			-display-columns 1 \
			-display-column-separator "$TAB" |\
		cut -d"$TAB" -f2 |\
		jq --raw-input)"
else
	# non interactive scene pick
	scene="$(cat "$CACHE_FILE" |\
		grep -w "$*" | head -n1 |\
		cut -d"$TAB" -f2 |\
		jq --raw-input)"
fi

# exit if no scene was selected / found
[ -z "$scene" ] && exit 0

jq -n --argjson scene "$scene" '{"entity_id": $scene}' |\
	curl -s -X POST -d @- \
		-H "Authorization: Bearer $HASS_TOKEN" \
		-H "Content-Type: application/json" \
		"$HASS_SERVER/api/services/scene/turn_on" > /dev/null