Send updates to Openhab via REST API from any BusyBox device (such as OpenWRT)

I’ve made a simple script that allows to send Updates via REST API using HTTP PUT method but without curl or wget. It uses nc instead. It makes possible to send status updates from OpenWRT. I know that it’s possible to do with HTTP GET request but it looks broken in OpenHAB2b2.

if [ "$#" -ne 2 ]; then
    echo "Usage: openhab-set-state ITEM STATE"
fi

ITEM=$1
STATE=$2
CONTENT_LENGTH=`expr length "$STATE"`
HOST=openhab
PORT=8080
printf "PUT /rest/items/$ITEM/state HTTP/1.1\r\nhost: $HOST:$PORT\r\nContent-Type: text/plain\r\nContent-Length: $CONTENT_LENGTH\r\n\r\n$STATE" | nc $HOST $PORT

This script can be used for checking presence based on devices connected to router. In that case corresponding states would be changed immediately and no ping is neccessary. Also Amazon Dash buttons can be handled.

# see http://wiki.openwrt.org/doc/devel/debugging to enable additional logging
mac_9c_6c_ff_a7_54_a8="Item1"
mac_10_68_ff_87_80_08="Item2"
mac_1c_56_ff_c7_d8_dc="Item3"
mac_74_c2_46_ff_9e_30="AmazonDashButton1"
mac_74_c2_46_ff_65_0d="AmazonDashButton2"

logread -f | while read input
do
  #echo input:$input
  if `echo $input | grep -q deauthenticated`
  then
    mac=`echo $input | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | tr : _`
    item=$(eval "echo \$mac_$mac")
    #echo mac:$mac:$item
    if [ -n "$item" ]; then # if corresponding item exists
      ./openhab-set-state.sh $item OFF
    fi
  elif `echo $input | grep -q authenticated`
  then
    mac=`echo $input | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | tr : _`
    item=$(eval "echo \$mac_$mac")
    #echo mac:$mac:$item
    if [ -n "$item" ]; then # if corresponding item exists
      ./openhab-set-state.sh $item ON
    fi
  fi
done
2 Likes