import time
from paho.mqtt import client as mqtt_client

### MQTT ###
broker = '127.0.0.1'
port = 1883
topic = "zigbee2mqtt/ComfortMonitor_1/10/set"
client_id = f'python-mqtt-310-pub'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

### VARIABLES ###

packets = 1000
wait_time = 1     # seconds


### FUNCTIONS ###
def publish(client):
    msg_count = 0
    start = time.time()
    while msg_count < packets:

        msg = '{"read":{"attributes":["zclVersion"],"cluster":"genBasic","options":{}}}'
        result = client.publish(topic, msg)
        msg_count += 1
        status = result[0]
        if ((msg_count/packets)*100)%10 == 0:
            print(f"{(msg_count/packets)*100} %")

        time.sleep(wait_time)

    stop = time.time()
    duration = stop - start
    s=time.gmtime(start)
    st=time.gmtime(stop)
    print(f"Measurement DONE!\nstart: {time.strftime('%Y-%m-%d %H:%M:%S', s)}\nstop: {time.strftime('%Y-%m-%d %H:%M:%S', st)}\ncalculated duration: {packets*wait_time} ... duration: {duration} s")
    client.disconnect()


def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()
