Cara menggunakan python mqtt subscribe

Buku ini secara khusus membahas dasar implementasi protokol MQTT untuk membangun aplikasi Internet of Things menggunakan bahasa pemrograman Python. Pada bagian awal dibahas konsep dasar bagaimana protokol MQTT bekerja dengan konsep publish/subscribe. Membahas MQTT broker/server yang populer digunakan disertai dengan contoh penggunaannya. Selain itu diberikan konsep dasar pemrograman Python dan cara penggunaan library Python Paho MQTT pada Raspberry Pi dan komputer berbasis sistem operasi Ubuntu. Buku ini juga membahas implementasi protokol MQTT menggunakan NodeMCU (ESP-8266) dan pemrogramannya menggunakan software Arduino IDE. Pada bagian akhir buku ini dibahas beberapa gambaran ide proyek Internet of Things yang menggunakan protokol MQTT.

Jika Anda kesulitan membeli lewat Google Play Book dapat menghubungi penulis lewat email : [email protected]

We will then create a simple Python example script that subscribes to a topic and publishes messages on that topic.

If all goes well we should see the published messages.

The example scripts are kept simple, and I don’t include any error checking.

I use my own locally installed broker, but you will probably find it easier when starting to use a free online broker like:

  • test.mosquitto.org
  • broker.hivemq.com
  • iot.eclipse.org

Was This Useful?

Cara menggunakan python mqtt subscribe

Installing The Client

You can Install the MQTT client using PIP with the command:

It usually isn’t as straightforward as using the command

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
5
as most machines have multiple versions of python installed and there are several versions of pip and the actual command depends on whether you are on Windows or Linux.

Therefore use the command:

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
6

before installing to find out where pip will install the files.

The screen shot below is taken from my Windows 10 machine where I have two versions of Python installed (3.4 and 3.6)

Cara menggunakan python mqtt subscribe

If I ran

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
5
It would install the client in the 3.6 site packages. To install it for the 3.4 version I would need to run.

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
8

On my Raspberry pi (linux) using the command

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
9

would install the client for use my python version 2.7

Cara menggunakan python mqtt subscribe

To install for version 3.5 I would need to run:

client =mqtt.Client(client_name)
0

Note: if you have multiple versions of python on your machine then take a look at my Python Notes.

Note: On the PI and maybe other linux versions if you get an error on install then use sudo pip install paho-mqtt.

Video- Installing The Mqtt Python Client and Other Modules Using PIP

You will find the online client documentation and also the install files if you need them.

The Python MQTT Client

The core of the client library is the client class which provides all of the functions to publish messages and subscribe to topics.

If you want to look at the code for this class you should find the code in the client.py file in the mqtt directory. (windows machine)

This directory is located in python34\Lib\site-packages\paho\mqtt (windows see Python Notes.)

Where python34 is the root of my python install.

Cara menggunakan python mqtt subscribe

Main Client Methods

The paho mqtt client class has several methods.The main ones are:

  • connect() and disconnect()
  • subscribe() and unsubscribe()
  • publish()

Each of these methods is associated with a callback. See Later.

Importing The Client Class

To use the client class you need to import it. Use the following:

Import paho.mqtt.client as mqtt

Creating a Client Instance

The client constructor takes 4 optional parameters, as shown below .but only the client_id is necessary, and should be unique.

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)

To create a instance use:

client =mqtt.Client(client_name)

See Working with Client objects for more details

Connecting To a Broker or Server

Before you can publish messages or subscribe to topics you need to establish a connection to a broker.

To do this use the connect method of the Python mqtt client.

The method can be called with 4 parameters. The connect method declaration is shown below with the default parameters.

connect(host, port=1883, keepalive=60, bind_address="")

Note: You only need to supply the broker name/IP address.

The general syntax is

client.connect(host_name)

See Working with Client Connections for more details.

Publishing Messages

Once you have a connection you can start to publish messages.

To do this we use the publish method.

The publish method accepts 4 parameters. The parameters are shown below with their default values.

publish(topic, payload=None, qos=0, retain=False)

The only parameters you must supply are the topic, and the payload.

The payload is the message you want to publish.

The general syntax is:

client.publish("house/light","ON")

Example Python Script:

We are now in a position to create our first Python Script to Publish a message.

The script below publishes the message OFF to topic house/main-light


import paho.mqtt.client as mqtt #import the client1
broker_address="192.168.1.184" 
#broker_address="iot.eclipse.org" #use external broker
client = mqtt.Client("P1") #create new instance
client.connect(broker_address) #connect to broker
client.publish("house/main-light","OFF")#publish

Note: I am using my own local broker but you can use an online broker like the one at iot.eclipse.org.

Subscribing To Topics

