Unifi: not seeing away devices!

I made further investigation this morning and I noticed also there is a long delay in controler interface before a device disconnected appears as offline (around at least 10 minutes !) so looks like HA can’t do better !
Only way I would see that would be more efficient who be a ping every 30s or whatever to the device to be sure it’s there or not ! Will have to check if a plugin exists to test such thing in HA…

I haven’t had a chance to check it out yet, but I found this link at some point in my travels:

Not sure if it will help you, if you try it, let us know!

I went finally with Owntracks and updates through my Mosquitto broker and it works great (IP ping is not very efficient due to energy saver algorythm in modern wireless devices !).
I found GPS is lot more efficient :slight_smile:

1 Like

I have a local fix for this. I guess I should get all setup so I can contribute it.

Curious to know how ? as most modern Wifi mobile devices are tricky to detect for sure with energy savings algorythm !

The Unifi controller shows recently connected devices (with 20 minutes or so) on their client list, but also reports a “last_seen” time for each device. I use this last seen time to filter out the devices who haven’t been seen within the “consider_home” timeframe.

Changed line 86 to:

self._clients = {client['mac']: client for client in clients if (dt_util.utcnow() - dt_util.utc_from_timestamp(float(client['last_seen']))) < self.consider_home}

( defined conside_home = config[DOMAIN].get(CONF_CONSIDER_HOME) in get_scanner )

https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/device_tracker/unifi.py

2 Likes

@tloth01 have you checked if you see your wireless devices like phones be considered as away quickly after having left the place ?

Yep, it works. I have my “consider_home” set to 3 minutes, so it takes 3 minutes after disconnecting.

I cant get this to work. Changed line 86

2017-06-13 22:10:03 INFO (MainThread) [homeassistant.loader] Loaded device_tracker.unifi from homeassistant.components.device_tracker.unifi
2017-06-13 22:10:05 INFO (MainThread) [homeassistant.components.device_tracker] Setting up device_tracker.unifi
2017-06-13 22:10:05 ERROR (MainThread) [homeassistant.components.device_tracker] Error setting up platform unifi
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/components/device_tracker/unifi.py", line 67, in get_scanner
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/components/device_tracker/unifi.py", line 76, in __init__
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/components/device_tracker/unifi.py", line 86, in _update
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/components/device_tracker/unifi.py", line 86, in <dictcomp>

Yea, I should setup a pull request, but I haven’t even setup an actual developer environment yet. Too busy with work I get paid for :smiley:

gotta import consider_home:

    from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner, CONF_CONSIDER_HOME)

pass it to UnifiScanner:

return UnifiScanner(ctrl, config[DOMAIN].get(CONF_CONSIDER_HOME)) 

and allow UnifiScanner to receive it:

    def __init__(self, controller, consider_home):
    """Initialize the scanner."""
    self._controller = controller
    self.consider_home = consider_home
2 Likes

Can anyone make a step by step guide to get this to work ?

OMG this is my only pet peeve with this component! I hate that it takes 10-20 minutes for a device to be marked “away”, so I don’t have any automations that require instant updating. Is this everything you’ve changed to update by last_seen? Thanks!

This is my first post, so bear with me.

This, too, is driving me nuts. It definitely is a Unifi problem, as it appears to be holding onto devices for quite a while after they are way out of range.

I took tloth01’s suggestions and modified unifi.py. I’m a Python neophyte (I’m an old-school C and PERL guy), but at least the component loaded without errors. I do not yet know if it works, as I’m not home to test.

Changes:

First, in my device_tracker.yaml file, I added the consider_home variable, set it to 180 minutes.

In unifi.py:

  • Changed the import to include CONF_CONSIDER_HOME exactly like tloth01 said:

    from homeassistant.components.device_tracker import (
    DOMAIN, PLATFORM_SCHEMA, DeviceScanner, CONF_CONSIDER_HOME)

  • Had to add an import for the dt_util functions, otherwise they threw an error. Did this right below the import of CONF_VERIFY_SSL:

    import homeassistant.util.dt as dt_util

  • The rest was exactly like tloth01 said. Modify the return (bold is what I added):

    return UnifiScanner(ctrl, config[DOMAIN].get(CONF_CONSIDER_HOME))

…then add it to the init function:

def __init__(self, controller, consider_home):
“”“Initialize the scanner.”""
self._controller = controller
self.consider_home = consider_home

  • Finally, change the “line 86” (which isn’t line 86 anymore) to tloth01’s version, bold section added:

    elf._clients = {client[‘mac’]: client for client in clients if (dt_util.utcnow() - dt_util.utc_from_timestamp(float(client[‘last_seen’]))) < self.consider_home}

I’ll check later tonight if this actually works and report back. Hope this helps.

An update, tloth01’s fix definitely seems to be an improvement. Much thanks to you, sir!

