I've created a script to determine if someone is at home (or not). It's based on if clients are connected to my Ubiquiti Wifi Network. So via the API I check if a at least one client is connected. I'm not a programmer at all, so most of the code is grabbed from several scripts and it's also a Lua script combined with a bash script.
I think it could be definately be cleaner code, but at least it's working. And it works a lot better than using Automatit or Tasker on the Android phones.
I'm using a dummy light to switch when someone is at home.
Lua time script to trigger the check.
Code: Select all
commandArray = {}
-- Call setHome when someone at home
if (otherdevices['homeSomeOne']=='On') then
os.execute('sudo ./home/pi/domoticz/scripts/bash/setHome.sh "On"')
print('called setHome / On')
end
-- Call setHome when no one at home
if (otherdevices['homeSomeOne']=='Off') then
os.execute('sudo ./home/pi/domoticz/scripts/bash/setHome.sh "Off"')
print('called setHome / Off')
end
return commandArray
Bash script setHome.sh to call Ubiquiti API and switch the dummy light if needed:
Code: Select all
#!/bin/sh
lightStatus=$1
username=<ubiquiti-controller login>
password=<ubiquiti-controller pass>
baseurl=<ubiquiti-controller url>
cookie=/tmp/unifi_cookie
curl_cmd="curl --sslv3 --silent --cookie ${cookie} --cookie-jar ${cookie} --insecure "
named_args_to_payload() {
payload=""
for a in "$@" ; do
if [ "${a##*=*}" = "" ] ; then
k=`echo $a | cut -d = -f 1`
v=`echo $a | cut -d = -f 2`
payload="${payload}, '$k':'$v'"
fi
done
echo ${payload}
}
unifi_requires() {
if [ -z "$username" -o -z "$password" -o -z "$baseurl" ] ; then
echo "Error! please define required env vars before including unifi_sh. E.g. "
echo ""
echo "username=ubnt"
echo "password=ubnt"
echo "baseurl=http://unifi:8443"
echo ""
exit -1
fi
}
unifi_login() {
# authenticate against unifi controller
${curl_cmd} --data "login=login" --data "username=$username" --data "password=$password" $baseurl/login
}
unifi_logout() {
# logout
${curl_cmd} $baseurl/logout
}
# stat/sta
unifi_list_sta() {
${curl_cmd} --data "json={}" $baseurl/api/stat/sta
}
unifi_requires
unifi_login
#put unifi_list_sta output in variabele
#check if a least one host is connected
var=$(unifi_list_sta)
if echo "$var" | grep -q "hostname"; then
isHome=yes;
else
isHome=no;
fi
if [ "$isHome" = "yes" ] && [ "$lightStatus" = "Off" ]; then
curl "http://<domoticz-url:port>/json.htm?type=command¶m=switchlight&idx=48&switchcmd=On"
fi
if [ "$isHome" = "no" ] && [ "$lightStatus" = "On" ]; then
curl "http://<domoticz-url:port>/json.htm?type=command¶m=switchlight&idx=48&switchcmd=Off"
fi
unifi_logout
In the future I will try to get the same result in LUA only but I'm not familiar using JSON and LUA. If someone has tips for improving it let me know.