Skip to content

Instantly share code, notes, and snippets.

@fredrike
Last active August 29, 2015 14:21
Show Gist options
  • Save fredrike/6f672bca8ab4f22e60f9 to your computer and use it in GitHub Desktop.
Save fredrike/6f672bca8ab4f22e60f9 to your computer and use it in GitHub Desktop.
telldus.py
import oauth2 as oauth
import json, time, requests, datetime
import re, string
XIVELY_API_KEY = ""
XIVELY_FEED_ID = ""
TELLDUS_PUB_KEY = ""
TELLDUS_PRIV_KEY = ""
TELLDUS_TOKEN = ""
TELLDUS_SECRET = ""
XIVELY_URL = "https://api.xively.com/v2/feeds/" + XIVELY_FEED_ID + ".json"
XIVELY_HEADERS = {'content-type': 'application/json', 'X-ApiKey': XIVELY_API_KEY}
EMONCMS_KEY = ""
consumer = oauth.Consumer(TELLDUS_PUB_KEY, TELLDUS_PRIV_KEY)
token = oauth.Token(TELLDUS_TOKEN, TELLDUS_SECRET)
client = oauth.Client(consumer,token)
resp, content = client.request('https://api.telldus.com/json/sensors/list?includeValues=1', "GET")
sensor = json.loads(content)
pattern = re.compile('[^A-Za-z0-9-]+')
data = { "version": "1.0.0", "datastreams": [] }
for s in sensor['sensor']:
atTime = time.strftime("%Y-%m-%dT%XZ",time.gmtime(s["lastUpdated"]))
if not s.has_key('humidity'):
s["humidity"] = ""
if not s["name"]:
s["name"] = s["id"]
s["name"] = pattern.sub('', s["name"])
#print s["clientName"]+ "_" + s["name"] + ": " + s["temp"] + " " + s["humidity"] + "% t: " + str(s["lastUpdated"])
data["datastreams"].append({ "id": s["clientName"]+ "_" + s["name"] + "_temp",
"datapoints": [{ "at": atTime, "value": s["temp"] }]})
if s["humidity"] and s["humidity"] != u'127' and s["humidity"] != u'0':
data["datastreams"].append({ "id": s["clientName"]+ "_" + s["name"] + "_hum",
"datapoints": [{ "at": atTime, "value": s["humidity"] }]})
string = ""
print data
for d in data["datastreams"]:
if datetime.datetime.strptime(d["datapoints"][0]["at"], "%Y-%m-%dT%XZ") > datetime.datetime.utcnow()-datetime.timedelta(minutes=3):
string += d["id"] + ":" + d["datapoints"][0]["value"]+","
#print string
if string:
string = string[:-1]
url= u"""http://emoncms.org/input/post.json?node=30&json={%s}&apikey=%s""" % (string, EMONCMS_KEY)
print url
try:
r = requests.get(url)
except:
pass
try:
r = requests.put(XIVELY_URL, data=json.dumps(data), headers=XIVELY_HEADERS)
print r.text
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment