Python/MQTT/thingsboard basic gpio panel mode selection.py

< Python < MQTT
import paho.mqtt.client as mqtt
import json

MQTT_BROKER = "thingsboard.sysats.tech"
TOKEN       = "rg6k7jyrX31SB36fgH9i"

RELAY           = 1
MODE_SELECTION  = 2

MANUAL          = 0
AUTOMATION      = 1

# We assume that all GPIOs are LOW
gpio_state = {RELAY: 0, MODE_SELECTION: MANUAL}

client = mqtt.Client("this is MQTT ID")

def on_connect(client, userdata, flags, rc):
    if rc==0:
        print("connected OK") #print out when connect sucessfully
    else:
        print("bad connection")  
    
    #Must put those 2 functions inside on_connect() callback function
    client.subscribe("v1/devices/me/rpc/request/+")
    client.publish("v1/devices/me/attributes", get_gpio_status())

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print("Received message") 
    print(msg.topic+" "+str(msg.payload.decode()))
    data = json.loads(msg.payload)

    print("debug: " + str(data))

    #Allow user to control GPIO when in MANUAL mode
    if (gpio_state[MODE_SELECTION] == MANUAL):
        set_gpio_status(data['params']['pin'], data['params']['enabled'])
    #Allow user to switch back from automation to manual mode
    elif gpio_state[MODE_SELECTION] == AUTOMATION:
        if (data['params']['pin'] == MODE_SELECTION) and (data['params']['enabled'] == MANUAL):
           set_gpio_status(data['params']['pin'], data['params']['enabled'])

    client.publish(msg.topic.replace('request', 'response'), get_gpio_status())
    client.publish("v1/devices/me/attributes", get_gpio_status())

def set_gpio_status(pin, status):
    gpio_state[pin] = status

def get_gpio_status():
    return json.dumps(gpio_state)

client.username_pw_set(TOKEN)
client.on_connect = on_connect
client.on_message = on_message

client.connect(MQTT_BROKER, 1883)
client.loop_forever()