Advertisement
Guest User

thingspeak_room_temp_loop.py

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