Skip to content

Add IP Sensors #234

@Yoanf26

Description

@Yoanf26

Is it possible to add the IP address values? Indeed, I have a Raspberry Pi which is connected via Ethernet and Wifi on two different networks. And I would like to retrieve the IP addresses in values for my HA. I tried it on my side in a separate file and it works with dependencies of "rpi-mqtt-monitor". Here is the code I used:

import psutil
import socket
import json
import time
import paho.mqtt.client as mqtt

# MQTT Configuration
MQTT_BROKER = "x.x.x.x"
MQTT_PORT = 1883
MQTT_USERNAME = None
MQTT_PASSWORD = None
MQTT_DISCOVERY_PREFIX = "homeassistant"
MQTT_CLIENT_ID = "rpi-ip-test"
PUBLISH_INTERVAL = 3600

def get_hostname():
    return socket.gethostname()

def get_ip_addresses():
    ip_dict = {}
    interfaces = psutil.net_if_addrs()

    for interface, addrs in interfaces.items():
        for addr in addrs:
            if addr.family == socket.AF_INET and not addr.address.startswith("127."):
                ip_dict[interface] = addr.address
    return ip_dict

def send_discovery_and_state(ip_data):
    hostname = get_hostname()
    client = mqtt.Client(client_id=MQTT_CLIENT_ID)

    if MQTT_USERNAME and MQTT_PASSWORD:
        client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)

    try:
        client.connect(MQTT_BROKER, MQTT_PORT, 60)

        for interface, ip in ip_data.items():
            state_topic = f"{MQTT_CLIENT_ID}/ip/{interface}"
            discovery_topic = f"{MQTT_DISCOVERY_PREFIX}/sensor/{MQTT_CLIENT_ID}/{interface}/config"
            unique_id = f"{hostname}_{interface}_ip"

            payload = {
                "name": f"{hostname} {interface}",
                "state_topic": state_topic,
                "unique_id": unique_id,
                "device": {
                    "identifiers": [hostname],
                    "name": hostname,
                    "model": "Raspberry Pi",
                    "manufacturer": "Raspberry"
                },
                "icon": "mdi:ip-network"
            }

            client.publish(discovery_topic, json.dumps(payload), retain=True)
            client.publish(state_topic, ip, retain=True)

            print(f"[MQTT] {interface} → {ip}")

        client.disconnect()

    except Exception as e:
        print(f"Erreur MQTT : {e}")

if __name__ == "__main__":
    while True:
        ip_data = get_ip_addresses()
        if ip_data:
            send_discovery_and_state(ip_data)
        else:
            print("No IP address detected.")
        time.sleep(PUBLISH_INTERVAL)

I thought, great, I'll now adapt it to contribute to the "rpi-mqtt-monitor" contribution, but I can't seem to get it to work. Is it possible to integrate it?

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions