Giulio
Giulio

Reputation: 150

Why mqtt with an autorun script.py can't stabilized the connection with the broker?

I am trying to run automatically a script in python. This script manage several LEDs and communicate via MQTT.

If I try to run the script via shell (no autorun) my connection work without any problem.

If I try to autorun the script, it starts correctly but the connection with the broker keep going up, down, up, down, up,... in an infinite loop. It can not establish the connection.

The autorun script is loaded in /etc/profile -> sudo python3 script/path.py

What could cause this problem?

def Connect(client,broker,port,keepalive,run_forever=False):
    #"""Attempts connection set delay to >1 to keep trying
    #but at longer intervals  """
    connflag=False
    delay=5

    print('--------------------------------')
    print("connecting " + client_id)
    badcount=0 # counter for bad connection attempts
    while not connflag:
        logging.info("connecting to broker "+str(broker))
        print("connecting to broker "+str(broker)+":"+str(port))
        print("Attempts ",badcount)
        try:
            res=client.connect(broker,port,keepalive)      #connect to broker
            if res==0:
                print('--------------------------------')
                print("Connection established")
                print('--------------------------------')
                connflag=True
                return 0
            else:
                logging.debug("connection failed.")
                print('--------------------------------')
                badcount += 1
                if badcount>=3 and not run_forever: 
                    raise SystemExit #give up

                elif run_forever and badcount<3:
                    delay=5
                else:
                    delay=3
[...........................................................]
[..................other stuff.................]
[...........................................................]


def on_connect(client, userdata, flags, rc):
    print('--------------------------------')
    logging.debug("Connected flags"+str(flags)+"result code "  + str(rc) + "client RPi Giulio")
    if rc == 0:
        print("Connected OK. Returned code = ", rc)
        print('--------------------------------')
        client.connected_flag  = True
        client.publish(connected_topic,1,retain=True)

    else:
        print("Bad connection. Returned code = ", rc)
        print('--------------------------------')
        client.bad_connection_flag = True

SOLUTION: CRONTAB https://www.dexterindustries.com/howto/auto-run-python-programs-on-the-raspberry-pi/

Upvotes: 0

Views: 54

Answers (1)

hardillb
hardillb

Reputation: 59751

As stated in the comments this is purely a guess based on the very limited information available.

The usual reason for a client to keep connecting/disconnecting is because you have multiple clients with the same clientid.

You can only ever have 1 client at a time connected to the broker with a given clientid, if a second client connects then the first will be kicked off. If the first client then tries to reconnect it will then kick the second client off and start the sequence again.

Because .profile is run for every login shell you could end up many instances of the client running.

You need to make sure that you only ever start one copy of the client and it has a unique clientid.

Upvotes: 1

Related Questions