#!/bin/sh # Author: reardencode # This script sets Multiswitch states based on the status of servers # on your network as well as the presence of device MAC addresses. # You can monitor basically any combination of hosts and MACs, as # long as you assign them to unique multiswitch switches. # Instructions: # * Set the variables at the top of the script to match your setup # * Put this in /jffs/scripts or /usr/bin or wherever on your router # * chmod +x /path/to/this/script # * Put '/path/to/this/script&' in /etc/rc.local (via CLI or GUI) # * Either run '/path/to/this/script&' from the CLI or reboot iw_devices="wlan0 wlan1" macs=",, ,," hosts=",, ,," vera_ip= # How frequently to poll devices / hosts poll_seconds=1 # How long a device may be disconnected before its switch is set to 0 timeout_seconds=60 # How long between refreshing switch states with same host/device refresh_seconds=300 base_query="id=lu_action&serviceId=urn:dcineco-com:serviceId:MSwitch1" base_url="http://$vera_ip:3480/data_request?$base_query" get_var_name() { local device_switch=${3#*,} echo ${1}_${2}_${device_switch%,*}_${device_switch#*,} } set_state() { local host_or_mac=$1 local item=$2 local new_state=$3 local old_state=$4 local name=${item%%,*} local device_switch=${item#*,} local device=${device_switch%,*} local switch=${device_switch#*,} local params="DeviceNum=$device&action=SetStatus$switch&newStatus$switch=$new_state" if [ $new_state -ne $old_state ]; then echo "Setting $device.$switch ($name) to $new_state" if wget -T 1 -O - "$base_url&$params" > /dev/null 2>&1; then eval $(get_var_name $host_or_mac state $item)=$new_state fi fi } poll_mac() { for iw_device in $iw_devices; do if iw dev $iw_device station get $1 > /dev/null 2>&1; then return 0 fi done return 1 } poll_host() { ping -w 1 -c 1 $1 > /dev/null 2>&1 return $? } poll_states() { local host_or_mac=$1 eval local items=\$${host_or_mac}s for item in $items; do eval local state=\$$(get_var_name $host_or_mac state $item) if eval poll_$host_or_mac ${item%%,*}; then set_state $host_or_mac $item 1 $state eval $(get_var_name $host_or_mac count $item)=$timeout_seconds else eval local count=\$$(get_var_name $host_or_mac count $item) if [ $count -le 0 ]; then set_state $host_or_mac $item 0 $state else eval $(get_var_name $host_or_mac count $item)=$((count-poll_seconds)) fi fi done } init_counts() { local host_or_mac=$1 eval local items=\$${host_or_mac}s for item in $items; do eval $(get_var_name $host_or_mac count $item)=$timeout_seconds done } clear_states() { local host_or_mac=$1 eval local items=\$${host_or_mac}s for item in $items; do eval $(get_var_name $host_or_mac state $item)=-1 done } main() { local refresh=0 init_counts host init_counts mac while true; do if [ $refresh -le 0 ]; then clear_states host clear_states mac refresh=$refresh_seconds fi poll_states host poll_states mac sleep $poll_seconds refresh=$((refresh-poll_seconds)) done } main