Advertisement
Guest User

thingspeak_room_temp_loop.py

a guest
Apr 14th, 2014
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. #!/usr/bin/python  
  2. import httplib, urllib
  3. import os
  4. import glob
  5. import time
  6.  
  7. def doit():
  8.  base_dir = '/sys/bus/w1/devices/'
  9.  device_folder = glob.glob(base_dir + '28*')[0]
  10.  device_file = device_folder + '/w1_slave'
  11.  Params = urllib.urlencode({'field1': temp_c, 'key':'MY KEY'})
  12.  Headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
  13.  conn = httplib.HTTPConnection("api.thingspeak.com:80")
  14.  
  15.  def read_temp_raw():
  16.   f = open(device_file, 'r')
  17.   lines = f.readlines()
  18.   f.close()
  19.   return lines
  20.  
  21.  def read_temp():
  22.     lines = read_temp_raw()
  23.     while lines[0].strip()[-3:] != 'YES':
  24.         time.sleep(0.2)
  25.         lines = read_temp_raw()
  26.     equals_pos = lines[1].find('t=')
  27.     if equals_pos != -1:
  28.         temp_string = lines[1][equals_pos+2:]
  29.         temp_c = float(temp_string) / 1000.0
  30.         temp_f = temp_c * 9.0 / 5.0 + 32.0
  31.         return temp_c, temp_f
  32.  
  33.  try:
  34.     conn.request("POST", "/update", params, headers)
  35.     response = conn.getresponse()
  36.     print temp_c
  37.     data = response.read()
  38.     temp_c = read_temp()
  39.     conn.close()
  40.  except:
  41.     print "connection failed"
  42.  
  43.  
  44. #sleep for 16 seconds (api limit of 15 secs)
  45. if __name__ == "__main__":
  46.     while True:
  47.         doit()
  48.         time.sleep(16)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement