From fbf518e14cb59caad3c459a04be7de35215eb52c Mon Sep 17 00:00:00 2001 From: Pranav Jerry Date: Sun, 14 Nov 2021 19:00:10 +0530 Subject: [PATCH] added class to wait until routable I haven't tested this properly yet --- naxalnet/network.py | 52 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/naxalnet/network.py b/naxalnet/network.py index 9f6a4bf..caa1e80 100644 --- a/naxalnet/network.py +++ b/naxalnet/network.py @@ -30,6 +30,7 @@ examples. import subprocess from pathlib import Path from dasbus.connection import SystemMessageBus +from dasbus.loop import EventLoop NETWORKD_BUS = "org.freedesktop.network1" @@ -118,3 +119,54 @@ class NetworkD: """ for i in self.runtime_path.iterdir(): self.remove_config(i.name) + + +class NetworkLoop(NetworkD): + """Used to wait until a condition is met + + Available methods: + + NetworkLoop.wait_until_routable(timeout=0): + return true when the network is routable, or false when timed out + + """ + + def __init__(self, *args, **kwargs): + # first, initialise the parent object + super().__init__(*args, **kwargs) + self.waitfor = None + self.wait_function = None + self.loop = EventLoop() + + def start_loop(self): + """start the dasbus loop""" + self.proxy.PropertiesChanged.connect(self.on_properties_changed) + self.loop.run() + + def wait_until_routable(self, timeout=0): + """ + wait until timeout in milliseconds and returns True when any + network interface is shown routable by networkd + """ + self.wait_for_change("AddressState", self.on_addressstate_change) + return self.is_routable() + + def wait_for_change(self, name, function): + """used by the public functions""" + self.waitfor = name + self.wait_function = function + self.start_loop() + + def on_addressstate_change(self): + """quit the loop if the network is routable""" + if self.is_routable(): + self.loop.quit() + + def on_properties_changed(self, bus_interface, data, blah): + """give this function some documentation""" + if self.waitfor in data: + return self.wait_function() + + def on_timeout(self): + """called by dasbus when a timeout occurs""" + self.loop.quit()