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...
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)