#!/usr/bin/env python
import rospy
import paho_mqtt.client as mqtt
from std_msgs.msg import Int16

#Replace these parameters with your MQTT parameters
mqtt_user="qfamebbw"
mqtt_password="MVT3d1Fwf_48"
mqtt_server="m10.cloudmqtt.com"
mqtt_port=15809

mode = 1
toggle = True;

#Callback functions for MQTT with paho
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("FromUnity")

def on_message(client, userdata, msg):
	global toggle, mode
	print(msg.topic+" "+str(msg.payload))
	if msg.topic == "FromUnity":
		mode = int(msg.payload)
		toggle = True

def talker():
	global toggle, mode
	pub = rospy.Publisher('tartMode', Int16, queue_size=10)
	rospy.init_node('unityTalker', anonymous=True)
	rate = rospy.Rate(10) # 10hz
	while not rospy.is_shutdown():
		if toggle:
			rospy.loginfo(mode)
			pub.publish(mode)
			toggle = False
		rate.sleep()

#MQTT-related declarations
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(mqtt_user, password=mqtt_password)
client.connect_async(mqtt_server, mqtt_port, 60)
client.loop_start()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass
