DEV Community

Cover image for Rasp-Pi Network ID tool
Peter G.
Peter G.

Posted on

Rasp-Pi Network ID tool

I needed a tool that could display relevant network information as quick as possible. Armed with a Raspberry Pi 3 B+, 2.13 inch Waveshare e-paper HAT V2, and a curiosity to explore its potential, I set out to develop a tool that could display network data. This was born out of necessity while I was setting up VLANs within PfSense. I got tired of using "ipconfig /release" and "ipconfig /renew" while testing network segregation and firewall rules. I will share that project in an additional post.

I plan making this post as concise as possible. During my research to make this project a reality, I dug through a lot of fluff to find the information I needed.

I assume you know how to flash the OS on to the PI. We will start post Pi imager. I used a fresh 64GB SD card. Also, noticed that the 128GB SD card I had initially used would not boot properly. I did not delve further to determine whether is was the SD card size or some operator error. Usually the latter..



pi@NetworkID:~ $ sudo apt update
pi@NetworkID:~ $ sudo apt upgrade

#install required packages
pi@NetworkID:~ $ sudo apt-get install python3-rpi.gpio python3-spidev python3-pil python3-pip


Enter fullscreen mode Exit fullscreen mode

Next we will enable the SPI interface. We will do this from the raspi-config interface.



pi@NetworkID:~ $ sudo raspi-config


Enter fullscreen mode Exit fullscreen mode

Choose option 3 - Interface options

Interface options

Enable SPI

Enable the SPI interface by selsecting the option. Then select finish when the main screen reappears.



pi@NetworkID:~ $ git clone https://github.com/waveshare/e-Paper.git
Cloning into 'e-Paper'...
remote: Enumerating objects: 8711, done.
remote: Counting objects: 100% (1961/1961), done.
remote: Compressing objects: 100% (264/264), done.
remote: Total 8711 (delta 1745), reused 1778 (delta 1694), pack-reused 6750 (from 1)
Receiving objects: 100% (8711/8711), 42.23 MiB | 307.00 KiB/s, done.
Resolving deltas: 100% (6242/6242), done.
Updating files: 100% (3002/3002), done.



Enter fullscreen mode Exit fullscreen mode

Give it few seconds to clone the repository. When it has finished, navigate to the e-paper directory that was created and run setup.py



pi@NetworkID:~ $ cd e-Paper/RaspberryPi_JetsonNano/python/

pi@NetworkID:~/e-Paper/RaspberryPi_JetsonNano/python $ sudo python3 setup.py install


Enter fullscreen mode Exit fullscreen mode

This is where I made a mistake. I needed to install Python3 Setup Tools and netifaces. These libraries are crucial for proper set up and network interface queries using python.



pi@NetworkID:~/e-Paper/RaspberryPi_JetsonNano/python $ sudo apt install python3-setuptools
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3-setuptools is already the newest version (66.1.1-1).
python3-setuptools set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

pi@NetworkID:~/e-Paper/RaspberryPi_JetsonNano/python $ sudo apt install python3-netifaces



Enter fullscreen mode Exit fullscreen mode

Now lets try to run Setup.py again.
Now after we have all the libraries and configurations correct, let's write some code!



import subprocess
import netifaces
from waveshare_epd import epd2in13_V2
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime

# Initialize e-Paper display
# Specifically for 2.13" V2 
epd = epd2in13_V2.EPD()

# Define fonts
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 12)
font_small = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 10)

def get_network_info(interface):
    try:
        # Get network information for the specified interface
        if interface in netifaces.interfaces():
            addresses = netifaces.ifaddresses(interface)
            ip_address = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            gateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
            mac_address = addresses[netifaces.AF_LINK][0]['addr']
            return ip_address, netmask, gateway, mac_address
        else:
            print(f"Interface {interface} not found.")
            return None, None, None, None
    except Exception as e:
        print(f"Error retrieving network information: {e}")
        return None, None, None, None

def get_ssid(interface):
    try:
        # Execute the iwgetid command to get the SSID of the specified interface
        result = subprocess.run(['iwgetid', interface, '--raw'], capture_output=True, text=True)
        if result.returncode == 0:
            return result.stdout.strip()
        else:
            return "SSID not found"
    except Exception as e:
        print(f"Error retrieving SSID: {e}")
        return "SSID error"

def display_network_info(ip_address, netmask, gateway, mac_address, ssid=None):
    # Create new image with white background (landscape orientation)
    image = Image.new('1', (epd.height, epd.width), 255)
    draw = ImageDraw.Draw(image)

    # Clear display
    epd.init(epd.FULL_UPDATE)
    epd.displayPartBaseImage(epd.getbuffer(image))

    # Draw network information on the display
    draw.text((10, 10), f"IP Address: {ip_address}", font=font, fill=0)
    draw.text((10, 30), f"Subnet Mask: {netmask}", font=font, fill=0)
    draw.text((10, 50), f"Default Gateway: {gateway}", font=font, fill=0)

    # Add timestamp
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    draw.text((10, 70), f"Timestamp: {current_time}", font=font, fill=0)

    # If SSID is available, display it
    if ssid:
        draw.text((10, 90), f"SSID: {ssid}", font=font, fill=0)

    # Display MAC address
    draw.text((10, 110), f"MAC Address: {mac_address}", font=font, fill=0)

    # Rotate the image 90 degrees clockwise
    image = image.rotate(90, expand=True)

    # Display rotated image on the e-Paper display
    epd.init(epd.FULL_UPDATE)
    epd.display(epd.getbuffer(image))

    # Sleep to conserve power
    epd.sleep()

def main():
    # Check for wireless connection first
    # Wirelss connection need to be configured before hand

    if 'wlan0' in netifaces.interfaces():
        interface = 'wlan0'
        ip_address, netmask, gateway, mac_address = get_network_info(interface)
        ssid = get_ssid(interface)
        if ip_address:
            display_network_info(ip_address, netmask, gateway, mac_address, ssid)
    # If no wireless connection, check for wired connection
    # Make sure the name of the interface here matches what is running on your device
    elif 'eth0' in netifaces.interfaces():
        interface = 'eth0'
        ip_address, netmask, gateway, mac_address = get_network_info(interface)
        if ip_address:
            display_network_info(ip_address, netmask, gateway, mac_address)
    else:
        print("No network interface found.")

if __name__ == '__main__':
    main()


Enter fullscreen mode Exit fullscreen mode

I choose to use crontab to run this script at reboot.



pi@NetworkID:~ $ contab -e 

# Use option one, or whichever editor you'd like.
# At the end of the file add this line.

@reboot /usr/bin/python3 /home/pi/network_monitor.py

# This will run the script at each reboot. 



Enter fullscreen mode Exit fullscreen mode

Top comments (0)