Page 2 of 2
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Tuesday 21 March 2017 22:23
by Zweef
Martijn85 wrote:I already had the shell script updated, so if someone still want's to use this one, this is the updated code:
......
device.sh
I'm playing with/adapting your nice script and do have some progress with it. I'm just started to use Domoticz and (bash) scripts, so just be patient with me...
Do you know if it is possible to get the content of a Domoticz user variable in a bash script?
Probable I need some kind of curl command to get the JSON results of the API command:
Code: Select all
/json.htm?type=command¶m=getuservariables
and filter the right uservariable, but I can't get it to work.
Can you please help me with that?
Thank you in advance!
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 23 March 2017 19:09
by sach
@asjmcguire
I wonder if you can help?
The PHP script suddenly stopped working a couple of nights ago.
When running the script manually I get:
PHP Notice: Undefined index: authorized in /home/pi/domoticz/scripts on line 100
any ideas?
Sach
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 23 March 2017 20:43
by asjmcguire
sach wrote:@asjmcguire
I wonder if you can help?
The PHP script suddenly stopped working a couple of nights ago.
When running the script manually I get:
PHP Notice: Undefined index: authorized in /home/pi/domoticz/scripts on line 100
any ideas?
Sach
I should really add a check for that, the line means if the wireless client is connected to the access point and allowed access to the network -
all of mine have always just said true. Is that the only thing it says - it doesn't list anything else?
I could probably do with a JSON dump of the list of clients so we can see what's different. Has Unifi been upgraded or anything?
To get a JSON dump to send me:
Goto the Unifi dashboard as usual and login.
Then visit https://<unifi-ip>:<unifi-port>/api/s/default/stat/sta and grab everything on that page and send it to me in a PM and I'll see if I can figure out what's going wrong.
Andy
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 23 March 2017 22:49
by asjmcguire
Attention!!
If we get confirmation that it works without any adverse affects from sach - then anyone running the PHP version of this script - should change line 100 from
to
to prevent any upgrades causing the script to fail as sach has indicated.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 23 March 2017 23:06
by sach
Thanks Andy,
Just tested it and I don't get the errors anymore, however my phone is not found and its connected to the network:
No matching clients are currently connected
No-one is home!
Switch state doesn't need changing
Sach
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 23 March 2017 23:56
by sach
Wait......it works
I restored the original from a backup and just made that one change and its working. I must have accidently changed something else too.
Thanks for your help Andy.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Friday 24 March 2017 0:20
by asjmcguire
sach wrote:Wait......it works
I restored the original from a backup and just made that one change and its working. I must have accidently changed something else too.
Thanks for your help Andy.
No problem, glad it's working now. I also use a second version of the script that just prints out to the console a list of the clients, mac addresses and IP addresses so I can verify the original script is working correctly. I'll probably just add some debugging stuff to the original script so in the future we can just run it with the argument --debug and get a printout of what it's doing.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Friday 24 March 2017 13:13
by hansworst
Thanks a lot for the PHP script, it seems to work great for my home with a iPhone + Android Phone for the moment.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Friday 23 June 2017 13:20
by carter
No problem, glad it's working now. I also use a second version of the script that just prints out to the console a list of the clients, mac addresses and IP addresses so I can verify the original script is working correctly. I'll probably just add some debugging stuff to the original script so in the future we can just run it with the argument --debug and get a printout of what it's doing.
Is it possible to see that code? I am very interested through domoticz to see which devices are connected.
Thank you!!
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Tuesday 01 August 2017 7:56
by sisaenkov
Another one bash-script to update Domoticz variables according to user presence.
You will need to change UniFi and Domoricz script parameters.
In my case the are 2 users that can be detected, so I set 2 var_ids, 2 var_names and 2 macs.
Code: Select all
#!/bin/bash
# UniFi parameters
username=admin
password=password
baseurl=https://xx.xx.xx.xx:8443
site=default
# Domoticz parameters
domoticz_host="http://172.16.1.100:8080"
var_id=(27 28) # User1, User2
var_name=(UniFi_User1 UniFi_User2)
mac=(38:59:39:f2:23:d6 30:e2:31:23:84:36)
cookie=/tmp/unifi_cookie
curl_cmd="curl -1ksSf --cookie ${cookie} --cookie-jar ${cookie} "
unifi_login() {
${curl_cmd} --data "{'username':'$username', 'password':'$password'}" $baseurl/api/login
}
unifi_list_sta() {
${curl_cmd} --data "json={}" $baseurl/api/s/$site/stat/sta
}
login=$(unifi_login 2>&1)
# Check UniFi availability
echo $login | grep 'Failed to connect' > /dev/null 2>&1
# UniFi is available
if [[ $? != 0 ]]; then
for i in `seq 0 \`expr $(echo ${mac[@]} | wc -w) - 1\``; do
# Detect user presence
find=$(unifi_list_sta | /usr/bin/jq -r '.data[].mac' | grep -x ${mac[$i]})
echo "MAC$i: $find"
# UniFi detects user presence
if [ -n "$find" ]; then
# Check Domoticz variable value
var_value=$(/usr/bin/curl -ks -X GET -H "Content-type: application/json" "$domoticz_host/json.htm?type=command¶m=getuservariable&idx=${var_id[$i]}" | /usr/bin/jq -r .result[].Value)
echo "Domoticz variable ${var_id[$i]}: $var_value"
# Domoticz variable has opposite state to the UniFi presence state
if [ $var_value = 0 ]; then
# Update variable value to Present state
/usr/bin/curl -ks -X GET -H "Content-type: application/json" "$domoticz_host/json.htm?type=command¶m=updateuservariable&vname=${var_name[$i]}&vtype=0&vvalue=1"
fi
# UniFi doesn't detect user presence
elif [ -z "$find" ]; then
# Check Domoticz variable value
var_value=$(/usr/bin/curl -ks -X GET -H "Content-type: application/json" "$domoticz_host/json.htm?type=command¶m=getuservariable&idx=${var_id[$i]}" | /usr/bin/jq -r .result[].Value)
echo "Domoticz variable ${var_id[$i]}: $var_value"
# Domoticz variable has opposite state to the UniFi presence state
if [ $var_value = 1 ]; then
# Update variable value to Present state
/usr/bin/curl -ks -X GET -H "Content-type: application/json" "$domoticz_host/json.htm?type=command¶m=updateuservariable&vname=${var_name[$i]}&vtype=0&vvalue=0"
fi
fi
done
# UniFi is unavailable
else
echo -e "ERROR:\tCan't connect to UniFi controller."
fi
I think that using only one type of determine presence is wrong. So I use UniFi detection at first and then Geofence.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 31 August 2017 11:42
by BakSeeDaa
salvation wrote: ↑Monday 20 October 2014 9:47
......
If someone has tips for improving it let me know.
Hi @salvation and thanks for sharing your script. I like it because it's simple and easy to maintain.
I made some changes to it.
EDIT: I made a new thread for my script
here.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 31 August 2017 14:11
by Luigi87
BakSeeDaa wrote: ↑Thursday 31 August 2017 11:42
salvation wrote: ↑Monday 20 October 2014 9:47
......
If someone has tips for improving it let me know.
Hi @salvation and thanks for sharing your script. I like it because it's simple and easy to maintain.
I made some changes to it though and I like to share them here in case it can help someone with similar needs.
I have 2 access points in my house, handled by a single unifi controller but on different sites. So I need the unifi controller bash script to handle multiple sites. I also modified so that the script runs continuously and updates Domoticz devices only if needed. Domoticz doesn't have to call the script. The script will update Domoticz devices (But only if needed)
Site IDs need to be configured in the array:
Code: Select all
declare -A sites=([first_site]=default [second_site]=iw0jsks9)
You can find the site ID in the unifi controller Web GUI if you fiddle around with right click and "inspect" in various places where sites are listed. (Chrome).
There is always a default site and the ID 'default' can be used. If you have more sites you'll need to find the IDs. An ID will look something like
iw0jsks9
Script name
/home/pi/domoticz/scripts/unifi-detect/unifi_detect.sh
Code: Select all
#!/usr/bin/env bash
# We want a single instance of this script
status=`ps -efww | grep -w "[u]nifi_detect.sh" | awk -vpid=$$ '$2 != pid { print $2 }'`
numProcs=( $status )
if [ ${#numProcs[@]} -gt 2 ]; then
echo "[`date`] : unifi_detect.sh : Process is already running: " "$status"
exit 1;
fi
unifi_username=roger
unifi_password=secret123
unifi_controller=https:/UNIFIIP:8443
cookie=/tmp/unifi_cookie
domoticz_ip=username:[email protected]
domoticz_port=8080
declare -A sites=([first_site]=default [second_site]=iw0jsks8)
declare -A cellPhones
cellPhones["Cell Phone Person A"]=domoDevIdxA
cellPhones["Cell Phone Person B"]=domoDevIdxB
cellPhones["Cell Phone Person C"]=domoDevIdxC
cellPhones["Cell Phone Person D"]=domoDevIdxD
declare -A lastStates
curl_cmd="curl --silent --cookie ${cookie} --cookie-jar ${cookie} --insecure "
unifi_login() {
# authenticate against unifi controller
${curl_cmd} --output /dev/null -H "Content-Type: application/json" -X POST -d "{\"password\":\"$unifi_password\",\"username\":\"$unifi_username\"}" $unifi_controller/api/login
}
unifi_logout() {
# logout
${curl_cmd} $unifi_controller/logout
}
switchDevice() {
#echo Checking idx $1 so that it is $2
domoState=$(curl --silent "http://$domoticz_ip:$domoticz_port/json.htm?type=devices&rid=$1")
#echo "$domoState"
if echo "$domoState" | grep -q "\"Status\" : \"On\""; then
oldState=On;
else
oldState=Off;
fi
if [ "$oldState" != "$2" ]; then
echo Switching idx $1 state to $2
curl --silent --output /dev/null "http://$domoticz_ip:$domoticz_port/json.htm?type=command¶m=switchlight&idx=$1&switchcmd=$2"
fi
}
# stat/sta
unifi_list_sta() {
for i in "${!sites[@]}"; do
${curl_cmd} --write-out \\n%{http_code} --data "json={}" $unifi_controller/api/s/${sites[$i]}/stat/sta
done
}
unifi_login
loopCounter=999999
while [ 1 -lt 2 ]; do
((loopCounter++))
if [ "$loopCounter" -gt 240 ]; then
#echo "Resetting the counter"
loopCounter=1
lastStates["Cell Phone Person A"]="Unknown"
lastStates["Cell Phone Person B"]="Unknown"
lastStates["Cell Phone Person C"]="Unknown"
lastStates["Cell Phone Person D"]="Unknown"
fi
#put unifi_list_sta output in variable
var=$(unifi_list_sta)
#echo "$var"
resultCode="${var##*$'\n'}"
for i in "${!cellPhones[@]}"; do
if echo "$var" | grep -q "$i"; then
newState="On";
else
newState="Off";
fi
if [ "$newState" != "${lastStates[$i]}" ]; then
lastStates[$i]="$newState"
switchDevice "${cellPhones[$i]}" "$newState";
fi
done
if [ "$resultCode" != "200" ]; then
echo "Exiting with a result code of : $resultCode"
exit 1
fi
#echo "Let's have some sleep..."
sleep 30
done
unifi_logout
Put this in crontab:
Code: Select all
*/5 * * * * /home/pi/domoticz/scripts/unifi-detect/unifi_detect.sh
I don't need to mention that you need to
Code: Select all
sudo chmod 755 /home/pi/domoticz/scripts/unifi-detect/unifi_detect.sh
do I?
Putting the script in the crontab works like a "watch dog" so that there will always be one instance of the script running.
You're the best!
I was just searching for a better way of checking presence in my system. Before I used Geolocation and Tasker but it's now very unstable due to the use of a OpenVPN connection on the clients (mobile devices).
So I have to integrate a presence detection system from the server to the client and not the other way around.
I will use you script, because i also have 2 ubiquity AP's in my home.
But I have a couple of questions about the script:
#1: where do i put in the MAC adresses of the Mobile devices? couldn't find this in the script
#2: If one of the mobile phones hops to the other AP (takes about a couple of seconds) will this cause the script to set the virtual switch to “off” (away)? Or is there some delay here? how long is this delay? same as seen in the topic about 5 minutes?
#3: what happens if both mobile devices are switched off from the WIFI, but still in reach for the Access points?
Explanation: Sometimes we have a downtime in the internet connection to the Internet Serice Provides. And when this happens and we are at home, we switch to the mobile internet connection. And switched off from the WIFI.
#4: An other solution to the issue by Question 3 is to do the Switch Off by the Geofence, and the Switch “on” by your Script. What part do I have to disable in your script to let the script only set the Virtual Switch to “On”
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 31 August 2017 15:57
by BakSeeDaa
Luigi87 wrote: ↑Thursday 31 August 2017 14:11
You're the best!
I was just searching for a better way of checking presence in my system. Before I used Geolocation and Tasker but it's now very unstable due to the use of a OpenVPN connection on the clients (mobile devices).
So I have to integrate a presence detection system from the server to the client and not the other way around.
I will use you script, because i also have 2 ubiquity AP's in my home.
But I have a couple of questions about the script:
#1: where do i put in the MAC adresses of the Mobile devices? couldn't find this in the script
#2: If one of the mobile phones hops to the other AP (takes about a couple of seconds) will this cause the script to set the virtual switch to “off” (away)? Or is there some delay here? how long is this delay? same as seen in the topic about 5 minutes?
#3: what happens if both mobile devices are switched off from the WIFI, but still in reach for the Access points?
Explanation: Sometimes we have a downtime in the internet connection to the Internet Serice Provides. And when this happens and we are at home, we switch to the mobile internet connection. And switched off from the WIFI.
#4: An other solution to the issue by Question 3 is to do the Switch Off by the Geofence, and the Switch “on” by your Script. What part do I have to disable in your script to let the script only set the Virtual Switch to “On”
Thanks for the kind words!
#1 You can set an alias for the MAC in the AP to match "Cell Phone Person A". As an alternative, you can also enter the MAC address instead of "Cell Phone Person A"
#2 As long as the phone is connected to one of the AP sites, it will be detected by the script. It's usually quite fast to detect a new connection while it's typically around 5 minutes before a client is considered disconnected by the AP.
#3 Device must be connected to the WiFi to be recognized by the AP. E.g. listed in the unifi web GUI. If a client disconnect from WiFi for any reason, then it will not be detected. Maybe you can try to keep WiFi connected at the same time as using GPRS/3G/4G? I don't know.
#4 I'm not sure if that's a good idea but you can make an if statement just before
Code: Select all
switchDevice "${cellPhones[$i]}" "$newState";
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 31 August 2017 16:13
by Luigi87
BakSeeDaa wrote: ↑Thursday 31 August 2017 15:57
Luigi87 wrote: ↑Thursday 31 August 2017 14:11
Cut
Thanks for the kind words!
#1 You can set an alias for the MAC in the AP to match "Cell Phone Person A". As an alternative, you can also enter the MAC address instead of "Cell Phone Person A"
#2 As long as the phone is connected to one of the AP sites, it will be detected by the script. It's usually quite fast to detect a new connection while it's typically around 5 minutes before a client is considered disconnected by the AP.
#3 Device must be connected to the WiFi to be recognized by the AP. E.g. listed in the unifi web GUI. If a client disconnect from WiFi for any reason, then it will not be detected. Maybe you can try to keep WiFi connected at the same time as using GPRS/3G/4G? I don't know.
#4 I'm not sure if that's a good idea but you can make an if statement just before
Code: Select all
switchDevice "${cellPhones[$i]}" "$newState";
your welcome
Your answere omn 1 till 3 are very clear to me now.
just 1 question about he "If" before the
Code: Select all
switchDevice "${cellPhones[$i]}" "$newState";
this will make:
Code: Select all
if [ "$newState" != "${lastStates[$i]}" ]; then
lastStates[$i]="$newState"
if switchDevice "${cellPhones[$i]}" "$newState";
Due to this the script will only switch the virtual switch to "On", and will not set it to "Off"
I am also not sure if this will work properly.
I have also an override switch for the "somebody at home" button, so i am not sure what to do yet. First i will implement the script as intended, if i have some spare time. i will try to do the switch off by the geofence.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Thursday 31 August 2017 17:34
by Luigi87
BakSeeDaa wrote: ↑Thursday 31 August 2017 11:42
Site IDs need to be configured in the array:
Code: Select all
declare -A sites=([first_site]=default [second_site]=iw0jsks9)
You can find the site ID in the unifi controller Web GUI if you fiddle around with right click and "inspect" in various places where sites are listed. (Chrome).
There is always a default site and the ID 'default' can be used. If you have more sites you'll need to find the IDs. An ID will look something like
iw0jsks9
I Couldn't wait to try the script but i have tried to Find the Site ID's with the Inspect button In chrome on serveral pages in the webGUI but with no result.
Could you please tell me more specific where to find this ID's Maybe on what page and where to right click?
Or maybe i understand site wrong.
I have 1 controller running, in this controller i have 2 serveral Access Point's running. do i have 1 site or 2 in this case? and will this work?
Because you can also see the site ID in the browser adress (
link)
Code: Select all
IPcontroller:8443/manage/site/default/dashboard
the part of the code will be like, if i have only 1 site.
Code: Select all
declare -A sites=([first_site]=default )
right?
i have tried it with the script as it was and getting the following result:
Code: Select all
Exiting with a result code of : 000
And the Switch is not toggled
What could be wrong?
( I've send you a PM with the complete Code)
Sorry, i am very not a programming guy. So reading and chaning the code is realy hard for me
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Friday 01 September 2017 10:57
by BakSeeDaa
Luigi87 wrote: ↑Thursday 31 August 2017 17:34
I have 1 controller running, in this controller i have 2 serveral Access Point's running. do i have 1 site or 2 in this case? and will this work?
Because you can also see the site ID in the browser adress (
link)
You can have 2 APs in a single site or you can have 2 sites with a single AP in each site. It depends on how you configured it. Most people have a single site.
I have made my first post a bit more clear about how to find the site ID and you are correct. The site ID is clearly visible in the URL.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Friday 01 September 2017 11:25
by BakSeeDaa
Luigi87 wrote: ↑Thursday 31 August 2017 17:34
i have tried it with the script as it was and getting the following result:
Code: Select all
Exiting with a result code of : 000
And the Switch is not toggled
What could be wrong?
( I've send you a PM with the complete Code)
Sorry, i am very not a programming guy. So reading and chaning the code is realy hard for me
At first glimpse it looks like if you have accidentally changed the script in any way so please check again that you are running the original.
Also check that you have curl installed. Just write
at the command prompt.
Try declare only a single site because that's what I believe that you have:
Code: Select all
declare -A sites=([first_site]=default)
Try if it's working.
If not, then you can try to uncomment the line:
You will then see the result fetched from Unifi with the result code on the last line.
EDIT:
It's not fair "hi-jacking" this thread so I made a new thread for my script
here.
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Friday 01 September 2017 12:48
by Luigi87
BakSeeDaa wrote: ↑Friday 01 September 2017 11:25
Luigi87 wrote: ↑Thursday 31 August 2017 17:34
i have tried it with the script as it was and getting the following result:
Code: Select all
Exiting with a result code of : 000
And the Switch is not toggled
What could be wrong?
( I've send you a PM with the complete Code)
Sorry, i am very not a programming guy. So reading and chaning the code is realy hard for me
At first glimpse it looks like if you have accidentally changed the script in any way so please check again that you are running the original.
Also check that you have curl installed. Just write
at the command prompt.
Try declare only a single site because that's what I believe that you have:
Code: Select all
declare -A sites=([first_site]=default)
Try if it's working.
If not, then you can try to uncomment the line:
You will then see the result fetched from Unifi with the result code on the last line.
EDIT:
It's not fair "hi-jacking" this thread so I made a new thread for my script
here.
Thanks, i will delete the script and will add it again to the system. Sometimes with copy-ing to the Command Console will not work out as it has to be
And also check if i have Curl installed.
keep you posted
Re: Switch on/off when someone entering/leaving home (Ubiquiti)
Posted: Sunday 16 September 2018 14:01
by sincze
asjmcguire wrote: ↑Tuesday 14 March 2017 3:52
Just stick it on your computer - edit the config section and tell cron to run the file every minute or every 5 minutes or whatever.
....
Job done. Hope this helps someone.
Excellent @asjmcguire you got me inspired as well. As I am a Pass2PHP 'user' I had to modify it a bit and I used the
https://github.com/Art-of-WiFi/UniFi-API-client.
The written code can be found here:
viewtopic.php?f=64&t=12343&start=640#p191660
WIthin the USG controller I used the 'note' field with the text 'GSM', to 'mark' my mobile phones.
I then just move through the list and store the found mobile phones in an array for further processing.
Code: Select all
foreach ($clients_array as $client) {
if (isset($client->note) && (strpos($client->note, "GSM") === 0)) { // Note field of USG contains the word GSM
$online_phones[] = $client->name; // Store found phone names in array
}
}
Again good work within this whole thread.