diff --git a/internet_usage/internet_usage_counter.py b/internet_usage/internet_usage_counter.py new file mode 100644 index 0000000..3f59d4c --- /dev/null +++ b/internet_usage/internet_usage_counter.py @@ -0,0 +1,35 @@ +""" +Using dbus, listen for network interface changes and update the internet usage +type='signal', interface='org.freedesktop.NetworkManager' +It writes disconnect and connect times to a file +""" +from pydbus import SystemBus +from gi.repository import GLib +import datetime + +# The path to the file where the internet usage is stored. +USAGE_FILE = "/home/inex/dev/Linux/internet_usage/usage.txt" + +session_bus = SystemBus() +loop = GLib.MainLoop() + +def handle_state_change(state): + if state == 70: + # The network interface is connected. + # Write the current time to the file. + with open(USAGE_FILE, "a") as usage_file: + usage_file.write(f"{datetime.datetime.now()} CONNECT\n") + + elif state == 50: + # The network interface is disconnected. + # Write the current time to the file. + with open(USAGE_FILE, "a") as usage_file: + usage_file.write(f"{datetime.datetime.now()} DISCONNECT\n") + +# Get the NetworkManager object. +nm = session_bus.get("org.freedesktop.NetworkManager") + +nm.StateChanged.connect(handle_state_change) + +loop.run() +