- Я хочу установить paho-mqtt с помощью этой команды: sudo apt-get install python-pip
- 2 ответа
- Paho Python MQTT Client – Publish With Examples
- Publishing a Message
- On_publish Callback
- Message Flow and Quality of Service Example
- Publishing on Restricted Topics
- Retain Message Flag
- Disconnecting After Publish
- Publishing and The Loop
- Publishing Using SSL
- Publishing Using WebSockets
- Publishing Video
- Common Questions and Answers
- Q- Do I know if and when my published messages have been received by a client?
- Q- What happens if I publish on the wrong topic?
- Q- What happens if I publish on a restricted topic?
- Q- How do I know that no one else is using that topic?
- Q- Can I publish on any topic that I want to?
- Course Links
- 41 comments
Я хочу установить paho-mqtt с помощью этой команды: sudo apt-get install python-pip
Я хочу установить paho-mqtt с помощью этой команды:
sudo apt-get install python-pip Collecting paho-mqtt Exception: Traceback (most recent call last): File «/usr/lib/python2.7/dist-packages/pip/basecommand.py», line 215, in main status = self.run(options, args) File «/usr/lib/python2.7/dist-packages/pip/commands/install.py», line 353, in run wb.build(autobuilding=True) File «/usr/lib/python2.7/dist-packages/pip/wheel.py», line 749, in build self.requirement_set.prepare_files(self.finder) File «/usr/lib/python2.7/dist-packages/pip/req/req_set.py», line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File «/usr/lib/python2.7/dist-packages/pip/req/req_set.py», line 554, in _prepare_file require_hashes File «/usr/lib/python2.7/dist-packages/pip/req/req_install.py», line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File «/usr/lib/python2.7/dist-packages/pip/index.py», line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File «/usr/lib/python2.7/dist-packages/pip/index.py», line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File «/usr/lib/python2.7/dist-packages/pip/index.py», line 568, in _get_pages page = self._get_page(location) File «/usr/lib/python2.7/dist-packages/pip/index.py», line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File «/usr/lib/python2.7/dist-packages/pip/index.py», line 792, in get_page «Cache-Control»: «max-age=600», File «/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py», line 501, in get return self.request(‘GET’, url, **kwargs) File «/usr/lib/python2.7/dist-packages/pip/download.py», line 386, in request return super(PipSession, self).request(method, url, *args, **kwargs) File «/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py», line 488, in request resp = self.send(prep, **send_kwargs) File «/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py», line 609, in send r = adapter.send(request, **kwargs) File «/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/adapter.py», line 47, in send resp = super(CacheControlAdapter, self).send(request, **kw) File «/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/adapters.py», line 423, in send timeout=timeout File «/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/connectionpool.py», line 643, in urlopen _stacktrace=sys.exc_info()[2]) File «/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/util/retry.py», line 315, in increment total -= 1 TypeError: unsupported operand type(s) for -=: ‘Retry’ and ‘int’
2 ответа
pip — это менеджер пакетов python, он работает много, как apt, но для пакетов python. apt-get install python-pip устанавливает только пип. Он не устанавливает никаких пакетов. вместо этого попробуйте:
pip install paho-mqtt
, и если это не работает (часто это не так), попробуйте
sudo pip install paho-mqtt
Вы можете указать версию python (убедитесь, что она установлена перед вами попытайтесь использовать его;))
Paho Python MQTT Client – Publish With Examples
In this tutorial we will look at how you publish messages using the Paho Python MQTT client.
We will use an example python script to publish messages, process the publish acknowledgements and examine QOS (quality of service) settings.
To publish a messages you use the publish method of the Paho MQTT Class object.
The publish method accepts 4 parameters. The parameters are shown below with their default values.
The only parameters you must supply are the topic, and the payload.
The payload is the message you want to publish.
Publishing a Message
To publish a message you need to:
- Create a client object.
- Create a client connection.
- publish the message
- Examine the return code of the publish request
- Examine the publish acknowledgement using the on_publish callback
Note 1: you don’t appear to need a client loop to process the on_publish callback.
Note2: When you publish a message the publish method returns a tuple (result, mid).
The result is the error code. A result of 0 indicates success.
The mid value is an integer that corresponds to the published message number as assigned by the client.
The mid value can be used with the on_publish callback to check that the messages was published.
On_publish Callback
When the message has been published to the Broker an acknowledgement is sent that results in the on_publish callback being called.
The on_publish callback function must receive three parameters
The client is the client object, and is useful when you have multiple clients that are publishing data.
The userdata is user defined data which isn’t normally used.
The mid value is the message id and can be used with the mid value returned from the publish method to check that a particular message has been published.
In the screen shot below I have printed the mid value from the publish message and on publish callback.
You can see that the numbers match which indicated that both messages were published OK
Message Flow and Quality of Service Example
If you want to try and ensure that the subscriber gets a message even though they might not be online then you need to publish with a quality of service of 1 or 2.
The schematic below shows the message flow between client and broker for messages with QOS of 0, 1 and 2.
The screen shot below shows the results of running a test Python script that publishes 3 messages with QOS of 0,1 and 2 respectively
Notice with QOS set to 2 there are more messages generated.
In addition messages sent with QOS of 0 are not acknowledged by the broker but instead by the sending client.
There is no guarantee that the broker received them. See:
Publishing on Restricted Topics
You may not be allowed to publish messages on certain topics.
However what happens if you do publish on a restricted topic?
Well as far as the client is concerned the publish succeeds, and if I run the previous script but restrict the topic then my client output would be identical to that shown above.
However this is what I would see on the Sever (broker)
Notice the denied publish message on the server console. Also notice the normal publish acknowledgement sequence.
Retain Message Flag
When publishing a message you can also set the retain message flag.
This flag tells the broker to store the last message that you sent.
This is very useful if you only publish messages at infrequent intervals- See Retained messages-Example’
Disconnecting After Publish
If you only publish messages at infrequent intervals then you will probably want to disconnect the client between publishing.
You can use the disconnect method along with the on_disconnect callback for this.
This type of disconnect does not result in a last will and testament message.
Publishing and The Loop
Although you can publish messages without starting a loop (See the Loop) you will need to start a loop or call the loop to send automatic ping messages.
Therefore you may find that your client gets disconnected , and without the loop you don’t see the disconnect message.
Therefore if you do this you will need to consider setting the keepalive to a higher value (60 seconds by default).
Note: If you publish messages inside the keep alive value then the connection isn’t closed by the server/broker.
Publishing Using SSL
You will need to add a broker/server CA key to the client, See Configuring Mosquitto for SSL for details about keys.
You then use the client.tls_set function before you connect. E.G.
Depending on how you’ve configured the broker you may need to use the TLS version parameter (code below set client to use TLSv1.2.
Because SSL normally uses port 8883 you will also need to change the port when connecting.
Publishing Using WebSockets
You can also publish messages over webSockets. You need to tell the client to use Websockets when creating the client object as show below:
Use the command
client= paho.Client(“control1”,transport=’websockets’)
instead of simply
client= paho.Client(“control1”)
The publish uses the same procedure and process as standard MQTT. See My MQTT WebSockets Notes
Publishing Video
Here is a video that I created that covers the main points from above. Grateful of any feedback
Common Questions and Answers
Q- Do I know if and when my published messages have been received by a client?
A- No. You only know that the broker has received them, and then only if the QOS is set to 1 or above.
Q- What happens if I publish on the wrong topic?
A- Generally unless the topic has an invalid topic address you wont know.
Q- What happens if I publish on a restricted topic?
A- You wont know as it will appear to succeed.
Q- How do I know that no one else is using that topic?
A- You don’t. You could subscribe to the topic beforehand and look for activity.
Q- Can I publish on any topic that I want to?
A- Yes unless the broker administrator has configured topic restrictions.
Course Links
41 comments
on_publish callback is called when an ack is sent, when the message has been published. How should I check if the ACK is not received? I need some kind of indication if the message is not published (ack not received) to log an error.
Hi
You need to set a timer and wait for the puback. If you haven’t got it after x secs then raise an error
Rgds
Steve
Hello Steve, I have a python script that starts an mqtt client and subscribes to a topic /motor. I have a JavaScript application that publishes messages to the topic /motor. Most of the time the message is processed instantaneously on the python side but sometimes the message is processed between 5 and 10 seconds. How can I debug this to find the causes of the slowness? Thank you
Hi
Are you sure it is the python script and not the Javascript one. Can you see the message being sent? Are you using a local broker.
If you are still stuck edit the Javascript script and send the message to the public broker test.mosquitto.org on topic sig/mapsy/test then use the ask steve page and send me the python script and I will take a look
rgds
Steve
Yes I receive message in python script, just sometimes it take times.
My python script is like this :
#!/usr/bin/env python3
#– coding: utf-8 —
import paho.mqtt.client as mqtt
import json
import base64
import os
# subscription to 10 topics
def on_connect(client, userdata, flags, rc):
log_event(“Connected to the MQTT server success with rc :” + str(rc))
client.subscribe(“topic1”)
client.subscribe(“topic2”)
client.subscribe(“topic3”)
client.subscribe(“topic4”)
client.subscribe(“topic5”)
client.subscribe(“topicXX”)
client.publish(“topic20”, “<\”status\”:\”ON\”>”)
def on_message(client, userdata, msg):
payload_string = msg.payload.decode(‘utf-8’)
if msg.topic == “topic1”:
print(“on message topic 1”)
if msg.topic == “topic2”:
print(“on message topic 2”)
if msg.topic == “topic3”:
print(“on message topic 3”)
if msg.topic == “topic4”:
print(“on message topic 4”)
if msg.topic == “topic5”:
print(“on message topic 5”)
client = mqtt.Client(“myClientId”)
client.username_pw_set(username=”login”, password=”password”)
client.on_connect = on_connect # Define callback function for successful connection
client.on_message = on_message # Define callback function for receipt of a message
client.connect(‘localhost’, 1883)
def process():
client.loop_start()
def my_thread_1(cient, killer):
#….. LOOP WHILE (true)
def my_thread_2(cient, killer):
#….. LOOP WHILE (true)
def my_thread_3(cient, killer):
#….. LOOP WHILE (true)
if __name__ == “__main__”:
try:
thread1 = Process(target=my_thread_1, args=(client, killer))
thread1.start()
thread2= threading.Thread(target=my_thread_2,)
thread2.start()
thread3 = threading.Thread(target=my_thread_3, args=(args[“frame_count”],))
thread3.daemon = True
thread3.start()
except KeyboardInterrupt:
print(“KeyboardInterrupt”)
#In main function I start 4 thread and client.loop_start() function
I do receive the messages in the on_message method in python but sometimes in a totally random way the messages are received with a delay between 5 and 10 seconds.
My javascript code is located in a react native application
would you like me to send you the app to download? you can submit posts in topics.
Does it have a way to improve the speed of message transmission?
Not sure why you are starting threads. Can you explain what the script should do. If you can get the react script to publish to the public broker test.mosquitto.org I can pick up your data there use topic sig/mapsy/test.
Contact me on the ask steve page and we can talk via email
rgds
steve
Hi Steve! Thank you for the excellent material.
I posted this on another page, but I think this is the correct place to put it, so, sorry to repost here. I’m having trouble using QoS 2 in the publish function of the Paho library for Python. Here is the scenario: I have the Mosquitto broker installed on one computer and, on another computer, I am using 2 Python scripts (publisher and subscriber) to do some tests. To validate these scripts, I have used Mosquitto on the command line (to test the subscriber script, I publish with Mosquitto on the command line and also the other way around). The publisher script works correctly for QoS 0 and 1, but does not publish anything when I set QoS to 2. The subscriber script works correctly with QoS 2 (I tested it by publishing via the Mosquitto command line). The function I have used is this:
ret = client1.publish (topic, message, qs, retain = True)
On the tuple returned by method, the result value is always 0 (sucess).
where qs is an integer that I assign to previous lines. I’ve also tried with qos = qs, but it doesn’t publish anything.
Any idea where I might be going wrong?
Hi what version of the client are you using?
Hi Steve,
I want to send 1000 messages per second from client to broker. How to do that?
You will need to put the publish in a while loop and send . I doubt if you will get 100 messages per second.
Below is code I use on my tester. Adjust the delay to increase/decrease the message rate.
topic_out=”test”
delays=[0.1,0.005,0.001]
delay=delays[0]
count=1
stime=time.time()
loops=10000
topic_logger=True
#topic_logger=False
logging_test_json=True
#logging_test_json=False
topic1=”test/sensor1″
topic2=”test/sensor2″
Why time.sleep(2) recommend to use after publish call ?
Hi Its isn’t recommended it just stops lots of messages being published.
rgds
steve
how to publish current date n time? this is my code. thx.
# import paho mqtt
import paho.mqtt.client as mqtt
# import time untuk sleep()
import time
# import datetime untuk mendapatkan waktu dan tanggal
import datetime
# definisikan nama broker yang akan digunakan
broker_address=”localhost”
# buat client baru bernama P2
print(“creating new instance”)
client = mqtt.Client(“P2”)
# koneksi ke broker
print(“connecting to broker”)
client.connect(broker_address, port=3333)
# mulai loop client
client.loop_start()
# lakukan 20x publish topik 1
print(“publish something”)
for i in range (20):
# sleep 1 detik
time.sleep(1)
# publish waktu sekarang topik 1
print(“Publishing message to topic”,”1″)
client.publish(“1”)
#stop loop
client.loop_stop()
Hi
try
localtime = time.localtime(time.time())
client.publish(“1”,localtime)
Dear Mr. Steve
I appreciated your contribution. I try to create my own test system based on your tutorials.
Step 1. Install mosquitto on window machine and execute some test cases. Everything is OK
Step 2. Install paho in ubuntu machine. Write a client code by python to connect with Window machine.
I start mosquitto_sub on window machine and try to publish a message from ubuntu.
cmd terminal command
mosquitto_sub -t ‘test/topic2’
Code python in ubunutu in ex2.py
import paho.mqtt.client as paho
broker=”192.168.203.76″
port=1883
def on_publish(client,userdata,result): #create function for callback
print(“data published \n”)
pass
client1= paho.Client(“control1”) #create client object
client1.on_publish = on_publish #assign function to callback
client1.connect(broker,port) #establish connection
ret= client1.publish(“test/topic2″,”hello from ubuntu”) #publish
terminal command
$python ex2.py
(0,1)
Nothing displayed on terminal on window.
I already checked the network connection b/w 2 machines. It was fine. Is there any specific configuration in Mosquitto broker on window? Is possibility when the network firewall or something that terminated message? How can I check MQTT publish message flow from ubuntu machine.
The only thing that looks wrong is the mosquitto_sub doesn’t have the -h broker switch. Is that a typo?
rgds
steve
Hello, I have to use mqtt and for that i am going through your tutorial and i have a silly doubt like the code you have written in this tutorial for publishing messages, i used that code only and run it in jupyter notebook with a mosquitto broker, the code is running fine but i want to know:
where can i see the messages which i have published ?
can we have two way communication ?
can i send a video file through this ?
How can we store messages ?
Hi
To see messages that you have published you need to subscribe to the topics that you are publishing on.
Take a look here
http://www.steves-internet-guide.com/python-mqtt-publish-subscribe/
and for the file sending
http://www.steves-internet-guide.com/send-file-mqtt/
rgds
steve
Thanks for reply.
If other person wants to see the message which i have published how can he see the message he has to subscribe to the topic right but for that subscribe code has to run, my question is:
subscribe code can be run seperately. If yes, then how, like you have told in one of your tutorial we have to subscribe before publishing, but other person need not to be publish only we publish the message and other persons just have to read it.
sorry for the bad english.
Yes the other person needs to subscribe. If he hasn’t subscribed and the message is published then he misses the message.
MQTT works like TV. If your not watching TV when the 9pm news is on you miss it.
“”””For Publisher””””
import paho.mqtt.client as mqtt
broker = “test.mosquitto.org”
port = 1883
def on_publish(client, userdata, result):
print(“data published \n”)
pass
client1 = mqtt.Client(“control1”)
client1.on_publish = on_publish
client1.connect(broker, port)
client1.loop_start()
sub = client1.subscribe(“simpletext/msg”)
print(sub)
ret = client1.publish(“simpletext/msg “,”Hello good morning have a good day”)
print(ret)
client1.loop_stop()
output:-
(0,1)
(0,2)
data published
import paho.mqtt.client as mqtt
broker = “test.mosquitto.org”
port = 1883
client1 = mqtt.Client(“control1”)
client1.connect(broker, port)
client1.loop_start()
sub = client1.subscribe(“simpletext/msg”, 2)
print(sub)
client1.loop_stop()
The thing is that for subscriber also message is not displayed it is giving an output in tuple form as you can see.
Help me to clarify my doubts.
Hi Subscribing to a topic doesn’t return a message.
Messages are captured in the on_message callback.
See
http://www.steves-internet-guide.com/into-mqtt-python-client/
rgds
steve
Thanks Steve for helping me out and guiding me through my first mqtt program which did work.
I will be here again if i need some help .
Thanks a lot Steve.
Best Regards
Ankur
I run on a rpi 3 with IO Pi Plus extender board and I want to run a python script that communicate with openhab2 through mqtt messages
from IOPi import IOPi
import time
import paho.mqtt.client as mqtt
#import json
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)
if (message.retain == 0):
#print(“mqtt received”,message.topic,”=”,str(message.payload.decode(“utf-8”)))
#print(message.topic,str(message.payload.decode(“utf-8”)))
torec = print(message.topic,str(message.payload.decode(“utf-8”)))
# Create client instance and connect to localhost
client = mqtt.Client()
bus1 = IOPi(0x20)
bus2 = IOPi(0x21)
bus2.set_pin_direction(1, 1) # set pin 1 as an input
bus2.set_pin_pullup(1, 1) # enable the internal pull-up resistor on pin 1
bus2.invert_pin(1, 1) # invert pin 1 so a button press will register as 1
bus1.set_pin_direction(1, 0) # set pin 8 as an output
bus1.write_pin(1, 0) # turn off pin 8
client.connect(“localhost”,1883,60)
client.subscribe(“#”)
client.on_message=on_message
#print(“connecting to broker”)
client.loop_start() #start the loop
if (bus2.read_pin(1) == 1) and (bus1.read_pin(1) == 0) or (torec == “light/l01 ON”): # check to see if the button is pressed
print (‘button 1 pressed turn on switch 1’) # print a message to the screen
print(torec)
#value = bus2.read_interrupt_capture(0)
bus1.write_pin(1, 1) # turn on pin 1
client.publish(“light/l01”, “ON”)
time.sleep(1) # sleep 1s before checking the pin again
elif (bus2.read_pin(1) == 1) and (bus1.read_pin(1) == 1) or (torec == “light/l01 OFF”):
print (‘button 1 pressed turn off switch 1’) # print a message to the screen
print(torec)
bus1.write_pin(1, 0) # turn off pin 1
client.publish(“light/l01”, “OFF”)
time.sleep(1) # sleep 1s before checking the pin again
#time.sleep(1) # wait
client.loop_stop() #stop the loop
if __name__ == “__main__”:
main()
I have a problem when I run it. It send mqtt messeges just fine but it only receives only whatever send it from the code. It doesnt reveive messeges from other source.
The connect,subscribe,loop_start and stop should be outside the while loop. Correct that and try again.
If you still have problems use the ask-steve page and send me the code.
Rgds
Steve
Thank you that was the problem. Now if you can help me about the variable. When I run the shell it always print and the 0 that was declared at the begging and after that print the topic at it should.
Can you email me the script
Rgds
steve