import paho.mqtt.client as mqtt import requests # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("shellies/freilandsolar/relay/0/power") client.subscribe("shellies/freilandsolar/relay/0/energy") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+ msg.payload.decode("utf-8")) HEADERS = { "Authorization" : "43d3886948451157f1b03bfc7db18c1ed4e4950bc77ffac3e70dff422574b204", "content-type":"application/json" } URL = "" BODY = "" #power if "power" in msg.topic: URL = "https://api.opensensemap.org/boxes/63f26d484fbabe0007d105d2/63f26d484fbabe0007d105d3" BODY = '{"value":' + msg.payload.decode("utf-8")+"}" result = requests.post(url = URL, headers = HEADERS, data = BODY) #energy & savings if "energy" in msg.topic: URL = "https://api.opensensemap.org/boxes/63f26d484fbabe0007d105d2/data" #calculate energy from Watt-minutes energy = float(msg.payload.decode("utf-8"))/60.0/1000.0 BODY = '[' BODY = BODY + '{"sensor":"63f2778a4fbabe0007d68fd9", "value":' + ("{:.1f}".format(energy)) + "}," #calculate savings savings = energy * 0.45 BODY = BODY + '{"sensor":"63f3482c4fbabe000746658e", "value":' + ("{:.2f}".format(savings)) + "}" BODY = BODY + ']' print(BODY) result = requests.post(url = URL, headers = HEADERS, data = BODY) print(result.text) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set("freilandsolar","Js9LLejQA6cBiA==") client.connect("ccc-p.org", 1883, 60) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()