0

I am using python mosquitto(paho) library. I got the problem of Unexpected disconnection. I found constantly dropping and connection with the server. . I am unable to find the problem. some times it shows [Error 104] connection reset by peer. I hosted my broker on amazon web services... my error is ---

Connected to xx.xx.xx.xx:1883

Unexpected disconnection.

Connected to xx.xx.xx.xx:1883

Unexpected disconnection.

Connected to xx.xx.xx.xx:1883

I am passing QOS=2, retain = true, clean session =false, no username and password, lwt =none , port= 1883, ip = server hosted on aws, client id = publisher

My code includes---

import time
import paho.mqtt.client as mqtt

class MqttCommunication(object):

    def __init__(self):

        self.current_module = "Mqtt Communication class"
        self.clientID = clientId
        self.name = thread_name

        self.DEBUG = True
        self.MQTT_HOST = ""
        self.MQTT_PORT = 1883
        self.MQTT_USERNAME = ""
        self.MQTT_PASSWORD = ""
        self.MQTT_CLIENT_ID = self.clientID
        self.MQTT_TOPIC = ""
        self.MQTT_QOS = 0
        self.MQTT_RETAIN = None
        self.MQTT_CLEAN_SESSION = None
        self.MQTT_LWT = ""

        self.client = mqtt.Client(self.MQTT_CLIENT_ID,          clean_session=self.MQTT_CLEAN_SESSION)
        self.on_connect = None
        self.on_disconnect = None
        self.on_message = None
        self.on_subscribe = None
        self.on_unsubscribe = None
        self.on_publish = None
        self.client.on_connect = self.mqtt_on_connect
        #self.client.on_message = self.mqtt_on_message
        self.client.on_disconnect = self.mqtt_on_disconnect
        self.client.on_subscribe = self.mqtt_on_subscribe
        self.client.on_unsubscribe = self.mqtt_on_unsubscribe
        self.client.on_publish = self.mqtt_on_publish



    def connectHost(self,mqtt_host,mqtt_port,mqtt_username,mqtt_password):
        self.MQTT_USERNAME = mqtt_username
        self.MQTT_PASSWORD = mqtt_password
        self.MQTT_HOST = mqtt_host
        self.MQTT_PORT = mqtt_port

        try:
            self.client.username_pw_set(self.MQTT_USERNAME, self.MQTT_PASSWORD)
            print self.client.connect(self.MQTT_HOST,self.MQTT_PORT,60)
            print self.MQTT_HOST

        except Exception, e:
            print "Error connecting to %s:%d: %s" % (mqtt_host, mqtt_port, str(e))

        return True

    def disconnectHost(self):
        self.client.disconnect()
        return True

    def mqttSettings(self,qos,mqtt_retain,mqtt_clean_session,mqtt_lwt):
        self.MQTT_QOS = qos
        self.MQTT_RETAIN = mqtt_retain
        self.MQTT_CLEAN_SESSION = mqtt_clean_session
        self.MQTT_LWT = mqtt_lwt
        return True

    def subscribeTopic(self,topic):
        self.MQTT_TOPIC = topic
        self.client.subscribe(self.MQTT_TOPIC, qos=self.MQTT_QOS)
        return True

    def unsubscribeTopic(self,topic):
        self.client.unsubscribe(self.MQTT_TOPIC)
        return True

    def setClientId(self,clientID):
        self.MQTT_CLIENT_ID= clientID
        return True

    def getClientId(self):
        return self.MQTT_CLIENT_ID

    def publishData(self,topic,message,qos):
        self.client.publish(topic,message,qos)
        return True


    # The callback for when the client receives a CONNACK response from the server.
    def mqtt_on_connect(self,client, userdata, flags, rc):
        if rc == 0:
            print "Connected to %s:%s" % (self.MQTT_HOST, self.MQTT_PORT)
            time.sleep(3)

        elif rc == 1:
            print "Connection refused - unacceptable protocol version"
        elif rc == 2:
            print "Connection refused - identifier rejected"
        elif rc == 3:
            print "Connection refused - server unavailable"
        elif rc == 4:
            print "Connection refused - bad user name or password"
        elif rc == 5:
            print "Connection refused - not authorised"
        else:
            print "Connection failed - result code %d" % (rc)



    # The callback for when a PUBLISH message is received from the server.
    def mqtt_on_message(self , client, userdata, msg):
        #print msg
        print(msg.topic+" : "+str(msg.payload))

    def mqtt_on_disconnect(self, client, userdata, rc):
        if rc != 0:
            print("Unexpected disconnection.")
        else:
            print('hello from disconnect')

    def mqtt_on_publish(self, client, userdata, mid):
        """
        What to do when a message is published
        """
        #print "publish"


    def mqtt_on_subscribe(self,client, userdata, mid, granted_qos):
        """
        What to do in the event of subscribing to a topic"
        """
        #logging.debug("Subscribe with mid " + str(mid) + " received.")


    def mqtt_on_unsubscribe(self, client, userdata, mid):
        """
        What to do in the event of unsubscribing from a topic
        """
        #logging.debug("Unsubscribe with mid " + str(mid) + " received.")

