eclipse / paho.mqtt.python

paho.mqtt.python
Other
2.19k stars 721 forks source link

Receiving MQTT_ERR_NO_CONN when re-using connection #693

Closed badgerwithagun closed 9 months ago

badgerwithagun commented 1 year ago

I have a simple script which connects at the beginning:

mq = paho.Client ( qId)
mq.username_pw_set ( uid, pw)
mq.connect ( host, port, 30

Then re-uses this connection in an async callback:

def callback( data ):
    global mq, topic, host, port
    try:
        res = mq.publish ( topic, data )
        if res.rc != paho.MQTT_ERR_SUCCESS:
            print("Error {} when publishing".format(res.rc))
        elif
            print("Success")

I get "Success" occasionally, but mostly get the error (MQTT_ERR_NO_CONN)

Are there are any issues with sharing connections between threads?

If so, is there a better way of doing this?

I've tried reconnecting whenever I get that error, in case I can slowly bootstrap all the threads, but the constant failures persist.

ralight commented 1 year ago

Are you using a call to any of the loop*() functions anywhere? If not, your connection will fail due to the background networking not being completed. Use loop_forever() (which blocks) where your application does not need to do anything other than respond to MQTT callbacks, and loop_start() (which starts a thread and so does not block) where your application has other tasks to achieve.

MattBrittan commented 9 months ago

I'm going to close this due to inactivity (hopefully Rogers comment helped).

Note: This is part of an exercise to clean up old issues so that the project can move forwards. Due to the number of issues being worked through mistakes will be made; please feel free to reopen this issue (or comment) if you believe it's been closed in error.