Вы находитесь на странице: 1из 21

2017830 OguiaPahoMQTTPythonClientBeginners

Casa MQTT Rede FAQs

Atualizado: 22 de agosto de 2017 Questionrio

O guia Paho MQTT Python Teste seu


conhecimento
Client-Beginners do MQTT com o
questionrio
O cliente paho
bsico do
MQTT python do
MQTT
Eclipse suporta
MQTT v 3.1 e 3.1.1 e
funciona com o Python 2.7 e 3.x.
Assine o
Instalando o Cliente boletim
informativo
Voc pode instalar o cliente usando PIP com o
comando: E-mail *

Pip install paho-mqtt

Voc encontrar aqui a documentao do cliente Se inscrever!

online . E tambm os arquivos de instalao, se voc


precisar deles.
Enquetes
Esquema do Tutorial
Sobre o que

Neste tutorial, olhamos para o objeto principal do voc gostaria


de aprender
cliente e so mtodos.
mais sobre?

http://www.stevesinternetguide.com/intomqttpythonclient/ 1/21
2017830 OguiaPahoMQTTPythonClientBeginners

Em seguida, criaremos um simples script de Protocolos


exemplo Python que se inscreve em um tpico e de Internet
publica mensagens sobre esse tpico. Rede
domstica
Se tudo correr bem devemos ver as mensagens Rede

publicadas. MQTT
Mosquitto

Os scripts de exemplo so mantidos simples, e no Internet das

incluo nenhuma verificao de erro. Uso meu Coisas


Automao
prprio corretor instalado localmente, mas voc
residencial
provavelmente achar mais fcil ao comear a usar
um corretor online gratuito como:
Voto

Test.mosquitto.org
Ver resultados
Broker.hivemq.com
Iot.eclipse.org

O cliente Python MQTT Anncios


Google
O ncleo da biblioteca do cliente a classe do
cliente que fornece todas as funes para publicar
mensagens e assinar tpicos .
Categorias
Se voc quiser ver o cdigo desta classe, voc deve
Painis
encontrar o cdigo no arquivo client.py no diretrio
Redes
mqtt . (Mquina do Windows)
domsticas
Internet
Este diretrio est localizado em python34 \ Lib \
IOT
site-packages \ paho \ mqtt
Mosquitto
MQTT
Onde python34 a raiz da minha instalao do
Rede
python.
DNS

Projetos

http://www.stevesinternetguide.com/intomqttpythonclient/ 2/21
2017830 OguiaPahoMQTTPythonClientBeginners

Python-
MQTT
Wi-fi

Meu Canal do
Youtube
Mtodos principais do cliente

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:

Importpaho.mqtt.clientasmqtt

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.

http://www.stevesinternetguide.com/intomqttpythonclient/ 3/21
2017830 OguiaPahoMQTTPythonClientBeginners

Client(client_id=,clean_session=True,userdata=None,protoco

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

http://www.stevesinternetguide.com/intomqttpythonclient/ 4/21
2017830 OguiaPahoMQTTPythonClientBeginners

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:

http://www.stevesinternetguide.com/intomqttpythonclient/ 5/21
2017830 OguiaPahoMQTTPythonClientBeginners

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


importpaho.mqtt.clientasmqtt#importtheclient1
broker_address="192.168.1.184"
#broker_address="iot.eclipse.org"#useexternalbroker
client=mqtt.Client("P1")#createnewinstance
client.connect(broker_address)#connecttobroker
client.publish("house/mainlight","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

Para se inscrever em um tpico, use o mtodo de


inscrio do objeto Paho MQTT Class.

O mtodo de subscrio aceita 2 parmetros - Um


tpico ou tpicos e um QOS (qualidade de servio)
conforme mostrado abaixo com seus valores
padro.

Inscreva-se (tpico, qos = 0)

Agora vamos subscrever tpicos e, neste exemplo,


subscreveremos o tpico house / bulb1 que

http://www.stevesinternetguide.com/intomqttpythonclient/ 6/21
2017830 OguiaPahoMQTTPythonClientBeginners

tambm o mesmo tpico em que estou


publicando.

Fazendo isso, nos permite ver as mensagens que


estamos publicando, mas precisaremos subscrever
antes de publicarmos.

Ento, nosso esboo do script se torna.

1. Criar nova instncia de cliente


2. Conecte-se ao corretor
3. Assine o tpico
4. Publicar mensagem

Nosso novo script de exemplo mostrado abaixo e


inseri algumas declaraes de impresso para
acompanhar o que est sendo feito.


importpaho.mqtt.clientasmqtt#importtheclient1
broker_address="192.168.1.184"
#broker_address="iot.eclipse.org"
print("creatingnewinstance")
client=mqtt.Client("P1")#createnewinstance
print("connectingtobroker")
client.connect(broker_address)#connecttobroker
print("Subscribingtotopic","house/bulbs/bulb1")
client.subscribe("house/bulbs/bulb1")
print("Publishingmessagetotopic","house/bulbs/bulb1")
client.publish("house/bulbs/bulb1","OFF")

If we run the script this is what we see:

http://www.stevesinternetguide.com/intomqttpythonclient/ 7/21
2017830 OguiaPahoMQTTPythonClientBeginners

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 where
sent to 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 except


them and proceed with the script.

To process callbacks you need to:

http://www.stevesinternetguide.com/intomqttpythonclient/ 8/21
2017830 OguiaPahoMQTTPythonClientBeginners

1. Create callback functions to Process any


Messages
2. Start a loop to check for callback messages.

The client docs describe the on_message callback


and the parameters it excepts.

Here is my callback function, which basically just


prints the received messages:

defon_message(client,userdata,message):
print("messagereceived",str(message.payload.decode("utf8")))
print("messagetopic=",message.topic)
print("messageqos=",message.qos)
print("messageretainflag=",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.on_message=on_message#attachfunctiontocallback

and finally we need to run a loop otherwise we


wont see the callbacks. The simplest method is to
use loop_start() as follows.

http://www.stevesinternetguide.com/intomqttpythonclient/ 9/21
2017830 OguiaPahoMQTTPythonClientBeginners

client.loop_start()#starttheloop

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:


importpaho.mqtt.clientasmqtt#importtheclient1
importtime
############
defon_message(client,userdata,message):
print("messagereceived",str(message.payload.decode("utf8")))
print("messagetopic=",message.topic)
print("messageqos=",message.qos)
print("messageretainflag=",message.retain)
########################################
broker_address="192.168.1.184"
#broker_address="iot.eclipse.org"
print("creatingnewinstance")
client=mqtt.Client("P1")#createnewinstance
client.on_message=on_message#attachfunctiontocallback
print("connectingtobroker")
client.connect(broker_address)#connecttobroker
client.loop_start()#starttheloop
print("Subscribingtotopic","house/bulbs/bulb1")
client.subscribe("house/bulbs/bulb1")
print("Publishingmessagetotopic","house/bulbs/bulb1")
client.publish("house/bulbs/bulb1","OFF")
http://www.stevesinternetguide.com/intomqttpythonclient/ 10/21
2017830 OguiaPahoMQTTPythonClientBeginners

time.sleep(4)#wait
client.loop_stop()#stoptheloop

If you run the script you should see the following

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.

Troubleshoot using Logging

To help troubleshoot your applications you can use


the built in client logging callback.

http://www.stevesinternetguide.com/intomqttpythonclient/ 11/21
2017830 OguiaPahoMQTTPythonClientBeginners

To use it you create a function to process the


logging callback. My function is shown below and it
simply prints the log message.

defon_log(client,userdata,level,buf):
print("log:",buf)

and then attach it to the callback:

client1.on_log=on_log

You should then see details of connections,publish


and subscribe messages like that shown below:

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

Common Problems

1. Not seeing any messages or not seeing all


expected messages.

Possible causes

1. You havent started a network loop or called the


loop() function. Or you havent registered or
http://www.stevesinternetguide.com/intomqttpythonclient/ 12/21
2017830 OguiaPahoMQTTPythonClientBeginners

created the callback functions.


2. You havent subscribed to the correct topics or
subscription has failed.
3. Access restrictions are in place.

2.- My messages dont 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.

Related Tutorials and Resources

MQTT overview for Beginners


Installing and Testing The Mosquitto MQTT
Broker
My Python Working Notes

Please rate? And use Comments to let me know


more
[Total: 33 Average: 3.6/5]

15 comments

Alican KAYIKCI says:


March 21, 2017 at 1:22 am

Hello,
im trying to write o code which gets tempreture value
and write it to a file. But my code getting stuck if there
http://www.stevesinternetguide.com/intomqttpythonclient/ 13/21
2017830 OguiaPahoMQTTPythonClientBeginners

is no broker and then when i try to execute code with


broker code does not give any response. im using
loop_start() func. And i understood that there is a
thread on the backround working. So is there a way to
stop loop properly when there is no broker or stop the
code with ctrl + c. Thank you

Reply

steve says:
March 21, 2017 at 5:02 pm

Hi
When the broker disconnects you get a
on_disconnect callback.
Put the loop_stop() call in there.
Here is a copy of my on_dicconect()
def on_disconnect(client, userdata, rc):
m=disconnecting reason ,str(rc)
logging.info(m)
client.connected_flag=False
client.disconnected_flag=True

Note: I use a flag to stop the loop because I normally


dont use the loop_start.
So yous would be:
def on_disconnect(client, userdata, rc):
loop_stop()

rgds
steve

Reply

nit says:
http://www.stevesinternetguide.com/intomqttpythonclient/ 14/21
2017830 OguiaPahoMQTTPythonClientBeginners

April 12, 2017 at 5:35 am

how to write our own mosquitto broker? could you


explain the code needed there

Reply

steve says:
April 12, 2017 at 7:52 am

Hi
Ive never written one but if you download the
testing suite here
there is a python broker which you can study.

Reply

Sohum says:
April 15, 2017 at 12:17 am

Hey! Amazing tutorial. Thank you.

I am trying out some of the things that you have


shown. I am able to subscribe to a topic, and have the
message show up in my Python console. So the loops,
and the call back configuration seems to be all set.

I am trying to compare the message that I am receiving


to a known string. How do I do that?
So basically, I need message.payload.decode(utf-8) to
be equal to a string variable(thats just variable for
Python I guess) and then in an if-statement inside the
loop, I am trying to get the code to compare it for every
iteration of the loop to a string. Once it is equal, the if

http://www.stevesinternetguide.com/intomqttpythonclient/ 15/21
2017830 OguiaPahoMQTTPythonClientBeginners

statement will run clientName.disconnect() and


.loop_stop()

I tried, under the def on_message, to do that by doing


this:
messCon = str(message.payload.decode(utf-8)) and
also down inside the loop. At both places it is either
Invalid syntax or that my variable messCon is not
defined.

I am at a loss on how to get this to work.

Any help is appreciated.

-Sohum

Reply

steve says:
April 15, 2017 at 7:58 am

Hi
that looks about right it may just be the if statement
missing the ==

if messConn==str(message.payload(uft-8):
clientName.disconnect()
loop_stop()

Reply

Chris Smyth says:


April 15, 2017 at 12:18 pm

http://www.stevesinternetguide.com/intomqttpythonclient/ 16/21
2017830 OguiaPahoMQTTPythonClientBeginners

This was a massive help to me, just starting with mqtt


(and Python) and this really got things moving. Thank
you.

Reply

steve says:
April 15, 2017 at 4:42 pm

Chris
Tks for your comments.Glad you found it useful
Steve

Reply

corydon says:
May 8, 2017 at 12:13 pm

Hi Steve,
I have a few question, hope you could help me out.
Q1. Which party generates the Callback? regarding the
on_connect(). It looks like the client generates after it
gets ACK message from broker. Is my understanding
correct?
How about on_message()

Q2. I am not clear of the meaning of


def on_connect(Client, userdate, flag, rc):
client.on_connect=on_connect

It looks On_Connect() has been defined in client


module already. To me , it just need to check the value
of rc to make judgment.

Thanks very much!


http://www.stevesinternetguide.com/intomqttpythonclient/ 17/21
2017830 OguiaPahoMQTTPythonClientBeginners

corydon

Reply

steve says:
May 8, 2017 at 3:52 pm

Yes you are correct the CONNACK triggers the


callback (on_connect).
The client.on_connect() method is defined in the
MQTT class.
the statement
client.on_connect=on_connect
replaces the method defined in the class with the
one you define in your script called on_connect().
Does that Make Sense?
Rgds
Steve
P.S I just did a video on client connections which you
may find helpful
https://youtu.be/vT4FTRgipOM

Reply

YK says:
August 7, 2017 at 2:17 pm

this question might be silly, but is the broker address


referring to my pc ip address?

Reply

steve says:
August 8, 2017 at 8:15 am

http://www.stevesinternetguide.com/intomqttpythonclient/ 18/21
2017830 OguiaPahoMQTTPythonClientBeginners

The broker address is the address of the machine


running the NQTT broker. You can use public
brokers like
test.mosquitto.org,broker.hivemq.com,iot.eclip
se.org.

Reply

YK says:
August 8, 2017 at 12:24 pm

If im using my PC as a localhost for the broker


then the address should be my pc ip address, am
i right? Or can i just type in localhost when i
assign the value into the broker_address
variable?

Reply

steve says:
August 9, 2017 at 8:33 am

Either should work. You might find these two


articles useful
http://www.steves-internet-guide.com/host-
name-resolution-methods-explained/
http://www.steves-internet-guide.com/hosts-
file/

Reply

YK says:
August 9, 2017 at 2:05 pm

http://www.stevesinternetguide.com/intomqttpythonclient/ 19/21
2017830 OguiaPahoMQTTPythonClientBeginners

thanks a lot.

Leave a Reply

Seu endereo de email no ser publicado. Campos


obrigatrios so marcados *

Comente

Nome *

E-mail *

Local na rede Internet

Comente

Mapa do site | Sobre e Contato | Divulgao


Copyright 2011-2017 Steve's Internet Guide
Por Steve Cope

http://www.stevesinternetguide.com/intomqttpythonclient/ 20/21
2017830 OguiaPahoMQTTPythonClientBeginners

http://www.stevesinternetguide.com/intomqttpythonclient/ 21/21

Вам также может понравиться