Page 1 of 4

Presence detection using UniFi Controller and DzVents  [Solved]

Posted: Friday 10 August 2018 12:22
by Delfuego
Recently I installed the script from the next link to monitor devices on my WiFi network using the Unifi Controller.
https://www.domoticz.com/forum/viewtopi ... 63&t=19197
Everything works fine but you need to SSH and CronTab all kind of things.

I wrote a script in DzVents that does the same and is a lot easier to use. You need at least DzVents version 2.4.0.

Same as in the previous link you create a virtual switch for every device you want to monitor.
Make sure DzVents is activated in your Domoticz settings. Check the next link on instructions.
https://www.domoticz.com/wiki/DzVents:_ ... _scripting

In the script you change 5 lines of code to your personal settings.
1. Change IP and Port to your Unifi Controller settings.
2. Change YourPassword and YourUsername to your password and username for Unifi Controller (I advice to create a separate read-only admin in your Unifi controller with only system stats access).
3. Change IP and Port to your Unifi Controller settings.
4. Change the mac addresses to addresses of devices you want to monitor. Mac addresses are case sensitive!!
5. Change the Id (Idx) of the devices you want to monitor, the position in DxIndx has to be the same as the position of the mac adress for that device in Mac.

You can add or remove device in step 4 and 5. Just make sure both, mac addresses and Idx numbers, match. So every mac address in Mac needs an Idx in DzInx on the same position.

Activate the script and the monitoring starts.

The Unifi Controller can take up to five minutes to detect a device leaving WiFi. The script runs every five minutes. Worst case it takes ten minutes to detect a device is not present on Wifi by Domoticz.

Code: Select all

return {
   on = {
      timer = { 'every 5 minutes' },
      httpResponses = { 'loggedin' , 'data' }
   },
   execute = function(domoticz, item)
        if (item.isTimer) then
            domoticz.openURL({
                url = 'https://192.168.1.1:8443/api/login',  --Change IP and Port to your Unifi Controller settings
                method = 'POST',
                postData = { ['password'] = 'YourPassword' , ['username'] = 'YourUsername' }, --Change YourPassword en YourUsername to your password en username for Unifi Controller (I advice to create a separate read-only admin in your Unifi controller with only system stats access)
                callback = 'loggedin'
         })
        end
        if (item.isHTTPResponse and item.ok) then
            if (item.trigger == 'loggedin') then
                domoticz.openURL({
                url = 'https://192.168.1.1:8443/api/s/default/stat/sta',  --Change IP and Port to your Unifi Controller settings
                method = 'GET',
                callback = 'data'
                })
            else    
                            
                local Mac = {'11:aa:22:bb:33:cc' , '11:aa:22:bb:33:cc' , '11:aa:22:bb:33:cc' , '11:aa:22:bb:33:cc' , '11:aa:22:bb:33:cc' }  --Change to mac addresses of devices you want to monitor
                local DzIndx = {11,12,13,22,33}  --Change to Domiticz Idx, the position in DxIndx has to be the same as the mac adress for that device in Mac (previous line)
                for i,y in ipairs(Mac)
                do
                    home = string.find( item.data , Mac[i])
                    if (home == nil) then
                        domoticz.devices(DzIndx[i]).switchOff().checkFirst()
                    else
                        domoticz.devices(DzIndx[i]).switchOn().checkFirst()
                    end
                end    
            end
        end    
   end 
}

Re: Presence detection using UniFi Controller and DzVents

Posted: Friday 10 August 2018 13:52
by papoo
Thank you
pity that my router is not compatible

Re: Presence detection using UniFi Controller and DzVents

Posted: Thursday 23 August 2018 15:58
by mcmikev
Great script! Did use the crontab version before too, but this is much easier!!
thank you for making it!

Re: Presence detection using UniFi Controller and DzVents

Posted: Monday 27 August 2018 21:22
by CronoS
Awesome! Works like a charm. Also with my unifi controller on Azure! Thanks

Re: Presence detection using UniFi Controller and DzVents

Posted: Friday 14 September 2018 13:06
by Gerald
You sir; just made my day :-)
Thanks!

Re: Presence detection using UniFi Controller and DzVents

Posted: Sunday 30 September 2018 15:09
by Petturik
I had to change a part of the code, seeing my site isn't called "default" anymore.

so I changed :

Code: Select all

url = 'https://192.168.2.12:8443/api/s/default/stat/sta',  --Change IP and Port to your Unifi Controller settings
to

Code: Select all

url = 'https://192.168.2.12:8443/api/s/<8randomcharactersmadeupbyunifi>/stat/sta',  --Change IP and Port to your Unifi Controller settings
After that it works like a charm !

Re: Presence detection using UniFi Controller and DzVents

Posted: Thursday 18 October 2018 22:19
by credenty
Hello,
It works perfect in Windows, thank you very much for this great script !!!
I have seen how I can change the execution time of the script, but how can I increase the time it is disconnected and reduce the detection time?

Re: Presence detection using UniFi Controller and DzVents

Posted: Friday 19 October 2018 10:32
by Delfuego
credenty wrote: Thursday 18 October 2018 22:19 Hello,
It works perfect in Windows, thank you very much for this great script !!!
I have seen how I can change the execution time of the script, but how can I increase the time it is disconnected and reduce the detection time?
I’m afraid the Unifi controller takes up to five minutes to detect a device has left your WiFi. Worst case in my script detection takes 10 minutes. Running the script every minute makes it a little bit faster but still somewhere between 1 and 6 minutes.
If somebody knows how to speed things up I’m very interested!

Re: Presence detection using UniFi Controller and DzVents

Posted: Friday 11 January 2019 12:56
by dressie
Love this script! Works like a charm. Would be nice to add it to the wiki page.

Verstuurd vanaf mijn SM-G950F met Tapatalk


Re: Presence detection using UniFi Controller and DzVents

Posted: Thursday 22 August 2019 8:44
by Flopp
This is really nice and easy script. Thank you

Re: Presence detection using UniFi Controller and DzVents

Posted: Saturday 04 April 2020 15:05
by cjb75
Been using this script for several years without any problems but since I upgraded to “Domoticz Version: 2020.1“ (running Unifi Controller 5.12.66) I get:

Error: Error opening url: https://192.168.10.2:8443/api/s/default/stat/sta
Error: dzVents: Error: (3.0.1) HTTP/1.1 response: 401 ==>> No reason returned!

Any ideas why?

Re: Presence detection using UniFi Controller and DzVents

Posted: Saturday 04 April 2020 15:53
by Delfuego
I’m not yet on 2020.1. Planned to try this week. I will look into this. (My controller is 5.12.66 too so that should not be the problem)

Re: Presence detection using UniFi Controller and DzVents

Posted: Saturday 04 April 2020 16:20
by cjb75
Great, let me know if I can assist you in any way!

btw – this script https://www.domoticz.com/forum/viewtopi ... ifi+script (using curl command) works fine for me but I would like to use dzvents.

Re: Presence detection using UniFi Controller and DzVents

Posted: Saturday 04 April 2020 20:36
by Delfuego
I think the problem was in the Unifi controller software running on Buster (or actually not running). I had the same error. After using the install script from the next link I managed to restart the Unifi contoller.
https://community.ui.com/questions/UniF ... b17f027776
After this Unifi install everything is working fine again.

Re: Presence detection using UniFi Controller and DzVents

Posted: Sunday 05 April 2020 6:58
by cjb75
My controller is running on a Cloud Key, so I guess I have another problem then.

As far as I can understand I can log in but getting the data results in :
Error: (3.0.1) HTTP/1.1 response: 401 ==>> No reason returned!

Re: Presence detection using UniFi Controller and DzVents

Posted: Tuesday 07 April 2020 21:27
by StasDemydiuk
@Delfuego Thank you so much for the script!

I've modified it a bit to allow collect historical data as mobile devices are going to sleep time to time and could be not visible in the network when script polls the UniFi Controller.