sharing some logs from log file....

1483168399: Client publisher already connected, closing old connection.
1483168399: Client publisher disconnected.
1483168399: New client connected from xx.xx.xx.xx as publisher (c0, k60).
1483168401: New connection from xx.xx.xx.xx on port 1883.
1483168401: Client publisher already connected, closing old connection.
1483168401: Client publisher disconnected.
1483168401: New client connected from xx.xx.xx.xx as publisher (c0, k60).
1483168404: New connection from xx.xx.xx.xx on port 1883.
1483168404: Client publisher already connected, closing old connection.
1483168404: Client publisher disconnected.
1483168404: New client connected from xx.xx.xx.xx as publisher (c0, k60).
1483168405: New connection from xx.xx.xx.xx on port 1883.
1483168405: Client publisher already connected, closing old connection.
1483168405: Client publisher disconnected.
1483168405: New client connected from xx.xx.xx.xx as publisher (c0, k60).
1483168408: New connection from xx.xx.xx.xx on port 1883.
1483168408: Client publisher already connected, closing old connection.
1483168408: Client publisher disconnected.
1483168408: New client connected from xx.xx.xx.xx as publisher (c0, k60).
1483168410: New connection from 27
hardillb
  • 54,545
  • 11
  • 67
  • 105
Himanshu mittal
  • 155
  • 5
  • 16
  • 1
    Update the question with the code so we can see how you're using the library and also some information about if all the clients are on the same machine or network – hardillb Dec 28 '16 at 16:58
  • 1
    Once the client is connected, the network traffic between the client and the mosquitto broker needs to be processed. This will avoid that the connection is shut by timeout. So if you are using paho you need to add `self.client.loop_start()` after you call the `self.client.connect(...)` function. – Hicaro Dec 29 '16 at 17:11
  • @Hicaro I included it but i am facing same problem again.. – Himanshu mittal Dec 31 '16 at 06:47
  • @Hicaro if you explain the reason why this happens. – Himanshu mittal Dec 31 '16 at 06:51
  • @hardillb shared some log from log file. if you help me how can i overcome using python or using any other method – Himanshu mittal Dec 31 '16 at 07:18
  • By your logs it seems you are trying to connect the same client more than once. Then the broker disconnects the older connection for that client. Could you also share the code where you use the class `MqttComunication`? – Hicaro Dec 31 '16 at 10:34

1 Answers1

1

You have multiple connections using the same client_id.

client_id's have to be unique, the broker will only allow one connection with a client_id at a time and will kick the oldest one off the broker when a new connection is formed. If you have reconnection logic in place then the old client will try and reconnect which will kick the new client off, this ends up in a feed back loop with no client managing to stay connected to the broker.

It looks like you have hard coded your client_id to "publisher" from the logs, this needs to be changed to be a unique value, normally I would set a to a prefix like "pub_" then add on a random number, a timestamp or some other identifier (e.g. thread number/name)

hardillb
  • 54,545
  • 11
  • 67
  • 105
  • I tried that too. now I am getting this error from mosquitto log table. 1483418758: Socket error on client mqttjs_e0cbe1a, disconnecting. 1483418793: Client 2017-01-03 09:54:40.930093 has exceeded timeout, disconnecti$ 1483418793: Socket error on client 2017-01-03 09:54:40.930093, disconnecting. 1483418822: New connection from xx.xx.xx.xx on port 1883. – Himanshu mittal Jan 03 '17 at 04:55
  • That is separate problem, most likely because your not staying the network loop. Ask a new question with your updated code and log output – hardillb Jan 03 '17 at 08:27
  • This bit us recently, our Python code was using `None` so the Paho code auto-generated our ID. But the C++ devs had hardcoded their ID and the first time we tried to have two instances talking to the broker, the connections went up and down like a yoyo. – paxdiablo Jul 27 '23 at 09:07