import paho.mqtt.client as mqtt
import time
import sys
import subprocess
import json

temp = None
humidity = None
airpress = None

def on_message_temp(mosq, obj, msg):
    global temp
    temp = json.loads(msg.payload)

def on_message_humidity(mosq, obj, msg):
    global humidity
    humidity = json.loads(msg.payload)

def on_message_airpress(mosq, obj, msg):
    global airpress
    airpress = json.loads(msg.payload)

Cayenne = mqtt.Client(client_id="ZZZ")    #replace your clientid value within the double quotes
Cayenne.username_pw_set("XXX", password="YYY")  #replace your username and password values within the double quotes

Cayenne.connect("mqtt.mydevices.com", port=1883, keepalive=60)

localmqtt = mqtt.Client()
localmqtt.message_callback_add("tinkerforge/bricklet/temperature/t6Q/temperature", on_message_temp) #do not include leading slash on topic
localmqtt.message_callback_add("tinkerforge/bricklet/humidity/uk9/humidity", on_message_humidity) #do not include leading slash on topic
localmqtt.message_callback_add("tinkerforge/bricklet/barometer/vGZ/air_pressure", on_message_airpress) #do not include leading slash on topic
localmqtt.connect("localhost", port=1883, keepalive=60)
localmqtt.subscribe([("/tinkerforge/bricklet/temperature/t6Q/temperature",0),("/tinkerforge/bricklet/humidity/uk9/humidity",0),("/tinkerforge/bricklet/barometer/vGZ/air_pressure",0)])
localmqtt.loop_start()

# for for topic is "v1/username/things/clientid/data/1" #replace username and clientid here and increment last digit for every sensor
topic_temp = "v1/XXX/things/ZZZ/data/1"  #replace username and clientid with your values here
topic_humidity = "v1/XXX/things/ZZZ/data/2" #replace username and clientid with your values here 
topic_airpress = "v1/XXX/things/ZZZ/data/3" #replace username and clientid with your values here

while True:
    try: 
        if temp is not None:
            cayennetemp = "temp,c=" + str(temp['temperature']/100)
            Cayenne.publish(topic_temp, payload=cayennetemp , retain=True)	

        if humidity is not None:
            cayennehumidity = "rel_hum,p=" + str(humidity['humidity']/10)
            Cayenne.publish(topic_humidity, payload=cayennehumidity , retain=True)

        if airpress is not None:
            cayenneairpress = "press,bar=" + str(airpress['air_pressure']/1000)
            Cayenne.publish(topic_airpress, payload=cayenneairpress , retain=True)

        time.sleep(5)
    except (EOFError, SystemExit, KeyboardInterrupt):
        localmqtt.loop_stop()
        Cayenne.disconnect()
        localmqtt.disconnect()
        sys.exit()
