Last active
October 12, 2015 14:58
-
-
Save smulube/4044595 to your computer and use it in GitHub Desktop.
Basic script to read data from a CurrentCost CC128 and post that data to Cosm
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 serial | |
import xml.etree.ElementTree as ET | |
import sys | |
import requests | |
import json | |
import time | |
import syslog | |
FEED_ID = 'FEED_ID' | |
API_KEY = 'API_KEY_WITH_UPDATE_RIGHTS_FOR_YOUR_FEED' | |
URL = 'http://api.cosm.com/v2/feeds/' + FEED_ID + '.json' | |
def read_currentcost(): | |
syslog.syslog("Reading data from currentcost") | |
print "Reading from currentcost" | |
sensor = None | |
watts = None | |
temp = None | |
while watts == None: | |
try: | |
line = ser.readline() | |
tree = ET.XML(line) | |
watts = int(tree.findtext("ch1/watts")) | |
sensor = tree.findtext("sensor") | |
temp = float(tree.findtext("tmpr")) | |
except Exception, inst: | |
sys.stderr.write("XML error: " + str(inst) + "\n") | |
line = None | |
ser.flushInput() | |
return sensor, watts, temp | |
def send_to_cosm(sensor, watts, temp): | |
print "Sending to cosm" | |
headers = { 'X-ApiKey': API_KEY } | |
payload = { 'version': '1.0.0', 'datastreams': [ { 'id': 'temperature', 'current_value': str(temp) }, { 'id' : 'watts', 'current_value': str(watts) }, { 'id' : 'kwh', 'current_value': kwh(watts, 6) } ] } | |
try: | |
r = requests.put(URL, data=json.dumps(payload), headers=headers) | |
except Exception, inst: | |
sys.stderr.write("HTTP error: " + str(inst) + "\n") | |
def kwh(watts, interval): | |
dividerAmount = ((60.0 / interval) * 60) | |
kwh = (watts / dividerAmount) / 1000 | |
return "%.6f" % kwh | |
def run(): | |
print "Starting currentcost.py" | |
while 1: | |
sensor, watts, temp = read_currentcost() | |
send_to_cosm(sensor, watts, temp) | |
ser = serial.Serial('/dev/ttyUSB0', 57600) | |
ser.timeout = 20 | |
ser.flushInput() | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is really great, I was struggling to get the data from my EnvyR to Xively, works a treat thanks.
I don't quite understand the kwh calculation what is that doing?