import paho.mqtt.client as mqtt
from time import sleep, time
import csv
studentGroup_name = 'StudentGroup_X'
# Assign client ID
mqtt_client_id = studentGroup_name
mqtt_base_topic = 'testtopic/7ZW5M0/' + mqtt_client_id
# MQTT broker/server parameters
mqtt_host_address_1 = 'broker.hivemq.com'
mqtt_host_port_1 = 1883
#defines name of the .csv file of the data output
output_filename = studentGroup_name + str(time()) +  '_output.txt'
#open file for appending (read&write)
csv_file_1 = open(output_filename, 'a+')
header = ("Timestamp","Topic","Message")
csv_file_1.write(';'.join(header) + '\n') # Join all data into one string separated by ; (as required for CSV) and finish the line using '\n'
csv_file_1.close()
# data to be written to csv
mqtt_host_address_2 = 'test.mosquitto.org'
mqtt_host_port_2 = 1883
# Global variable to save latest received message
latest_mesage_payload = ''
latest_mesage_topic = ''
def on_connect():
    print("MQTT successfully connected!")
def on_dissconnect():
    print("Client disconnected form the MQTT broker!")
def on_message(client, userdata, message):
    print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos))
    # Save message content in a global variable
    global latest_mesage_payload, latest_mesage_topic
    latest_mesage_payload = message.payload
    latest_mesage_topic = message.topic
    #write message toppica and payload into CSV file
    global csv_file_1
    data = [str(time()), str(message.topic), str(message.payload)] #add all data into array of strings
    # open file for appending (read&write)
    csv_file_1 = open(output_filename, 'a+')
    csv_file_1.write(';'.join(data) + '\n')
    csv_file_1.close()
# Create Client
client = mqtt.Client(client_id = mqtt_client_id)
# Start runnig the network loop in a paralel thread in regular intervals 
mqtt.loop_start() 
while True:
    # Try to connect to a broker and subscribe to the topic(s)
    try:
        # Assign on_connect/on_disconnect function to a Client
        client.on_connect = on_connect
        client.on_disconnect = on_dissconnect
        # Connect Client
        client.connect(host = mqtt_host_address_1, port = mqtt_host_port_1)
        break #exit the loop if no error in connection
    except:
        # In case error occured in connecting
        print("An error occurred in connection")
        sleep(2) # wait 2 seconds
    # print ("Trying again!")
try:
    # Subscribe Client to a topic
    client.subscribe(mqtt_base_topic + '/#')
    # Assign on_message function to a Client
    client.on_message = on_message
except:
    print("An error occurred while trying to subscribe to a topic")
# Main part of the script for publishing
while True:
    try:
        msg = time()
        client.publish(topic = mqtt_base_topic+'/time', payload = msg)
        # Run mqtt network loop - this will try to send/receive all
        client.loop()
    except:
        print("An error occurred while trying to publish to a topic!")
        # print("Trying again!")
    sleep(2)
# Stop runnig the network loop in a paralel thread in regular intervals 
mqtt.loop_stop() # This part of code is in regular circumstances unreachable!