aboutsummaryrefslogtreecommitdiff
path: root/.local/share/bin/scene
blob: 3a140fa8cb886e8a171caa11625453f0a2109688 (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
#!/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

# 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)"

# exit if no scene was selected
[ -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