Mqtt and Python - How to Use Hostname in Topic?

I am a total newbie to MQTT and Python on my Raspi. However, by using search and "G" a lot, I made it as far as I can capture and publish temperatures. Too make things more simple in managing the data, I'd like to use the hostname in the topic.

So far I do:

client.publish("data/humidity_rel", "%.2f" %humidity)

what I'd like to do is using the hostname which I get like this

import socket
socket.gethostname()
host = socket.gethostname()

I thought my topic should look like

client.publish("host/data/humidity_rel", "%.2f" %humidity) but simply adding "host" like this doesn't work.

tried all kinds of syntax but w/o success

Any help appreciated

1 Answer

Neither the MQTT spec or the Paho Python MQTT client implementation will do what you want automatically, it's up to you to do the string substitution yourself.

client.publish(host+"/data/humidity_rel", "%.2f" %humidity)

or

client.publish('%s/data/humidity_rel' % host, "%.2f" %humidity)

or

client.publish('{}/data/humidity_rel'.format(host), "%.2f" %humidity)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest