Fencing your entire apartment with X10

So I’ve begun using X10 for some non-essential systems at home (AC, lights, etc.). I am using a firecracker and the following script, which I will put a nice little iPhone-compatible interface around:

#!/bin/sh
#
# The X10 devices are controlled via a "firecracker" on ttyS1
#
# Copyright (C) 2009 Jon Masters 
#
# Distributed under GNU General Public License version 2.
#

X10_FC_PORT="/dev/ttyS1"
X10_BR_COMMAND="/usr/bin/br --port $X10_FC_PORT"

# e.g. TARGETS=("device1" "device2"...)
TARGETS=("device1")
# e.g. MODULES=("A1" "A2"...)
MODULES=("A1")

TARGET="$1"
COMMAND="$2"

x10_set_module_state() {
        module=$1
        state=$2

        if [ "xon" == "x$state" ]
        then
                $X10_BR_COMMAND $module on
        else
                if [ "xoff" == "x$state" ]
                then
                        $X10_BR_COMMAND $module off
                fi
        fi
}

x10_set_module_state_all() {
        state=$1

        for ((i=0;i< $((${#TARGETS[@]}));i++)); do
                echo "setting module ${TARGETS[${i}]} to $state"
                x10_set_module_state ${MODULES[${i}]} $state
                echo "waiting for module ${TARGETS[${i}]} to settle"
                usleep 500000
        done
}

in_array() {
        haystack=( "$@" )
        haystack_size=( "${#haystack[@]}" )
        needle=${haystack[$((${haystack_size}-1))]}
        for ((i=0;i<$(($haystack_size-1));i++)); do
                h=${haystack[${i}]};
                [ "x$h" == "x$needle" ] && return $i
        done
        return 255
}

if [ "x$TARGET" == "x" ] || [ "x$COMMAND" == "x" ];
then
        echo "Usage: ippower  |  "
        echo ""
        echo "TARGETS: ${TARGETS[@]}"
        echo "COMMANDS: on off"
        echo ""
        exit 1
fi

if [ "xall" == "x$TARGET" ]
then
        if [ "xon" == "x$COMMAND" ]
        then
                echo "turning on all modules"
                x10_set_module_state_all on
        elif [ "xoff" == "x$COMMAND" ]
        then
                echo "turning off all modules"
                x10_set_module_state_all off
        fi
else
        in_array "${TARGETS[@]}" "$TARGET"; item=$?

        if [ 255 -ne $item ]
        then
                MODULE="${MODULES[$item]}"
                #echo "TARGET: $TARGET"
                #echo "MODULE: $MODULE"
                if [ "xon" == "x$COMMAND" ]
                then
                        x10_set_module_state $MODULE on
                        echo "requested module $TARGET on"
                elif [ "xoff" == "x$COMMAND" ]
                then
                        x10_set_module_state $MODULE off
                        echo "requested module $TARGET off"
                fi
        else
                echo "Unknown target: $TARGET"
        fi
fi

Jon.

Leave a Reply