SHARE
TWEET

Furnace Monitor

alaskanshade Nov 28th, 2013 11 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2. import sys
  3. import RPi.GPIO as GPIO
  4. import time
  5. import MySQLdb
  6. import pickle
  7. from datetime import datetime, date
  8.  
  9. pins = [17,18,22,23]
  10. prev = [0,0,0,0]
  11. on = [0,1,1,0]
  12. try:
  13.     f = open('state', 'r')
  14.     prev = pickle.load(f)
  15. except:
  16.     print('no previous state')
  17. db = MySQLdb.connect('localhost','monitor','***','furnace')
  18.  
  19. def checkInput(pin, prev_value, on_value):
  20.     input = GPIO.input(pin)
  21.     if (prev_value != input):
  22.         print('%s changed: %s' %(pin,input))
  23.         c = db.cursor()
  24.         try:
  25.             if (input == on_value):
  26.                 c.execute("""insert into log_event (pin) values (%d)""" % pin)
  27.             else:
  28.                 c.execute("""update log_event set off_time = CURRENT_TIMESTAMP where pin = %d and off_time is null""" % pin)
  29.             db.commit()
  30.         except MySQLdb.Error, e:
  31.             print "Unexpected error: %s" % e
  32.             db.rollback()
  33.         f = open('state','w')
  34.         pickle.dump(prev, f)
  35.         f.close()
  36.     return input
  37.    
  38. def heartbeat():
  39.     cur_input = [GPIO.input(pins[0]),GPIO.input(pins[1]),GPIO.input(pins[2]),GPIO.input(pins[3])]
  40.     print('heartbeat: %s,%s,%s,%s' % tuple(cur_input))
  41.     c = db.cursor()
  42.     try:
  43.         c.execute("""insert into heartbeat (p17,p18,p22,p23) values (%d,%d,%d,%d)""" % tuple(cur_input))
  44.         db.commit()
  45.     except:
  46.         db.rollback()
  47.     return datetime.now()
  48.  
  49. try:
  50.     GPIO.setmode(GPIO.BCM)
  51.     for i in range(len(pins)):
  52.         GPIO.setup(pins[i],GPIO.IN)
  53.         prev[i] = GPIO.input(pins[i])
  54.     last_beat = heartbeat()
  55.     while True:
  56.         for i in range(len(pins)):
  57.             prev[i] = checkInput(pins[i], prev[i], on[i])
  58.         if ((datetime.now() - last_beat).total_seconds() >= 60):
  59.             last_beat = heartbeat()
  60.             f = open('state','w')
  61.             pickle.dump(prev, f)
  62.             f.close()
  63.         time.sleep(0.5)
  64. except:
  65.     l = open('error.log','w')
  66.     l.write(sys.exc_info()[0])
  67.     l.close()
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top