Experimental function to improve the reliability showing the mdns services. Now it will remove a device only when it's not found a "x" amount of times
@@ -2,6 +2,9 @@ from time import sleep
from socket import inet_ntoa
from .zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf
+current_services = {}
+count_services = {}
+
class MDNSBrowser:
"""
Class for zeroconf multicast DNS service discovery of arduino (esp)
@@ -9,9 +12,12 @@ class MDNSBrowser:
"""
def __init__(self):
+ global count_services
+ global current_services
+
self._zeroconf = None
self._browser = None
- self.services = []
+ self.temp_addresses = []
def start(self):
"""Start zeroconf
@@ -23,6 +29,7 @@ class MDNSBrowser:
handlers=[self.on_service_state_change])
sleep(0.20)
self._zeroconf.close()
+ self.service_check()
def on_service_state_change(self, zeroconf, service_type, name, state_change):
"""Service state change
@@ -46,7 +53,8 @@ class MDNSBrowser:
info = zeroconf.get_service_info(service_type, name)
if(info):
- device['address'] = inet_ntoa(info.address)
+ address = inet_ntoa(info.address)
+ device['address'] = address
device['port'] = info.port
device['weight'] = info.weight
device['priority'] = info.priority
@@ -55,7 +63,32 @@ class MDNSBrowser:
value = value.decode("utf-8")
device[key] = value
- self.services.append(device)
+ count_services[address] = 0
+ current_services[address] = device
+ self.temp_addresses.append(address)
+
+ def service_check(self):
+ """Check Services
+
+ Some times zeroconf can not see a device that was previously connected.
+ With the use of two global variables, it will stop to show a device only
+ if it is not found the number of time in the "threshold" variable.
+ """
+ threshold = 5
+
+ counter = count_services.keys()
+ removed = list(set(counter) - set(self.temp_addresses))
+
+ for address in removed:
+ count_services[address] = count_services[address] + 1
+
+ from copy import deepcopy
+
+ temp_count = deepcopy(count_services)
+ for key, value in temp_count.items():
+ if(value >= threshold):
+ del count_services[key]
+ del current_services[key]
def formated_list(self):
"""List of services
@@ -66,13 +99,11 @@ class MDNSBrowser:
list -- board id and addres (ip)
"""
mdns_list = []
-
- if(bool(self.services)):
- for device in self.services:
-
- address = device['address']
- board = device['board'].capitalize()
- auth = device['auth_upload']
+ if(len(current_services) > 0):
+ for key, value in current_services.items():
+ address = value['address']
+ board = value['board'].capitalize()
+ auth = value['auth_upload']
caption = "{0} ({1})".format(board, address)
mdns_list.append([caption, address, auth])
