Last active
December 2, 2018 11:31
-
-
Save bjoern-r/001916c57617e1a2e31aaa4887970b44 to your computer and use it in GitHub Desktop.
sonoff POW MQTT to emoncms publisher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import paho.mqtt.client as mqtt | |
import json | |
import time | |
import requests | |
nodename="sonoff" | |
apikey="--xx--" | |
url="https://emoncms.org/input/post" | |
def on_connect(client, userdata, flags, rc): | |
global nodename | |
print("Connected with result code " + str(rc)) | |
client.subscribe("tele/%s/#"%nodename) | |
client.publish("cmnd/%s/TelePeriod"%nodename, 60) | |
def on_message(client, userdata, msg): | |
print(msg.topic + " " + str(msg.payload)) | |
if msg.topic.endswith("SENSOR"): | |
# {"Time":"2018-05-19T12:05:02","ENERGY":{"Total":0.264,"Yesterday":0.046,"Today":0.045,"Power":2,"Factor":0.12,"Voltage":221,"Current":0.080}} | |
try: | |
dat = json.loads(msg.payload.decode()) | |
ts = time.strptime(dat["Time"],"%Y-%m-%dT%H:%M:%S") | |
uts= time.mktime(ts)+3600.0 | |
postdata="time=%d&node=%s&apikey=%s&fulljson=%s"%(int(uts),nodename,apikey,json.dumps(dat["ENERGY"],separators=(',', ':'))) | |
#geturl='https://emoncms.org/input/post/%s?time=%d&fulljson=%s&apikey=%s'%(nodename,int(uts),json.dumps(dat["ENERGY"],separators=(',', ':')),apikey ) | |
print("POST data:", postdata) | |
#print("curl --data '%s' '%s'"%(postdata,"https://emoncms.org/input/post")) | |
r = requests.post(url, data=dict(node=nodename,apikey=apikey,time=int(uts),data=json.dumps(dat["ENERGY"],separators=(',', ':')))) | |
print("POST->",r.text) | |
except Exceltion as e: | |
print("Error:",e) | |
client = mqtt.Client() | |
client.on_connect = on_connect | |
client.on_message = on_message | |
client.connect("localhost", 1883, 60) | |
client.loop_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Small typing error on line 31, should be Exception and not Exceltion