To subscribe to a topic you use the subscribe method of the Paho MQTT Class object.

The subscribe method accepts 2 parameters – A topic or topics and a QOS (quality of Service) as shown below with their default values.

subscribe(topic, qos=0)


We will now subscribe to topics and in this example we will subscribe to the topic house/bulb1 which is also the same topic that I’m publishing on.

Doing this lets us see the messages we are publishing but we will need to subscribe before we publish.

So our script outline becomes.

  1. Create new client instance
  2. Connect to broker
  3. Subscribe to topic
  4. Publish message

Our new example script is shown below, and I have inserted some print statements to keep track of what is being done.


import paho.mqtt.client as mqtt #import the client1
broker_address="192.168.1.184" 
#broker_address="iot.eclipse.org"
print("creating new instance")
client = mqtt.Client("P1") #create new instance
print("connecting to broker")
client.connect(broker_address) #connect to broker
print("Subscribing to topic","house/bulbs/bulb1")
client.subscribe("house/bulbs/bulb1")
print("Publishing message to topic","house/bulbs/bulb1")
client.publish("house/bulbs/bulb1","OFF")

If we run the script this is what we see:

Cara menggunakan python mqtt subscribe

So where is the message that I published?

When a client subscribes to a topic it is basically telling the broker to send messages to it that are sent to the broker on that topic.

The broker is ,in effect, publishing messages on that topic.

When the client receives messages it generate the on_message callback.

To view those messages we need to activate and process the on_message callback.

Aside: Callbacks are an important part of the Python Client and are covered in more detail in Understanding Callbacks.

Callbacks also depend on the client loop which is covered in Understanding the Client Loop.

However at this stage it may be better to just accept them and proceed with the script.

To process callbacks you need to:

  1. Create callback functions to Process any Messages
  2. Start a loop to check for callback messages.

The describe the on_message callback and the parameters it excepts.

Here is my callback function, which basically just prints the received messages:

def on_message(client, userdata, message):
    print("message received " ,str(message.payload.decode("utf-8")))
    print("message topic=",message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)

Note the message parameter is a message class with members topic, qos, payload, retain.

I.e message.topic will give you the topic.

Now we need to attach our callback function to our client object as follows:

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
0

and finally we need to run a loop otherwise we won’t see the callbacks. The simplest method is to use loop_start() as follows.

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
1

We also need to stop the loop at the end of the script (loop_stop()), and in addition wait a little to give the script time to process the callback, which we accomplish using the time.sleep(4) function.

This what our completed example script now looks like:

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
2

If you run the script you should see the following

Cara menggunakan python mqtt subscribe

Note: logically you should be able to start the loop before you create a client connection, but it you do then you get unexpected results.

Useful Exercises

You should try commenting out, one by one, the lines:

  • client.on_message=on_message
  • client.loop_start()
  • client.Loop_stop()

and run the script to see the results.

Receiving Messages outside of the on_message Callback

A common question is how do you get received messages into the main script from the on-message callback. There are several ways of doing this as explained in Receiving Messages with the Paho MQTT Python Client

Troubleshoot using Logging

To help troubleshoot your applications you can use the built in client logging callback.

To use it you create a function to process the logging callback. My function is shown below and it simply prints the log message.

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
3

and then attach it to the callback:

Client(client_id=””, clean_session=True, userdata=None, protocol=MQTTv311, transport=”tcp”)
4

You should then see details of connections,publish and subscribe messages like that shown below:

Cara menggunakan python mqtt subscribe

The above is a quick overview to get started you can find out more details in the tutorials below:

  • MQTT Subscribe-Python MQTT Client Examples
  • MQTT Publish-Python MQTT Client Examples

Video – Using the Paho Python MQTT Client.

Common Problems

1. Not seeing any messages or not seeing all expected messages.

Possible causes

  1. You haven’t started a network loop or called the loop() function. Or you haven’t registered or created the callback functions.
  2. You haven’t subscribed to the correct topics or subscription has failed.
  3. Access restrictions are in place.

2.- My messages don’t appear in the order I expected?

Possible causes

  1. The callback functions are async functions which can be called at any time. Use a queue to store the messages and print in one place. I use the Python logging module.

——–> MQTT Python Beginners Course

Important Changes for MQTTv5

Although you may not currently be working with MQTTv5 I would advise you to take a look at the Client changes for MQTTv5 tutorial as by making slight changes to your code you can make it future proof.

MQTT Python Kindle Book

If you prefer all of my MQTT pythons tutorials all in one place then you might be interested in my Kindle Book.
Working with the Paho Python MQTT Client

Cara menggunakan python mqtt subscribe

Don't forget to Subscribe to the latest posts and receive notifications of new posts and videos direct to your inbox.