Tested this morning with a 3-minute consider_home value, and it showed me away within 4 minutes or so (give or take). Much better than the 10+ minutes on the stock code.

To clarify, what I mean by “testing” is simply getting in my car and driving away, not disabling WiFi (which could cause a dissociate with the AP) but simply allowing my signal to fade away as I leave. In this scenario, I have confirmed by watching my Unifi’s console that it does “hold onto” devices for quite some time when they just disappear like this.

One side-effect that I will need to investigate is that one of our iPhones shows away at an odd time last night, when I know it was home. Not sure if this is an iPhone sleeping issue. Playing with the Unifi API, it does include an indication in the client list on whether a device is sleeping, but I don’t know how accurate that is and if it is helpful.

Have problems with Unifi, i got following in my log, Can not understand whats wrong

“2017-08-12 20:49:08 ERROR (MainThread) [homeassistant.components.device_tracker] Error setting up platform unifi
Traceback (most recent call last):
File “/usr/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py”, line 600, in urlopen
chunked=chunked)
File “/usr/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py”, line 345, in _make_request
self._validate_conn(conn)
File “/usr/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py”, line 844, in validate_conn
conn.connect()
File “/usr/lib/python3.6/site-packages/requests/packages/urllib3/connection.py”, line 326, in connect
ssl_context=context)
File "/usr/lib/python3.6/site-packages/requests/packages/urllib3/util/ssl
.py”, line 325, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File “/usr/lib/python3.6/ssl.py”, line 401, in wrap_socket
_context=self, _session=session)
File “/usr/lib/python3.6/ssl.py”, line 808, in init
self.do_handshake()
File “/usr/lib/python3.6/ssl.py”, line 1061, in do_handshake
self._sslobj.do_handshake()
File “/usr/lib/python3.6/ssl.py”, line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/usr/lib/python3.6/site-packages/requests/adapters.py”, line 438, in send
timeout=timeout
File “/usr/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py”, line 630, in urlopen
raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/usr/lib/python3.6/site-packages/homeassistant/components/device_tracker/init.py”, line 153, in async_setup_platform
platform.get_scanner, hass, {DOMAIN: p_config})
File “/usr/lib/python3.6/asyncio/futures.py”, line 331, in iter
yield self # This tells Task to wait for completion.
File “/usr/lib/python3.6/asyncio/tasks.py”, line 244, in _wakeup
future.result()
File “/usr/lib/python3.6/asyncio/futures.py”, line 244, in result
raise self._exception
File “/usr/lib/python3.6/concurrent/futures/thread.py”, line 55, in run
result = self.fn(*self.args, **self.kwargs)
File “/usr/lib/python3.6/site-packages/homeassistant/components/device_tracker/unifi.py”, line 52, in get_scanner
site_id=site_id, ssl_verify=verify_ssl)
File “/usr/lib/python3.6/site-packages/pyunifi/controller.py”, line 89, in init
self._login(version)
File “/usr/lib/python3.6/site-packages/pyunifi/controller.py”, line 148, in _login
r = self.session.post(login_url, params)
File “/usr/lib/python3.6/site-packages/requests/sessions.py”, line 565, in post
return self.request(‘POST’, url, data=data, json=json, **kwargs)
File “/usr/lib/python3.6/site-packages/requests/sessions.py”, line 518, in request
resp = self.send(prep, **send_kwargs)
File “/usr/lib/python3.6/site-packages/requests/sessions.py”, line 639, in send
r = adapter.send(request, **kwargs)
File “/usr/lib/python3.6/site-packages/requests/adapters.py”, line 512, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

The SSL certificate verification failure jumps out at me. Have you tried “verify_ssl: false” in the unifi configuration block?

Tried to submit a pr here. https://github.com/home-assistant/home-assistant/pull/8998
The long code line is tripping up the code checker. Anyone know how to format the line to make it happy?

https://github.com/home-assistant/home-assistant/pull/8998

If anyone wants to test this PR and comment it would be appreciated.

For anyone that finds this thread in the future, the solution discussed above was added to Home Assistant in October 2017.

The Unifi WAP documentation discusses the new feature which is named detection_time:

  • (int)(Optional) How long since the last seen time before the device is marked away, specified in seconds.
  • Default value: 300

The consider_home attribute discussed above is a separate setting that can be added to any tracker device as per the Device Tracker documentation:

  • Seconds to wait till marking someone as not home after not being seen. Allows you to override the global consider_home setting from the platform configuration on a per device level.

One will need to test these settings in their own environment to determine it they help.

2 Likes

Hallo - this looks like a great fix…but it’s for the Unifi WAP and not the Direct component only, right? I’m using Direct solely because I seem unable to use WAP*.

  • because my controller is hosted on my Hass Pi - so I can’t seem to connect to it.