import json
import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, reason_code, properties):
    print(f"Connected with result code {reason_code}")
    #client.subscribe("info/device")
    client.subscribe("#")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    try:
        hardware_definitions_dictionary = json.loads(msg.payload)
        print(msg.topic + "\n" + str(hardware_definitions_dictionary))
    except json.decoder.JSONDecodeError:
        print("Invalid payload")

def main():
    mytransport = 'tcp'
    mqttc = mqtt.Client(client_id="test-mqtt-hardware-definition-service",
                        transport=mytransport,
                        protocol=mqtt.MQTTv5)

    mqttc.on_connect = on_connect
    mqttc.on_message = on_message
    broker = "127.0.0.1"
    mqttc.connect(broker, port=1883)

    # Blocking call that processes network traffic, dispatches callbacks and handles reconnecting.
    mqttc.loop_forever()

if __name__ == "__main__":
    main()
