Delay before querying default route

This commit is contained in:
Mike Cifelli 2021-05-25 13:30:11 -04:00
parent 9d6be61051
commit ce2cfd961e
1 changed files with 28 additions and 25 deletions

View File

@ -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(