From ce2cfd961ebf7777ee412832fa1f27b07f2b2bff Mon Sep 17 00:00:00 2001 From: Mike Cifelli <1836280-mike-cifelli@users.noreply.gitlab.com> Date: Tue, 25 May 2021 13:30:11 -0400 Subject: [PATCH] Delay before querying default route --- wifi-keepalive.py | 53 +++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/wifi-keepalive.py b/wifi-keepalive.py index 0061ac2..514f4dd 100644 --- a/wifi-keepalive.py +++ b/wifi-keepalive.py @@ -10,44 +10,47 @@ PING_INTERVAL_IN_SECONDS = 80 class WifiKeepalive: def __init__(self): - self.defaultRoute = self.getDefaultWifiRoute() + self.defaultRoute = None self.initialDelay = INITIAL_DELAY_IN_SECONDS self.pingInterval = PING_INTERVAL_IN_SECONDS - self.isConnected = True + self.isConnected = False self.pingCommand = 'ping -c 1 -W 2 -n' + self.connectedMessage = 'Connected to Wifi' + self.disconnectedMessage = 'No Wifi Connection' def run(self): - sleep(self.initialDelay) + self.prepare() - while self.isRunning(): + while True: self.keepalive() sleep(self.pingInterval) - def isRunning(self): - return True + def prepare(self): + sleep(self.initialDelay) + self.updateDefaultWifiRoute() + + if self.defaultRoute: + self.connect(preparing=True) + else: + self.disconnect(preparing=True) def keepalive(self): if self.defaultRoute: - self.pingDefaultRoute() + self.connect() + self.ping() or self.updateDefaultWifiRoute() else: - self.attemptWifiConnection() + self.disconnect() + self.updateDefaultWifiRoute() - def pingDefaultRoute(self): - if not self.isConnected: - print('Connected to Wifi', flush=True) + def connect(self, preparing=False): + if not self.isConnected or preparing: + print(self.connectedMessage, flush=True) + self.isConnected = True - self.isConnected = True - isPingSuccess = self.ping() - - if not isPingSuccess: - self.defaultRoute = self.getDefaultWifiRoute() - - def attemptWifiConnection(self): - if self.isConnected: - print('No Wifi Connection', flush=True) - - self.isConnected = False - self.defaultRoute = self.getDefaultWifiRoute() + def disconnect(self, preparing=False): + if self.isConnected or preparing: + print(self.disconnectedMessage, flush=True) + self.isConnected = False def ping(self): try: @@ -57,12 +60,12 @@ class WifiKeepalive: return True - def getDefaultWifiRoute(self): + def updateDefaultWifiRoute(self): defaults = [ r['gateway'] for r in self.getRoutes() if self.isDefaultWifiRoute(r) ] - return defaults[0] if defaults else None + self.defaultRoute = defaults[0] if defaults else None def getRoutes(self): outputLines = check_output(