Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This script is based on this tutorial from Adafruite
- # http://learn.adafruit.com/send-raspberry-pi-data-to-cosm/overview
- #
- # Created on Feb 2, 2013 by Steven Smethurst
- # Version: 1.00
- #
- # Directions
- # Install EEML - markup language COSM accepts
- # wget -O geekman-python-eeml.tar.gz https://github.com/geekman/python-eeml/tarball/master
- # Connect a LED between Pin 6 ( Ground) and pin 12 (GPIO18)
- # Connect a swtich between Pin 6 (ground) and pin 11 (GPIO17)
- #
- #!/usr/bin/env python
- import time
- import os
- import glob
- import time
- import eeml
- #set up the Raspberry PI GPIO pins
- import RPi.GPIO as io
- io.setmode(io.BCM)
- # set up the 1Wire sensors
- os.system('modprobe w1-gpio')
- os.system('modprobe w1-therm')
- # CONFIGURATION
- # COSM variables. The API_KEY and FEED are specific to your COSM account and must be changed
- API_KEY = 'XXXXXXXXXXXXXXX'
- FEED = 123456
- API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED)
- SCAN_INTERVAL = 10
- # set constant pins
- pin_LightswitchOne = 27
- pin_LightswitchTwo = 22
- pin_Doorswitch = 17
- pin_PID = 25
- pin_relayOne = 24
- pin_relayTwo = 23
- # Set up pins
- io.setup(pin_LightswitchOne, io.IN)
- io.setup(pin_LightswitchTwo, io.IN)
- io.setup(pin_Doorswitch, io.IN)
- io.setup(pin_PID, io.IN)
- io.setup(pin_relayOne, io.OUT)
- io.setup(pin_relayTwo, io.OUT)
- base_dir = '/sys/bus/w1/devices/'
- device_folders = glob.glob(base_dir + '28*')
- def SendToCosm( values ) :
- # Send the change of state to https://cosm.com
- # open up your cosm feed
- pac = eeml.Pachube(API_URL, API_KEY)
- for point in values:
- pac.update( [eeml.Data(point[0], point[1]) ] )
- # send data to cosm
- print "Sending data to COSM"
- print str( values )
- pac.put()
- # Return CPU temperature as a character string
- def getCPUtemperature():
- res = os.popen('vcgencmd measure_temp').readline()
- return(res.replace("temp=","").replace("'C\n",""))
- # Return RAM information (unit=kb) in a list
- # Index 0: total RAM
- # Index 1: used RAM
- # Index 2: free RAM
- def getRAMinfo():
- p = os.popen('free')
- i = 0
- while 1:
- i = i + 1
- line = p.readline()
- if i==2:
- return(line.split()[1:4])
- # Return % of CPU used by user as a character string
- def getCPUuse():
- return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
- # Return information about disk space as a list (unit included)
- # Index 0: total disk space
- # Index 1: used disk space
- # Index 2: remaining disk space
- # Index 3: percentage of disk used
- def getDiskSpace():
- p = os.popen("df -h /")
- i = 0
- while 1:
- i = i +1
- line = p.readline()
- if i==2:
- return(line.split()[1:5])
- def read_temp_raw( filename ):
- f = open(filename, 'r')
- lines = f.readlines()
- f.close()
- return lines
- def ReadSingleSensor( i, sensor_file ):
- device_name = sensor_file.replace( base_dir, '' ).replace( '/w1_slave', '' )
- lines = read_temp_raw( sensor_file )
- while lines[0].strip()[-3:] != 'YES':
- time.sleep(0.2)
- lines = read_temp_raw( sensor_file )
- equals_pos = lines[1].find('t=')
- if equals_pos != -1:
- temp_string = lines[1][equals_pos+2:]
- temp_c = float(temp_string) / 1000.0
- cosmValues = [[ device_name, temp_c ]]
- return cosmValues
- def ReadSensors():
- results = []
- for (i, item) in enumerate(device_folders):
- sensor_file = item + '/w1_slave'
- results += ReadSingleSensor( i, sensor_file )
- return results
- def main() :
- #temp variables
- LastPoll = 0
- LastState_LightswitchOne = 3 #non state
- LastState_LightswitchTwo = 3 #non state
- LastState_PID = 3 #non state
- CurrentState_LightswitchOne = 3 #non state
- CurrentState_LightswitchTwo = 3 #non state
- CurrentState_Doorswitch = 3 #non state
- CurrentState_RelayOne = False
- Count_PID = 0
- # MAIN LOOP
- while 1:
- #read the current sensors
- CurrentState_LightswitchOne = io.input(pin_LightswitchOne)
- CurrentState_LightswitchTwo = io.input(pin_LightswitchTwo)
- CurrentState_Doorswitch = io.input(pin_Doorswitch)
- #Check to see if the sensors have changed.
- if( CurrentState_LightswitchOne != LastState_LightswitchOne ) :
- LastState_LightswitchOne = CurrentState_LightswitchOne
- # something has changed.
- if CurrentState_LightswitchOne :
- print("Light Switch One: On")
- io.output(pin_relayOne, True)
- else:
- print("Light Switch One: OFF")
- io.output(pin_relayOne, False)
- if( CurrentState_LightswitchTwo != LastState_LightswitchTwo ) :
- LastState_LightswitchTwo = CurrentState_LightswitchTwo
- # something has changed.
- if CurrentState_LightswitchTwo :
- print("Light Switch Two: On")
- io.output(pin_relayTwo, True)
- else:
- print("Light Switch Two: OFF")
- io.output(pin_relayTwo, False)
- if( CurrentState_Doorswitch != CurrentState_Doorswitch ) :
- CurrentState_Doorswitch = CurrentState_Doorswitch
- if( CurrentState_LightswitchOne == True | CurrentState_Doorswitch == True ) :
- io.output(pin_relayOne, True)
- # The PID uses FALSE to detect motion.
- CurrentState_PID = 0 # no motion
- if io.input(pin_PID) == False :
- CurrentState_PID = 1 # motion detected.
- if( CurrentState_PID != LastState_PID ) :
- LastState_PID = CurrentState_PID
- # something has changed.
- if CurrentState_PID :
- print("Motion detected!")
- else:
- print("Motion: Stopped")
- if CurrentState_PID :
- Count_PID += 1 # count how many times this session that motion has been detected.
- # Only send home once every Scan interval.
- CurrentTime = time.time()
- if( CurrentTime > LastPoll):
- LastPoll = CurrentTime + SCAN_INTERVAL
- try:
- # CPU informatiom
- CPU_temp = getCPUtemperature()
- CPU_usage = getCPUuse()
- # RAM information
- # Output is in kb, here I convert it in Mb for readability
- RAM_stats = getRAMinfo()
- RAM_total = round(int(RAM_stats[0]) / 1000,1)
- RAM_used = round(int(RAM_stats[1]) / 1000,1)
- RAM_free = round(int(RAM_stats[2]) / 1000,1)
- # Disk information
- DISK_stats = getDiskSpace()
- DISK_total = DISK_stats[0]
- DISK_free = DISK_stats[1]
- DISK_perc = DISK_stats[3]
- # add the temp sensors
- results = ReadSensors()
- # generate the Cosm Poll
- cosmValues = [[ "CPU_temp", str( CPU_temp ) ] ]
- cosmValues += [[ "CPU_usage", str( CPU_usage ) ] ]
- cosmValues += [[ "RAM_total", str( RAM_total ) ] ]
- cosmValues += [[ "RAM_used", str( RAM_used ) ] ]
- cosmValues += [[ "RAM_free", str( RAM_free ) ] ]
- cosmValues += [[ "DISK_total", str( DISK_total ) ] ]
- cosmValues += [[ "DISK_free", str( DISK_free ) ] ]
- cosmValues += [[ "DISK_perc", str( DISK_perc ) ] ]
- cosmValues += [[ "SWITCH_one", str( CurrentState_LightswitchOne ) ] ]
- cosmValues += [[ "SWITCH_two", str( CurrentState_LightswitchTwo ) ] ]
- # counts how many times motion has been detected between polls.
- cosmValues += [[ "Motion", str( Count_PID ) ] ]
- Count_PID = 0 # reset the count back to zero
- for sensor in results:
- cosmValues += [[ sensor[0], str( sensor[1] ) ] ]
- # send to Cosm
- SendToCosm( cosmValues )
- except Exception as e:
- print('ERROR: Unexpected error')
- print( str(e) )
- # Be nice to the system and sleep between checks
- time.sleep( 0.1 )
- # All done
- board.exit()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement