Advertisement
Guest User

Raspberry PI homeatuoation

a guest
Nov 24th, 2013
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.42 KB | None | 0 0
  1. # This script is based on this tutorial from Adafruite
  2. # http://learn.adafruit.com/send-raspberry-pi-data-to-cosm/overview
  3. #
  4. # Created on Feb 2, 2013 by Steven Smethurst
  5. # Version: 1.00
  6. #
  7. # Directions
  8. # Install EEML - markup language COSM accepts
  9. #    wget -O geekman-python-eeml.tar.gz https://github.com/geekman/python-eeml/tarball/master
  10. # Connect a LED between Pin 6 ( Ground) and pin 12 (GPIO18)
  11. # Connect a swtich between Pin 6 (ground) and pin 11 (GPIO17)
  12. #  
  13.  
  14. #!/usr/bin/env python
  15. import time
  16.  
  17. import os
  18. import glob
  19. import time
  20. import eeml
  21.  
  22. #set up the Raspberry PI GPIO pins
  23. import RPi.GPIO as io
  24. io.setmode(io.BCM)
  25.  
  26. # set up the 1Wire sensors
  27. os.system('modprobe w1-gpio')
  28. os.system('modprobe w1-therm')
  29.  
  30. # CONFIGURATION
  31. # COSM variables. The API_KEY and FEED are specific to your COSM account and must be changed
  32. API_KEY         = 'XXXXXXXXXXXXXXX'
  33. FEED            = 123456
  34. API_URL         = '/v2/feeds/{feednum}.xml' .format(feednum = FEED)
  35. SCAN_INTERVAL   = 10
  36.  
  37. # set constant pins
  38. pin_LightswitchOne  = 27
  39. pin_LightswitchTwo  = 22
  40. pin_Doorswitch      = 17
  41. pin_PID             = 25
  42. pin_relayOne        = 24
  43. pin_relayTwo        = 23
  44.  
  45.  
  46. # Set up pins
  47. io.setup(pin_LightswitchOne, io.IN)
  48. io.setup(pin_LightswitchTwo, io.IN)
  49. io.setup(pin_Doorswitch,     io.IN)
  50. io.setup(pin_PID, io.IN)
  51. io.setup(pin_relayOne, io.OUT)
  52. io.setup(pin_relayTwo, io.OUT)
  53.  
  54.  
  55. base_dir        = '/sys/bus/w1/devices/'
  56. device_folders  = glob.glob(base_dir + '28*')
  57.  
  58. def SendToCosm( values ) :
  59.     # Send the change of state to https://cosm.com
  60.     # open up your cosm feed
  61.     pac = eeml.Pachube(API_URL, API_KEY)
  62.    
  63.     for point in values:
  64.         pac.update( [eeml.Data(point[0], point[1]) ] )
  65.        
  66.     # send data to cosm
  67.     print "Sending data to COSM"
  68.     print str( values )
  69.     pac.put()    
  70.  
  71. # Return CPU temperature as a character string                                      
  72. def getCPUtemperature():
  73.     res = os.popen('vcgencmd measure_temp').readline()
  74.     return(res.replace("temp=","").replace("'C\n",""))
  75.  
  76. # Return RAM information (unit=kb) in a list                                        
  77. # Index 0: total RAM                                                                
  78. # Index 1: used RAM                                                                
  79. # Index 2: free RAM                                                                
  80. def getRAMinfo():
  81.     p = os.popen('free')
  82.     i = 0
  83.     while 1:
  84.         i = i + 1
  85.         line = p.readline()
  86.         if i==2:
  87.             return(line.split()[1:4])
  88.  
  89. # Return % of CPU used by user as a character string                                
  90. def getCPUuse():
  91.     return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
  92.  
  93. # Return information about disk space as a list (unit included)                    
  94. # Index 0: total disk space                                                        
  95. # Index 1: used disk space                                                          
  96. # Index 2: remaining disk space                                                    
  97. # Index 3: percentage of disk used                                                  
  98. def getDiskSpace():
  99.     p = os.popen("df -h /")
  100.     i = 0
  101.     while 1:
  102.         i = i +1
  103.         line = p.readline()
  104.         if i==2:
  105.             return(line.split()[1:5])
  106.  
  107.  
  108.  
  109.  
  110.  
  111. def read_temp_raw( filename ):
  112.     f = open(filename, 'r')
  113.     lines = f.readlines()
  114.     f.close()
  115.     return lines
  116.  
  117. def ReadSingleSensor( i, sensor_file ):
  118.     device_name = sensor_file.replace( base_dir, '' ).replace( '/w1_slave', '' )
  119.  
  120.     lines = read_temp_raw( sensor_file )
  121.     while lines[0].strip()[-3:] != 'YES':
  122.         time.sleep(0.2)
  123.         lines = read_temp_raw( sensor_file )
  124.        
  125.     equals_pos = lines[1].find('t=')
  126.     if equals_pos != -1:
  127.         temp_string = lines[1][equals_pos+2:]
  128.         temp_c = float(temp_string) / 1000.0
  129.  
  130.  
  131.     cosmValues = [[ device_name, temp_c ]]
  132.     return cosmValues
  133.  
  134. def ReadSensors():    
  135.     results = []    
  136.     for (i, item) in enumerate(device_folders):
  137.         sensor_file = item + '/w1_slave'
  138.         results += ReadSingleSensor( i, sensor_file )
  139.     return results
  140.  
  141.  
  142. def main() :
  143.    
  144.    
  145.     #temp variables
  146.     LastPoll                    = 0
  147.     LastState_LightswitchOne    = 3 #non state
  148.     LastState_LightswitchTwo    = 3 #non state
  149.     LastState_PID               = 3 #non state
  150.     CurrentState_LightswitchOne = 3 #non state
  151.     CurrentState_LightswitchTwo = 3 #non state
  152.     CurrentState_Doorswitch     = 3 #non state
  153.    
  154.     CurrentState_RelayOne       = False  
  155.    
  156.     Count_PID                   = 0
  157.    
  158.    
  159.    
  160.     # MAIN LOOP
  161.     while 1:
  162.        
  163.         #read the current sensors
  164.         CurrentState_LightswitchOne = io.input(pin_LightswitchOne)  
  165.         CurrentState_LightswitchTwo = io.input(pin_LightswitchTwo)
  166.         CurrentState_Doorswitch     = io.input(pin_Doorswitch)
  167.        
  168.        
  169.         #Check to see if the sensors have changed.
  170.         if( CurrentState_LightswitchOne != LastState_LightswitchOne ) :
  171.             LastState_LightswitchOne = CurrentState_LightswitchOne
  172.             # something has changed.
  173.             if CurrentState_LightswitchOne :
  174.                 print("Light Switch One: On")
  175.                 io.output(pin_relayOne, True)
  176.             else:
  177.                 print("Light Switch One: OFF")
  178.                 io.output(pin_relayOne, False)
  179.            
  180.         if( CurrentState_LightswitchTwo != LastState_LightswitchTwo ) :
  181.             LastState_LightswitchTwo = CurrentState_LightswitchTwo
  182.             # something has changed.
  183.             if CurrentState_LightswitchTwo :
  184.                 print("Light Switch Two: On")
  185.                 io.output(pin_relayTwo, True)
  186.             else:
  187.                 print("Light Switch Two: OFF")
  188.                 io.output(pin_relayTwo, False)
  189.                
  190.         if( CurrentState_Doorswitch != CurrentState_Doorswitch ) :
  191.             CurrentState_Doorswitch = CurrentState_Doorswitch
  192.    
  193.                
  194.         if( CurrentState_LightswitchOne == True | CurrentState_Doorswitch == True ) :
  195.             io.output(pin_relayOne, True)
  196.                
  197.         # The PID uses FALSE to detect motion.
  198.         CurrentState_PID = 0 # no motion
  199.         if io.input(pin_PID) == False :
  200.             CurrentState_PID = 1 # motion detected.
  201.  
  202.         if( CurrentState_PID != LastState_PID ) :
  203.             LastState_PID = CurrentState_PID            
  204.             # something has changed.
  205.             if CurrentState_PID :
  206.                 print("Motion detected!")
  207.             else:
  208.                 print("Motion: Stopped")        
  209.  
  210.         if CurrentState_PID :
  211.             Count_PID += 1 # count how many times this session that motion has been detected.
  212.  
  213.        
  214.         # Only send home once every Scan interval.
  215.         CurrentTime = time.time()
  216.         if( CurrentTime > LastPoll):
  217.             LastPoll = CurrentTime + SCAN_INTERVAL          
  218.            
  219.             try:
  220.                
  221.                 # CPU informatiom
  222.                 CPU_temp  = getCPUtemperature()
  223.                 CPU_usage = getCPUuse()
  224.                
  225.                 # RAM information
  226.                 # Output is in kb, here I convert it in Mb for readability
  227.                 RAM_stats = getRAMinfo()
  228.                 RAM_total = round(int(RAM_stats[0]) / 1000,1)
  229.                 RAM_used  = round(int(RAM_stats[1]) / 1000,1)
  230.                 RAM_free  = round(int(RAM_stats[2]) / 1000,1)
  231.                
  232.                 # Disk information
  233.                 DISK_stats = getDiskSpace()
  234.                 DISK_total = DISK_stats[0]
  235.                 DISK_free  = DISK_stats[1]
  236.                 DISK_perc  = DISK_stats[3]
  237.                
  238.                 # add the temp sensors
  239.                 results = ReadSensors()
  240.        
  241.                 # generate the Cosm Poll
  242.                 cosmValues  = [[ "CPU_temp", str( CPU_temp ) ] ]
  243.                 cosmValues += [[ "CPU_usage", str( CPU_usage ) ] ]
  244.                 cosmValues += [[ "RAM_total", str( RAM_total ) ] ]
  245.                 cosmValues += [[ "RAM_used", str( RAM_used ) ] ]
  246.                 cosmValues += [[ "RAM_free", str( RAM_free ) ] ]
  247.                 cosmValues += [[ "DISK_total", str( DISK_total ) ] ]
  248.                 cosmValues += [[ "DISK_free", str( DISK_free ) ] ]
  249.                 cosmValues += [[ "DISK_perc", str( DISK_perc ) ] ]    
  250.                 cosmValues += [[ "SWITCH_one", str( CurrentState_LightswitchOne ) ] ]  
  251.                 cosmValues += [[ "SWITCH_two", str( CurrentState_LightswitchTwo ) ] ]  
  252.  
  253.                 # counts how many times motion has been detected between polls.
  254.                 cosmValues += [[ "Motion", str( Count_PID ) ] ]  
  255.                 Count_PID = 0 # reset the count back to zero
  256.                
  257.                
  258.                
  259.                 for sensor in results:
  260.                     cosmValues += [[ sensor[0], str( sensor[1] ) ] ]                
  261.                
  262.                 # send to Cosm
  263.                 SendToCosm( cosmValues )
  264.                
  265.             except Exception as e:
  266.                 print('ERROR: Unexpected error')  
  267.                 print( str(e) )  
  268.        
  269.         # Be nice to the system and sleep between checks
  270.         time.sleep( 0.1 )
  271.        
  272.     # All done    
  273.     board.exit()    
  274.    
  275.    
  276. if __name__ == '__main__':
  277.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement