rmoesbergen / openwrt-ha-device-tracker

OpenWRT device tracker for Home Assistant that actually works
99 stars 17 forks source link

[Feature Request] Time for reconnection #50

Open Otamay opened 1 month ago

Otamay commented 1 month ago

Hi,

I have some devices that loses connection due to power management or bad signal quality, and then reconnect almost immediately. Another reason is disconnecting from current AP and then connecting to alternative AP on the same router. So in HA I have multiple offline/online events breaking the device online time continuity.

Could some logic be implemented so that the device tracker publish a device as not seen, only if has been offline for at least X seconds?

I tried some basic stuff but as the program is event-driven, I think another thread must exist that handles the devices current status. I don't know yet if there is a simpler way.

Best regards, your program is so useful.

Otamay commented 1 month ago

I sort of implemented this request by creating a timer thread when a disconnection occurs. After 5 seconds, the function id does a full scan and checks if the disconnected device is online. If it's not, then adds sets the device as away.

I need more proper testing to know its reliability, but it works. I also think a single timer should exist per device so if multiple reconnections occur in the time window, the old timer should be cancelled prior to creating a new one. Also I need to add the timeout argument to the settings.

What do you think?

New method in PresenceDetector class:

    def set_device_away_if_timeout(self, interface: str, device: str) -> None:
        if not self._should_handle_device(device):
            return

        def s(interface: str, device: str):
            self._do_full_sync()
            for intf, dev in self._last_seen_clients:
                if device == dev:
                    return
            self.set_device_away(interface, device)
        Timer(5, s, [interface, device]).start()

Also modified UbusWatcher object creation argument:

watcher = UbusWatcher(interface, self.set_device_home, self.set_device_away_if_timeout)

rmoesbergen commented 1 month ago

Hi @Otamay , thanks for reporting this issue and providing a possible fix. Regarding this issue disconnecting from current AP and then connecting to alternative AP on the same router. : the latest version should fix that. It takes care of devices moving from one WiFi interface to another on the same router. The quick reconnect/disconnect is another issue though, I'll have to think a bit more about that, and will take your code into account (it seems quite simple, so that's good). This used to work in version 1.X, but got lost in the 2.X event driven rewrite unfortunately. I'll let you know when I come up with something.