Friday, March 21, 2014

Connect to thingspeak (Python Code)

import httplib
import urllib
import serial
import time
import math
import urllib2



def dglux(device_ID,device_point,value):
    conn = httplib.HTTPConnection("localhost",8080)
    data="/httpds?__device"+'='+str(device_ID)+'&'+str(device_point)+'='+str(value)
    conn.request("GET", data)

def thing_speak(f1,f2): 
    try:       
        para= urllib.urlencode({'field1':f1,'field2':f2,
                                'key':'xxxxxxxxxxxxxxxxxxxxxxxx'})
        headers={"Content-type":"application/x-www-form-urlencoded","Accept":
                 "text/plain"}
        conn=httplib.HTTPConnection("api.thingspeak.com:80")
        conn.request("POST","/update",para,headers)
        response=conn.getresponse()
        print response.status, response.reason
        data=response.read()
        conn.close()
    except:
        print "Network Connection error"
    
ser = serial.Serial("COM3",9600)
while True:
    f1=ser.readline()   
    if eval(f1)>0:       
        #print type(f1)
        f2=eval(f1)*230*0.8
        print f1,f2
        thing_speak(f1,f2)
        #time.sleep(45   
        #dglux("Home","Current",f1)
ser.close()