User:Yoana Buzova/ pr5.2

From XPUB & Lens-Based wiki
# -*- coding: utf-8 -*- 
#!/usr/bin/env python

import os, subprocess, signal, time
import RPi.GPIO as GPIO
import datetime

PIR = 23
LED = 24
BUTTON = 25

pirState = False
pirVal = False
#pirValButton = False

initialRecTime = 0.0
recordvalue = False

#maximum duration of the sound file
maxRecordingTime = 60.0

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR,GPIO.IN)
GPIO.setup(LED,GPIO.OUT)
GPIO.setup(BUTTON,GPIO.IN)

#static starts and ends of the commands, the counter variable goes in between them 
myname = 'PINK-'
commandRecordBegin='arecord -q -f cd -t wav > file sounds/'
commandRecordEnd='.wav'
commandPlayBegin='aplay '
lastSoundName = ' ' 

from subprocess import check_output, CalledProcessError


FOLDER = "/home/pi"


def get_free():
	i = os.statvfs(FOLDER)
	free_mb = (i.f_bavail * i.f_frsize) / 1000.0 / 1000.0
	return free_mb

def delete_if_full():
	print "delete_if_full"
	free = get_free()
	minfree = 275.0
	while (free < minfree):
		print free
		sfiles = check_output(["/bin/sh", "-c", "ls -t /home/pi/sounds/*wav"]).strip().split("\n")
		oldest = sfiles[-1]
		oldest = os.path.join ("/home/pi/sounds/", oldest)
		print oldest
		print 'I am in the loop'
		os.remove (oldest)  #deleted oldest file
		print "deleted oldest"
		free = get_free()
		print free
	 
	

def play():
	print "PLAY"
	try:
		
		#it changes the permissions of the folder of the sever so it can played from the website
		check_output(["ssh", "oyo@91.250.112.182", "chmod o+x leaveamessage/test/"])
		#play the last sound file in the server
		ls = check_output(["ssh", "oyo@91.250.112.182", "ls -t leaveamessage/test/sounds/*.wav"])
		mostrecent = ls.split("\n")[0]
		print "mostrecent", mostrecent
		cmd = "ssh oyo@91.250.112.182 'cat "+mostrecent+"' | aplay"
		print cmd
		os.system(cmd)

	except CalledProcessError:
		print "oops, error ls ing server. Playing local files."
		playLocal()
	except IndexError:
		print "oops, error ls ing server. Playing local files."
		playLocal()

def playLocal():
	print "PLAY LOCAL"
	lsLocalSounds = check_output(["ls -t sounds/*.wav"], shell=True)
	mostRecentSound = lsLocalSounds.split("\n")[0]
	print mostRecentSound
	commandPlay=commandPlayBegin+mostRecentSound
	os.system(commandPlay)	

def stopRecording():
	global recordvalue
	global initialRecTime
	recordvalue = False 		
	initialRecTime = 0.0	
	print "stop recording called"
	GPIO.output(LED, False)
	os.kill(proc1.pid, signal.SIGKILL)
	os.kill(proc1.pid+1, signal.SIGKILL)
	print "finished recording and killed process"
	#os.system("rsync -avz /home/pi/sounds/*.wav oyo@91.250.112.182:leaveamessage/test/sounds/")
	scpCommandStr = "scp sounds/"+lastSoundName+" oyo@91.250.112.182:leaveamessage/test/sounds/"
	os.system(scpCommandStr)

	delete_if_full()	

#We use this variable for forcing the user to release the buttons to start recording or playing again
needToReleaseRec = False
needToReleasePlay = False
while True:
	pirValButton = GPIO.input(BUTTON)
	if(pirValButton == True):
		if(recordvalue == False and needToReleaseRec == False):
			recordvalue = True
			needToReleaseRec = True
			initialRecTime = time.time()
			print "initialTime",initialRecTime
			GPIO.output(LED, True)
			print "REC"
			timestampNow = datetime.datetime.now().strftime("%Y_%m_%d-%H_%M_%S")
			lastSoundName = myname+timestampNow+commandRecordEnd
			commandRecord=commandRecordBegin+lastSoundName
			proc1 = subprocess.Popen(commandRecord, shell = True)
			print "hello stranger"
	
	
	else:
		needToReleaseRec = False
	if(recordvalue == True):
		if(pirValButton == False):
			stopRecording()
		else:
			currentRecTime = time.time() 
			diffRecTime = currentRecTime - initialRecTime
			if(diffRecTime > maxRecordingTime):
				print "You pressed the REC button for too long! ",diffRecTime
				stopRecording()
	
		
	if(pirValButton == False): #in case the REC button is no pressed we check the PLAY one
		pirVal = GPIO.input(PIR)		
		if(pirVal == True):
			if(needToReleasePlay == False):
				needToReleasePlay = True
				print 'PLAY button pressed'
				play()
				print 'back from playing'
		else:
			needToReleasePlay = False