Auto IP detecting in MQTT configuration file?

Hi, so I’ve built my RPi3 automation script around a python code that connects to the paho MQTT handler in the following manner:

import paho.mqtt.client as paho

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

client1 = paho.Client("MQTTclient")
client1.connect(get_ip_address('wlan0'), 1883)

So, the proccess is dynamic, and I don’t need to care about IP changing after reboots, etc…

But still the only manual work is the “mqtt.cfg” file under “/etc/openhab2/services” which defines

MQTTbroker.url=tcp://192.168.137.118:1883

How can I make this to automatically detect IP like my python script does?

Note: python function that detects IP address from (https://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python/24196955#24196955)

It’s not going to be easy to change mqtt.cfg to dynamically reflect IP address changes to the tcp setting.
One “solution” would be to use a hostname and DNS resolution. You could update (auto) the A Record in DNS to reflect the IP Address changes.
Note that this may have some problems since DNS records will be cached and you may have to restart the MQTT binding in OH2 to re-establish the connection

Ps: Can’t you reserve the IPs in your DHCP?

Thank you but you’re getting too technical for me, I was hoping for a simple solution that only changes the IP address in “mqtt.cfg” without all the hassle of network inter-workings in Linux.

Anyway, reserving the IP in DHCP is good for now, but I still need to think about more robust solution.

Especially that my “mqtt.cfg” file only contains one line, and overwriting it probably isn’t too difficult a task, any IP changes should happen. After that, MQTT broker will be restarted and voila, we’re back in business.

I can’t think of a simpler solution that using a hostname within mqtt.cfg :slight_smile:

Since mqtt.cfg is a flat text config file (without native/internal support for scripts etc), you would have to find an external solution to update it.
One option would be an external script that modifies the file itself. Of course, you would have to see how you would trigger this script. I think that it’s more complicated like this, that’s why I proposed to use a hostname instead of an IP.

Just to clarify: You have a MQTT Broker (Mosquitto?) on a remote host (1) (rPi3?) that is based on dynamic IP Address.
Your OH2 is running on another host (2) (rPi3?) and you are connecting the MQTT Binding on host (2) over the network to the MQTT Broker host (1).
Correct?

1 Like

OH2 and the MQTT broker (mosquitto) are on the same RPi, so only one IP to deal with.

Well… then this should do the trick:

MQTTbroker.url=tcp://localhost:1883

or I am missing something? :slight_smile:

3 Likes