With these changes script polls data from controller every minute and it is possible to setup time interval (for my devices I found the most convenient one is 6 min) so device will be considered as offline if it wasn't present in the network during the whole period.

Code: Select all

return {
    on = {
        timer = { 'every 1 minutes' },
        httpResponses = { 'unifi_loggedin' , 'unifi_data' }
    },
    data = {
        presenceHistory = { history = true, maxMinutes = 6 } 		-- Change maxMinutes value to appropriate for your devices
    },
    execute = function(domoticz, item)
        local controllerUrl = 'https://192.168.1.1:8443/' 	--Change IP and Port to your Unifi Controller settings
        local controllerLogin = 'user'						-- Your username for Unifi Controller
        local controllerPassword = 'password' 				-- Your password for Unifi Controller

        local devices = {
            ['11:aa:22:bb:33:cc'] = 11,						-- Change to mac addresse of your device and its Domiticz Idx
            ['11:aa:22:bb:33:cc'] = 'myDevice' 					-- You can use device name instead of Domiticz Idx as well
        }

        if (item.isTimer) then
            domoticz.openURL({
                url = controllerUrl .. 'api/login',
                method = 'POST',
                postData = { 
                    ['password'] = controllerPassword, 
                    ['username'] = controllerLogin 
                },
                callback = 'unifi_loggedin'
            })
        end
        
        if (item.isHTTPResponse and item.ok) then
            if (item.trigger == 'unifi_loggedin') then
                domoticz.openURL({
                    url = controllerUrl .. 'api/s/default/stat/sta',
                    method = 'GET',
                    callback = 'unifi_data'
                })
            end
        
            if (item.trigger == 'unifi_data') then
                local presenceHistory = domoticz.data.presenceHistory

                for mac, device in pairs(devices) do
                    local isPresent = string.find(item.data, mac)
                    
                    presenceHistory.add({
                        ['mac'] = mac,
                        ['isPresent'] = not (isPresent == nil)
                    })
                
                    local wasPresent = presenceHistory.reduce(function(acc, item)
                        if (item.data.mac == mac and item.data.isPresent) then
                            acc = acc + 1
                        end
                        
                        return acc
                    end, 0)
                                       
                    if (wasPresent == 0) then
                        domoticz.devices(device).switchOff().checkFirst()
                    else
                        domoticz.devices(device).switchOn().checkFirst()
                    end
                end
            end
        end
    end
}

Re: Presence detection using UniFi Controller and DzVents

Posted: Tuesday 07 April 2020 22:57
by Delfuego
StasDemydiuk wrote: Tuesday 07 April 2020 21:27 @Delfuego Thank you so much for the script!

I've modified it a bit to allow collect historical data as mobile devices are going to sleep time to time and could be not visible in the network when script polls the UniFi Controller.

With these changes script polls data from controller every minute and it is possible to setup time interval (for my devices I found the most convenient one is 6 min) so device will be considered as offline if it wasn't present in the network during the whole period.
Nice what you did with the script. I had the same issue and solved it by only switching a phone off if it was away for two cycles. Your solution is better because a phone has to be away 6 cycles.

Re: Presence detection using UniFi Controller and DzVents

Posted: Saturday 11 April 2020 16:12
by rudolfpi
Thank you for this script!

Re: Presence detection using UniFi Controller and DzVents

Posted: Wednesday 27 May 2020 16:59
by Decyph
Hey everyone, thanks for this script, been using it for a while now and it works well.

I just updated my unifi controller to 5.12.72 and now a phone which is away for already 3 days still says it is online.
No errors in the log, seems like the api is still giving the mac address as online or the api is not working anymore and it uses old data (if possible).

Any thoughts?

Re: Presence detection using UniFi Controller and DzVents

Posted: Thursday 28 May 2020 10:27
by Delfuego
Hi Decyph,
Nice to here you are using the script.
I myself run Unifi Controller 5.12.72 and Domoticz 2020.2 and everything works fine.
Maybe you can put in "print (item.data)" in the for do loop and study the output in the log (I copied the output to a editor). I really think the problem is not in the software versions of your setup.