davesteele / comitup

Bootstrap Wifi support over Wifi
https://davesteele.github.io/comitup/
GNU General Public License v2.0
322 stars 54 forks source link

Q: how to check for comitup/WiFi status in Python #116

Closed marcelstoer closed 4 years ago

marcelstoer commented 4 years ago

This is related to #93.

What is the most simple (= lowest complexity) or generally recommended way to check for the comitup/WiFi status in Python? I would like to dump information onto a display:

marcelstoer commented 4 years ago

This is a slight deviation of the above idea and at least works. It's missing the first step (AP y/n, don't know how).

import socket
import pynmcli

def is_connected():
    try:
        socket.create_connection(("1.1.1.1", 53))
        return True
    except OSError:
        pass
    return False

def get_wifi_status():
    def extract_nmcli_line_value():
        return line.split(":")[1].strip()

    status = dict()
    nmcli_lines = pynmcli.NetworkManager.Device().show("wlan0").execute().split("\n")
    for i in range(0, len(nmcli_lines)):
        line = nmcli_lines[i]
        if line.startswith("GENERAL.STATE:"):
            status["state"] = extract_nmcli_line_value()
        elif line.startswith("GENERAL.CONNECTION:"):
            status["ssid"] = extract_nmcli_line_value()
        elif line.startswith("IP4.ADDRESS[1]"):
            status["ip-address"] = extract_nmcli_line_value()

    return status

net_status = dict()
internet_status = dict()

net_status["wifi"] = get_wifi_status()
net_status["internet"] = internet_status

internet_status["connected"] = is_connected()

print(net_status)
davesteele commented 4 years ago

You can get most of this from the Comitup dbus interface (python-dbus), and the rest from the NetworkManager dbus or nmcli. See the comitup 8 man page.

marcelstoer commented 4 years ago

python-dbus

That's the keyword I needed, thanks! As you might have guessed I'm not familiar with D-Bus and Python isn't my home turf. I had looked at the comitup man page before and wondered how to get into a position to call the methods documented there.

>>> import dbus
>>> bus = dbus.SystemBus()
>>> comitup = bus.get_object("com.github.davesteele.comitup", "/com/github/davesteele/comitup")
>>> print(comitup.get_info())
dbus.Dictionary({dbus.String('version'): dbus.String('1.10'), dbus.String('apname'): dbus.String('comitup-72'), dbus.String('hostnames'): dbus.String('comitup-72.local'), dbus.String('imode'): dbus.String('single')}, signature=dbus.Signature('ss'))
>>> print(comitup.state())
(dbus.String('CONNECTED'), dbus.String('***-redacted-***'))

The more I work with comitup the more I appreciate this fantastic project and how you run it. Thanks!