Control Home Assistant with ncurses

Beitrag vom 13.08.2017

I'm using Home Assistant in my local network to control lights, radio and some other stuff. To access the home assistant functions from my PocketCHIP, I've written a small shell script using the dialog util.

Home Assistant Shell on PocketCHIP

Dependencies

sudo apt install dialog jq curl

How it works

The script fetches all input_boolean Components from Home Assistant via RESTful API and creates a list with the dialog util. HTTP requests will be done by curl, JSON parsing by jq.

After selecting an entry, the script calls the input_boolean.toggle service.

The script

#!/bin/bash

# -> Config

ENDPOINT="http://192.168.1.1:8123/api"

# -> Config END

while true
do

    ALLSTATES=$(curl -s "$ENDPOINT/states" | jq -r 'map(select(.entity_id|startswith("input_boolean.")))' | jq -r 'sort_by(.entity_id)')

    # Fetch states from home assistant
    ENTITIES=$(echo "$ALLSTATES" | jq -r 'map(.entity_id)')
    ENTITYSTATES=$(echo "$ALLSTATES" | jq -r 'map(.state)')
    FRIENDLIES=$(echo "$ALLSTATES" | jq -r 'map(.attributes.friendly_name)')
    LENGTH=$(echo "$ENTITIES" | jq -r '.|length')

    # Build dialog menu
    MENUSTR=()
    for I in $(seq 0 $(($LENGTH-1))); do
        E=$(echo $ENTITIES | jq -r ".[$I]" | cut -d '.' -f 2)
        F=$(echo $FRIENDLIES | jq -r ".[$I]")
        S=$(echo $ENTITYSTATES | jq -r ".[$I]")
        MENUSTR+=($E "[$S] $F")
    done

    # Display dialog menu
    exec 3>&1

    CHOICE=$(dialog --clear \
       --backtitle "Home Assistant Shell Tools" \
       --title "Toggle Input Boolean" \
       --menu "Choose a input boolean to toggle" \
       20 70 12 \
       "${MENUSTR[@]}" \
       2>&1 1>&3)

    CODE=$?;
    exec 3>&-;

    # Quit?
    if [ ! "$CODE" == 0 ]; then
        clear
        break
    fi

    # Execute home assistant update
    echo 25 | dialog --gauge "Execute toggle for ${CHOICE}..." 7 70 0
    curl -s -X POST "$ENDPOINT/services/input_boolean/toggle" -d "{\"entity_id\": \"input_boolean.${CHOICE}\"}" > /dev/null
    echo 100 | dialog --gauge "Toggle for ${CHOICE} finished" 7 70 0
    sleep 1

done

exit 0

Hallo Internet

Mein Name ist Christian, vom Beruf bin ich Anwendungsentwickler.

In meiner Freizeit beschäftige ich mich mit verschiedensten Technologien. Hier sammele ich Dinge, die für mich interessant waren oder sind.