Presence detection using UniFi Controller and DzVents  [Solved]

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Delfuego
Posts: 32
Joined: Sunday 29 July 2018 16:18
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: The Netherlands
Contact:

Presence detection using UniFi Controller and DzVents  [Solved]

Post 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 
}
Last edited by Delfuego on Tuesday 17 December 2019 16:19, edited 5 times in total.
User avatar
papoo
Posts: 126
Joined: Friday 22 January 2016 22:14
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.10
Location: France
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post by papoo »

Thank you
pity that my router is not compatible
mcmikev
Posts: 146
Joined: Tuesday 26 May 2015 8:11
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: right here
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post by mcmikev »

Great script! Did use the crontab version before too, but this is much easier!!
thank you for making it!
CronoS
Posts: 135
Joined: Wednesday 15 July 2015 23:40
Target OS: -
Domoticz version:
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post by CronoS »

Awesome! Works like a charm. Also with my unifi controller on Azure! Thanks
Gerald
Posts: 4
Joined: Monday 30 October 2017 12:59
Target OS: Linux
Domoticz version:
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post by Gerald »

You sir; just made my day :-)
Thanks!
User avatar
Petturik
Posts: 2
Joined: Friday 13 July 2018 13:05
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: NL
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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 !
RPi3b+
Z-Wave(+)
Zigbee
ESP8266
credenty
Posts: 16
Joined: Saturday 12 November 2016 11:07
Target OS: Windows
Domoticz version:
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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?
Delfuego
Posts: 32
Joined: Sunday 29 July 2018 16:18
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: The Netherlands
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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!
dressie
Posts: 156
Joined: Monday 25 May 2015 22:44
Target OS: Raspberry Pi / ODroid
Domoticz version: V2020.2
Location: Netherlands
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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

Flopp
Posts: 279
Joined: Sunday 03 January 2016 14:55
Target OS: -
Domoticz version:
Location: Sweden
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post by Flopp »

This is really nice and easy script. Thank you
cjb75

Re: Presence detection using UniFi Controller and DzVents

Post 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?
Delfuego
Posts: 32
Joined: Sunday 29 July 2018 16:18
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: The Netherlands
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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)
cjb75

Re: Presence detection using UniFi Controller and DzVents

Post 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.
Delfuego
Posts: 32
Joined: Sunday 29 July 2018 16:18
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: The Netherlands
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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.
cjb75

Re: Presence detection using UniFi Controller and DzVents

Post 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!
StasDemydiuk
Posts: 59
Joined: Saturday 14 January 2017 21:37
Target OS: Linux
Domoticz version: Beta
Location: Ukraine
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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
}
Delfuego
Posts: 32
Joined: Sunday 29 July 2018 16:18
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: The Netherlands
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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.
rudolfpi
Posts: 8
Joined: Monday 19 March 2018 18:17
Target OS: Linux
Domoticz version:
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post by rudolfpi »

Thank you for this script!
Decyph
Posts: 10
Joined: Monday 07 November 2016 11:43
Target OS: Linux
Domoticz version: 11838
Location: Hoofddorp, NL
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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?
Delfuego
Posts: 32
Joined: Sunday 29 July 2018 16:18
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: The Netherlands
Contact:

Re: Presence detection using UniFi Controller and DzVents

Post 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.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest