2 years ago

#66282

test-img

lorenzo

Python & paho.mqtt: disconnecting after 20 min

I've a problem with a simple python & paho.mqtt code, I report below the code that generates problems purged from connections to the db and other secondary functions


import mysql.connector
import datetime
import json
import paho.mqtt.client as mqtt
import aliveUtil
import logging
from logging.handlers import WatchedFileHandler
import dbconn
from signal import signal, SIGINT, SIGTERM
from sys import exit
import ast
import time

def on_connect(client, userdata, flags, rc):
    if rc == 0:                        
        mqttcR.subscribe([("/xxx/+/retained",1),("/xxx/status/send/#",1)])
              
    else:
        logging.error("Mqtt client retained connection error")
        printOutput("Mqtt client retained connect error")

        
def on_disconnect(client, userdata, rc):
    logging.debug("retained returnCode:"+str(rc))
    printOutput("Disconnect retained returnCode:"+str(rc))
    mqttcR.reconnect()


def on_message(client, obj, msg):
    
    switchMessage(msg)   

def on_publish(client, obj, mid):
    logging.debug("Payload:" + str(obj.payload) + " Mid:" +  str(mid))

def on_subscribe(client, obj, mid, granted_qos):
    logging.debug("Mid:" + str(mid) + " GrantedQos:" + str(granted_qos))

def on_log(client, obj, level, string):
    logging.debug(string)

def printOutput(stringa):   
    logging.info(stringa)

def switchMessage(msg):      
    payload=msg.payload.replace("'", " ")        
    try:
        jsonReceived = json.loads(payload)

    except Exception as exception:
        logging.error('json.load payload')
        logging.error(str(exception))
            
    topic=str(msg.topic)        

    try:
        if topic.find('retained') != -1:            
            saveRetained(jsonReceived)                        

        elif topic.find('status') != -1:            
            saveStatus(jsonReceived)                                   
        
    except Exception as exception:
        logging.error('Try topic exception')
        logging.error(str(exception))        
        logging.error(str(topic))
        #print str(jsonReceived)

def saveRetained(jMessage):   
    print "do something in saveRetained"

    

def saveStatus(jMessage):   
    print "do something in saveRetained"

logging = createWatchedLog('/var/log/xxx/xxx.log')
logging.info('==== START SCRIPT ====')
logging.info('Setup SIGINT signal handler')
signal(SIGINT, get_shutdown_handler('SIGINT received'))
logging.info('Setup SIGTERM signal handler')
signal(SIGTERM, get_shutdown_handler('SIGTERM received'))
logging.info('Setup mqtt client (pyPahoClient)')

unicoID="pythonXXXClient"+str(aliveUtil.randomDigits())
mqttcR = mqtt.Client(client_id=unicoID, clean_session=False)

mqttcR.on_message = on_message
mqttcR.on_connect = on_connect
mqttcR.on_disconnect = on_disconnect
mqttcR.on_publish = on_publish
mqttcR.on_subscribe = on_subscribe


MQTT_Broker = "localhost"
MQTT_Port = 1883
Keep_Alive_Interval = 600

logging.info('Setup mqtt client username e password')
mqttcR.username_pw_set("XXXuser", "xxx")
logging.info('Connect to mqtt broker')

mqttcR.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval))

logging.info('Mqtt loop forever')
mqttcR.loop_forever()

Checking the log file I realized that every 20 minutes the client disconnects and reconnects with the RC 1 message.

2022-01-18 17:14:03,780: INFO: am_alive_mqtt.printOutput():69: Mqtt client connect
2022-01-18 17:14:03,818: DEBUG: am_alive_mqtt.on_subscribe():62: Mid:7 GrantedQos:(1, 1)

2022-01-18 17:34:04,099: DEBUG: am_alive_mqtt.on_disconnect():46: returnCode:1
2022-01-18 17:34:04,101: DEBUG: am_alive_mqtt.on_connect():27: returnCode:0
2022-01-18 17:34:04,101: INFO: am_alive_mqtt.on_connect():30: Mqtt client connect
2022-01-18 17:34:04,145: DEBUG: am_alive_mqtt.on_subscribe():62: Mid:8 GrantedQos:(1, 1)

2022-01-18 17:54:04,412: DEBUG: am_alive_mqtt.on_disconnect():46: returnCode:1
2022-01-18 17:54:04,414: DEBUG: am_alive_mqtt.on_connect():27: returnCode:0
2022-01-18 17:54:04,414: INFO: am_alive_mqtt.on_connect():30: Mqtt client connect
2022-01-18 17:54:04,448: DEBUG: am_alive_mqtt.on_subscribe():62: Mid:9 GrantedQos:(1, 1)

I checked several pages on this site but couldn't find an explanation. Any suggestions?

Many thanks in advance

UPDATE After several tests I discovered that the problem occurs when inside the saveRetained function there is a simple query:

query="SELECT * FROM table_mqtt WHERE serialnumber='"+str(serialnumber)+"'"      
number_of_rows = cursor.execute(query); 
row=cursor.fetchone()

if I comment this part everything works without restarting every 20 min

python

mqtt

paho

0 Answers

Your Answer

Accepted video resources