The appropriate value of max_packets for MQTT loop function - python

I have this code that should run indefinitely, however, it doesn't. It keeps on stopping every few hours from the client's side (stop publishing, the loop keeps on running, but nothing is received at the broker), and the only thing that can be done is to rerun it again.
I was advised here to increase the number of max_packets for the loop function, but it's not working and the client stops publishing randomly without continuing. What should be done? I tried the values of 1, 3, 5, 50 and a 1000 but no use.
Code:
client = mqtt.Client()
client.connect(address, 1883, 60)
while True:
data = getdata()
client.publish("$ahmed/",data,0)
client.loop(timeout=1.0, max_packets = 1) # what should be the parameters here so it doesn't stop publishing?
time.sleep(0.2)

In addition to applications messages which are published/subscribed, MQTT also have internal keepalive to avoid problem of half open TCP connections(1). And it is the responsibility of client to make sure keepalives are sent. As per specification, the broker will disconnect clients which doesn't send keepalives in one and half times of keepalive time interval( in absence of other messages).
In addition to sending messages, the loop()* functions also maintains this keepalive traffic flow between broker and client.
A random try: Try using loop_start() once instead of calling loop() in while loop. E.g.
client = mqtt.Client()
client.connect(address)
#runs a thread in background to call loop function internally.
#In addition, this also reconnects to broker on a lost connection.
client.loop_start()
while True:
data = getdata()
client.publish("$ahmed",data)
client.loop_stop()

Just a random guess... has the client disconnected?
In your code you are not handling any callback like on_disconnect(client, userdata, rc) which is called when the client disconnects from the broker.
def on_disconnect_handler(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection.")
client.on_disconnect = on_disconnect_handler
You are also not checking loop() return value:
Returns MQTT_ERR_SUCCESS on success.
Returns >0 on error.
You should do something like
while True:
rc = client.loop(timeout=1.0)
if rc:
# handle loop error here

Just make the client connect every time the loops is through. I have tested it and connecting to the brokers doesn't any significant extra latency on the flow. Since I have to rerun the program to make work it again, I may as well reconnect the client in the loop, so I don't have to do it myself. This is the rawest idea I could come up with that seems to be working without any problems.
client = mqtt.Client()
client.connect(address, 1883, 60)
while True:
client.connect(address, 1883, 60) # just let it reconnect every time it loops ;)!
data = getdata()
client.publish("$ahmed/",data,0)
client.loop(timeout=1.0, max_packets = 1)
time.sleep(0.2)

Related

Paho mqtt on internet disconnect not running callback

I have this mqtt class
class MQTT():
def __init__(self):
# Observer.__init__(self) # DON'T FORGET THIS
self.mqttClient = paho.Client(client_id=constants.MQTT_CLIENT_ID)
self.mqttClient.username_pw_set(username=constants.MQTT_BROKER_USERNAME, password=constants.MQTT_BROKER_PASSWORD)
# assign mqtt event callbacks
self.mqttClient.on_message = self.on_message
self.mqttClient.on_connect = self.on_connect
self.mqttClient.on_disconnect = self.on_disconnect
self.mqttClient.on_socket_close = self.on_disconnect
self.mqttClient.on_log = self.on_log
def on_disconnect(self,client, userdata, rc):
log("MQTT DISCONNECT:",client, userdata, rc)
and then
mqtt = MQTT()
If i run my code it work perfectly but then i have to run some functions when internet connection is lost. So for that i am using on_disconnect and after running code if turn of network nothing happen. I want some call back to run on Internet connection lost. Do we have any ?
on_disconnect is the right callback for this - the question is when it gets called?
If the network connection is lost your client will only notice it at its next attempt of transmission. So if the client is not about to publish something (or acknowledge a subscription which was received just before the connection dropped) the next transmission will be the PINGREQ
By default keepalive is set to 60 - that means your client will send a PINGREQ every 60 seconds if no other control package was sent within this time interval.
So the on_disconnect callback will be called, it just does not happen as fast as you expected. Try a lower keepalive to improve on this

How to implement a "mailbox" service through mqtt?

I'm a newby to all things mqtt and as a first exercise I wanted to create a “mailbox” service through a persistent mqtt session. The incentive is a low power ESP8266 device that sleeps most of the time and periodically wakes up and checks if there are any pending commands for it.
I tried implementing this through a sender and receiver on my Linux host with python and paho mqtt. Mosquitto is running in the background as the broker.
First here is the "mbox" sender, which sends another message every time Enter is pressed.
import paho.mqtt.client as mqtt
broker_address='127.0.0.1'
client = mqtt.Client('MBoxClient')
client.connect(broker_address)
counter = 1
while True:
print('Press Enter to send msg #'+str(counter)+': ', end='')
if input().startswith('q'):
break
client.publish("mbox/mail","Hello "+str(counter), qos=1)
counter += 1
client.disconnect()
print('done!')
And here is my mbox receiver:
import paho.mqtt.client as mqtt
import time
def on_message(client, userdata, message):
print("message:", message.topic + ': ' + str(message.payload.decode("utf-8")))
print('I\'m listening for mbox messages!')
broker_address="127.0.0.1"
client_name='mbox'
is_first=True
while 1:
client = mqtt.Client(client_name, clean_session=is_first)
is_first=False
print("polling")
client.on_message=on_message
client.connect(broker_address)
client.subscribe('mbox/#',qos=1)
client.loop_start()
time.sleep(0.1) # How long should this time be?
client.loop_stop()
# client.loop(0.1) # why doesn't this do the same action as the previous three lines?
client.disconnect()
time.sleep(5)
Even though this works, I feel that my solution is very hackish. client.loop_start() and client.loop_stop() creates another thread. But when I tried doing client.loop(0.1) instead it didn't work.
So my questions are:
Is there a direct way of polling for a message, instead of the indirect method of using loop_start();…;loop_stop()?
If using loop_start();time.sleep(t);loop_end() is idiomatic, how do I know how long time to sleep for?
Why doesn’t the receiver work when I do loop(0.1); instead of loop_start(); sleep(0.1); loop_stop()`? What is the difference?
Is the receiver guaranteed to receive all the messages?
Is there a better way to implementing this pattern?
Questions answered in order.
No, polling totally defeats the point of a pub/sub protocol like MQTT
You should really be calling client.loop() in a loop, it defaults to only handling 1 packet in the timeout period supplied. QOS 1 needs multiple packets to complete delivery.
calling client.loop(0.1) is going to block for 0.1 seconds waiting for an incoming message, then return. if a message arrives after that 0.1 seconds it's going to sit in the OS TCP/IP stack until you call client.loop() again. If you are not calling it on a regular interval then the broker is going to boot the client because the KeepAlive test will fail. The client loop also handles sending all the subscribe messages.
Assuming the messages are published at QOS > 0 and you have subscribed at QOS > 0 and the client id is kept the same and clean session is false the broker should deliver and messages published while the subscriber is offline
As previously mentioned you need to call client.loop() multiple times per message, as it is you are only calling it once per wake up period. Starting the background thread will handle all the required messages for the length of time you let it run for.

Publish and subscribe both ways using MQTT Python

I currently have a Python program written on the Raspberry Pi 3 to read in humidity and temperature sensor data and publish this data to a topic. I can then receive this data using my laptop. Here is my code for reading sensor data and publishing it to a topic from my Raspberry Pi:
import RPi.GPIO as GPIO
import time
import json
import Adafruit_DHT as dht
import math
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
# Creating the JSON Objects
dht22 = {}
arduino = {}
dht22Temp = []
dht22Hum = []
arduinoLED = []
dht22['temperature'] = dht22Temp
dht22['humidity'] = dht22Hum
dht22['sensor'] = 'DHT22'
arduino['blink'] = arduinoLED
arduino['actuator'] = 'arduinoLED'
# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005
def main():
# Main program block
while True:
h, t = dht.read_retry(dht.DHT22, 17) //Reading humidity and temp data from GPIO17
t = round(t,2)
h = round(h,2)
if t > 25:
if len(arduinoLED) == 3:
arduinoLED.pop(0)
arduinoLED.append("true")
else:
arduinoLED.append("true")
else:
if len(arduinoLED) == 3:
arduinoLED.pop(0)
arduinoLED.append("false")
else:
arduinoLED.append("false")
if len(dht22Temp) == 3:
dht22Temp.pop(0)
dht22Temp.append(t)
else:
dht22Temp.append(t)
if len(dht22Hum) == 3:
dht22Hum.pop(0)
dht22Hum.append(h)
else:
dht22Hum.append(h)
# lm35dzTemp.append(tempc)
# Publishing sensor information by JSON converting object to a string
publish.single("topic/sensorTemperature", json.dumps(dht22), hostname = "test.mosquitto.org")
publish.single("topic/sensorTemperature", json.dumps(arduino), hostname = "test.mosquitto.org")
# Printing JSON objects
print(dht22)
print(arduino)
time.sleep(2)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
Here is my code for subscribing and receiving data from my laptop:
import paho.mqtt.client as mqtt
import json
# This is the Subscriber
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("topic/sensorTemperature")
def on_message(client, userdata, msg):
print(json.loads(msg.payload)) #converting the string back to a JSON object
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)
client.loop_forever()
What I want to do is now publish something from my laptop (perhaps in the same code as the subscriber, or in a separate file that will just publish a message to the same topic - "topic/sensorTemperature"). But my question is: how do I also publish and subscribe to messages on my Raspberry Pi (in my first code that I published)? Since I am publishing messages in an infinite loop to my laptop, I will also need an infinite loop to subscribe to the same (or different topic) to receive messages. How do you run two of these loops at once? Will I need two different threads?
Thank you.
As suggested by Sergey you can use loop_start to create a separate thread for receiving messages.
Here is how your main function will look like:
def main():
# Create a new client for receiving messages
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.subscribe(topic)
client.connect(mqttserver)
client.loop_start()
while True:
#code for publishing
pass
The easiest way is to start another Python process (similar to your laptop's script) on Raspberry in parallel, handling messages received from laptop.
But if you want to implement everything in one script, you can extend your second code fragment (processing messages) with implementation of first fragment (publishing sensors data).
Of course, you can't use loop_forever() in this case. When you call loop_forever(), it will never return until client calls disconnect(), so you can't process received messages (main thread is blocked). Paho client also has routines loop() and loop_start()/loop_stop() to control over network loop.
Take a look on them:
1) Function loop() can take timeout as an argument. It will block until new message arrives or time is out. In first case - preform the processing of received message and calculate time until the next publish. Pass this time as parameter to loop() again. In second case, just publish data and call loop() with time until next publish (2 seconds in your example).
2) loop_start()/loop_stop() starts and stops background thread doing job of sending and receiving(and processing) data for you. Create client, register on_message() callback, connect/subscribe, and call loop_start() to start this thread. Main thread is free for you now - use it with logic of first fragment (loop with 2 seconds sleep).
Simply put your code from subscribing script into publishing script before while True: and replace loop_forever() with loop_start(). Use loop_stop() when you script is exitting before GPIO.cleanup().

mqtt_client does not publish immediately [duplicate]

I am implementing a program that listen to a specific topic and react to it when a new message is published by my ESP8266. When a new message is received from ESP8266, my program will trigger the callback and perform a set of tasks. I am publishing two messages in my callback function back to the topic that the Arduino is listening. However, the messages are published only after the function exits.
Thank you for all your time in advance.
I have tried to use loop(1) with a timeout of 1 second inside the callback function. The program will publish the message immediately, but it seems to stuck in the loop. Will someone be able to give me some pointers how can I execute each publish function immediately in my callback function, instead of when the whole callback completes and return to the main loop_forever()?
import paho.mqtt.client as mqtt
import subprocess
import time
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("ESP8266")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client.publish("cooking", '4')
client.loop(1)
print("Busy status published back to ESP8266")
time.sleep(5)
print("Starting playback.")
client.publish("cooking", '3')
client.loop(1)
print("Free status published published back to ESP8266")
time.sleep(5)
print("End of playback.")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.1.9", 1883, 60)
#client.loop_start()
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
You can't do this, you are already in the message handling loop (that's what called the on_message function) at the point you call publish. This will queue the outgoing messages to be handled by the next iteration of the loop, that's why they are sent once on_message returns.
It hangs when you call the loop method because the loop is already running.
You should not be making blocking (sleep) calls in the on_message callback anyway, if you need to do thing that take time, start up a second thread to do these. By doing this you free up the network loop to handle the outgoing publishes as soon as they are made.

Python Paho MQTT: Unable to publish immediately in a function

I am implementing a program that listen to a specific topic and react to it when a new message is published by my ESP8266. When a new message is received from ESP8266, my program will trigger the callback and perform a set of tasks. I am publishing two messages in my callback function back to the topic that the Arduino is listening. However, the messages are published only after the function exits.
Thank you for all your time in advance.
I have tried to use loop(1) with a timeout of 1 second inside the callback function. The program will publish the message immediately, but it seems to stuck in the loop. Will someone be able to give me some pointers how can I execute each publish function immediately in my callback function, instead of when the whole callback completes and return to the main loop_forever()?
import paho.mqtt.client as mqtt
import subprocess
import time
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("ESP8266")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client.publish("cooking", '4')
client.loop(1)
print("Busy status published back to ESP8266")
time.sleep(5)
print("Starting playback.")
client.publish("cooking", '3')
client.loop(1)
print("Free status published published back to ESP8266")
time.sleep(5)
print("End of playback.")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.1.9", 1883, 60)
#client.loop_start()
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
You can't do this, you are already in the message handling loop (that's what called the on_message function) at the point you call publish. This will queue the outgoing messages to be handled by the next iteration of the loop, that's why they are sent once on_message returns.
It hangs when you call the loop method because the loop is already running.
You should not be making blocking (sleep) calls in the on_message callback anyway, if you need to do thing that take time, start up a second thread to do these. By doing this you free up the network loop to handle the outgoing publishes as soon as they are made.

Categories

Resources