#!/usr/bin/python

import urllib, urllib2
from time import sleep

#Tom living room
FEEDID = 122399466
#FEEDID = 882725081 
APIKEY = "ULcmy2F4POfiEWoa38OwZFVL6H4FsTr4tPB4rsx7OkTdd1aO"
#APIKEY = "PMZMnfxywZarRTkxVIX7rt13hHWVaBUQABg9djYFVotliKdr"
FILE = "trl_xively_spare_room.csv"
#FILE = "trl_xively_living_room.csv"

#times
ILIM = 6 #xively hours limit if we want all data points
LIM = 1000 #max points in one transaction
START = "2013-08-05T00:00:00Z"
END =  "2013-08-12T00:00:00Z"
WAIT = 60 #number of seconds to wait between queries

#URL data
BASE_URL = "https://api.xively.com"
URL = "/v2/feeds/%d.csv?duration=%dhours&limit=%d&interval=0" % (FEEDID,ILIM,LIM)

f = open(FILE, 'a')

#GET csv
while START < END:
    try:
        print BASE_URL + URL + "&start="+START
        req = urllib2.Request(BASE_URL + URL + "&start="+START)
        req.add_header('X-ApiKey',APIKEY)
        response = urllib2.urlopen(req) 
        csv = response.read()
        START = csv.splitlines()[-1].split(",")[1]
        START = START[:-2] + str(int(START[-2]) + 1) + "Z"
        f.write(csv)
        f.write('\n')
    except urllib2.URLError as e:
        print e
        break

    sleep(WAIT) #wait until the next query

f.close()
