User avatar
phaze3131
Posts: 45
Joined: Thu Apr 30, 2015 3:50 am

MQTT "Topic" Question

Sun Oct 18, 2015 11:32 pm

I have my Rpi all setup running a python program that makes it an MQTT broker (that can control an LED).

I am using openhab as a virtual MQTT client, but am just very confused by what the "topic" should be in this line of item configuration:

Item itemName {mqtt="<direction>[<broker>:<topic>:<type>:<trigger>:<transformation>]" }

Here is my line:
Switch node2_sw1 "sw2" (node2,all) {mqtt=">[mysensor:XXXXXXXXX:command:ON:1],>[mysensor:XXXXXXXX:command:OFF:0]"}

Where the "XXXXXXXXX" is the part I'm unsure about.

Thanks for any help.

User avatar
DougieLawson
Posts: 39124
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: MQTT "Topic" Question

Sun Oct 18, 2015 11:41 pm

MQTT topics are any valid string that matches the protocol specification for topics or a fragment of a topic with a wildcard character.

http://www.hivemq.com/blog/mqtt-essenti ... -practices
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

User avatar
phaze3131
Posts: 45
Joined: Thu Apr 30, 2015 3:50 am

Re: MQTT "Topic" Question

Sun Oct 18, 2015 11:59 pm

Hey Doug, like always thanks for the reply. I read that before I posted and I still am not sure what my "topic" would be in my case.

Or maybe the answer is, the "topic" doesn't matter for my case as long as it follows the specification?

Edit1.0: just read your sig, and saw the MQTT Evangelist :) I just learned what it was the other day and how I can use it in my automation research, so I will keep reading and keep working on understanding it.

Edit1.1: Figured I might add the python code I am using on my pi broker (maybe it might help)

Code: Select all

import paho.mqtt.client as paho
import RPi.GPIO as GPIO
import json, time

# device credentials
device_id        = 'admin'      # * set your device id (will be the MQTT client username)
device_secret    = '313131'  # * set your device secret (will be the MQTT client password)
random_client_id = 'MQTT'      # * set a random client_id (max 23 char)

# -------------- #
# Board settings #
# -------------- #
buttonPin = 7
ledPin = 12

GPIO.setmode(GPIO.BOARD)  # use P1 header pin numbering convention
GPIO.cleanup()            # clean up resources
GPIO.setup(ledPin, GPIO.OUT)   # led pin setup
GPIO.setup(buttonPin, GPIO.IN)   # button pin setup


# --------------- #
# Callback events #
# --------------- #

# connection event
def on_connect(client, data, flags, rc):
    print('Connected, rc: ' + str(rc))

# subscription event
def on_subscribe(client, userdata, mid, gqos):
    print('Subscribed: ' + str(mid))

# received message event
def on_message(client, obj, msg):
    # get the JSON message
    json_data = msg.payload
    # check the status property value
    print(json_data)
    value = json.loads(json_data)['properties'][0]['value']
    if value == 'on':
        led_status = GPIO.HIGH
        GPIO.output(ledPin, GPIO.HIGH)
    else:
        led_status = GPIO.LOW
        GPIO.output(ledPin, GPIO.LOW)

    # confirm changes to Leylan
    client.publish(out_topic, json_data)


# ------------- #
# MQTT settings #
# ------------- #

# create the MQTT client
client = paho.Client(client_id=random_client_id, protocol=paho.MQTTv31)  # * set a random string (max 23 chars)

# assign event callbacks
client.on_message = on_message
client.on_connect = on_connect
client.on_subscribe = on_subscribe


# device topics
in_topic  = 'devices/' + device_id + '/get'  # receiving messages
out_topic = 'devices/' + device_id + '/set'  # publishing messages

# client connection
client.username_pw_set(device_id, device_secret)  # MQTT server credentials
client.connect("178.62.108.47")                   # MQTT server address
client.subscribe(in_topic, 0)                     # MQTT subscribtion (with QoS level 0)

# ------------ #
# Button logic #
# ------------ #

prev_status = GPIO.LOW
led_status  = GPIO.LOW
updated_at  = 0  # the last time the output pin was toggled
debounce    = 0.2  # the debounce time, increase if the output flickers

# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
    rc = client.loop()
    button = GPIO.input(buttonPin)

    if button != prev_status and time.time() - updated_at > debounce:
        prev_status = button
        updated_at  = time.time()

        if button:
            led_status = not led_status
            button_payload = 'off'
            if led_status == GPIO.HIGH:
                button_payload = 'on'
            # effectively update the light status
            GPIO.output(ledPin, led_status)
            payload = { 'properties': [{ 'id': '518be5a700045e1521000001', 'value': button_payload }] }
            client.publish(out_topic, json.dumps(payload))

print('rc: ' + str(rc))
Edit1.2: the actual code says what the topics are, I just blindly didn't look hard enough.
devices/<DEVICE-ID>/get
Just not sure if it's 'get' or 'set' because the broker is receiving the clients request to change the light so I think it will be 'get'

User avatar
DougieLawson
Posts: 39124
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: MQTT "Topic" Question

Mon Oct 19, 2015 7:22 am

Your program has two topics

devices/<DEVICE-ID>/get (this one is subscribed for command & control)
devices/<DEVICE-ID>/set (this one is published for results from your sensor)

So you could use devices/# to subscribe to all of your devices, or devices/<DEVICE-ID>/# to subscribe to both the set and get topics. Or if you have multiple sensors subscribe to devices/+/set to read all of the results on a single subscription. And finally devices/+/get to publish c&c messages to every sensor.

It's quite versatile and the # or + wildcards let you cross hierarchical boundaries in your topic tree.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

User avatar
phaze3131
Posts: 45
Joined: Thu Apr 30, 2015 3:50 am

Re: MQTT "Topic" Question

Mon Oct 19, 2015 10:35 pm

perfect answer, definitely makes alot more sense, ty again Doug!

Return to “Beginners”