1

I have a mqtt broker which I am connecting through python.

I want to check if I am able to connect to my broker and trigger a mail if my connection is successful.

I intend to use a global variable connected and if this is false after trying to connect I trigger an alarm.

My code:

import paho.mqtt.client as mqtt 
import time

broker_address="ip"
port = "port"

global connected


def mqttConnection():
    connected = False
    print(connected)
    client = mqtt.Client("BrokerCheck",clean_session=True) #create new instance
    client.on_connect = on_connect
    print('Connecting to broker')
    client.connect(broker_address, port=port) #connect to broker

def on_connect(client, userdata, flags, rc):
    if rc==0:
        print("connected OK Returned code=",rc)
        connected = True
    else:
        print("Bad connection Returned code=",rc)



if __name__ == '__main__':
    mqttConnection()
    time.sleep(60)
    if connected:
        pass
    else:
        #trigger an alarm

But I have a problem with my global variable connected. Am I using it in a right way?

chink
  • 1,505
  • 3
  • 28
  • 70
  • The assignment to `connected` creates a local variable that shadows the global of the same name within the scope defined by `mqttConnection`. – chepner Aug 29 '19 at 16:13
  • where you able to connect with broker_address="ip", port = "port" declared as variables and then passing them to connect? – Sardar Faisal Aug 15 '23 at 12:15

2 Answers2

1

You need to specify the variable as global within the scope of each function that you want to assign to it from. For example:

connected = None

def mqttConnection():
    global connected
    connected = False
    print(connected)
    client = mqtt.Client("BrokerCheck",clean_session=True) #create new instance
    client.on_connect = on_connect
    print('Connecting to broker')
    client.connect(broker_address, port=port) #connect to broker

def on_connect(client, userdata, flags, rc):
    global connected
    if rc==0:
        print("connected OK Returned code=",rc)
        connected = True
    else:
        print("Bad connection Returned code=",rc)

Basically, python functions are able to read any variables declared outside the function, but as soon as that function assigns to the variable, a new variable is created in local scope that overrides the one in global scope. The global operation disables this and allows you to assign to the actual global variable rather than create a new one.

Andy
  • 3,132
  • 4
  • 36
  • 68
Rob Streeting
  • 1,675
  • 3
  • 16
  • 27
0

You can do something like this in your case:

x = 1
def foo(y):
  global x
  # Changing x locally will change the global value
  print(x)
ksha
  • 2,007
  • 1
  • 19
  • 22