Pi Python:
# Import required libraries
import ftplib,os,sys,time,socket
from subprocess import call
import RPi.GPIO as GPIO
class netCam():
def __init__(self):
self.file='test2.jpg'
# Initialize LEDs
try:
self.initGPIO()
except:
raise
sys.exit("ERROR: Could not initiate GPIO!")
# This LED is ON
for LED in self.LedSeq:
GPIO.output(LED, True)
time.sleep(0.2)
GPIO.output(11, True)
GPIO.output(9, True)
# Create a TCP/IP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('', 10002)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
# --------------------------------------------------------------------------------
def initGPIO(self):
try:
# Tell GPIO library to use GPIO references
GPIO.setmode(GPIO.BCM)
# Set Switch GPIO as input
GPIO.setup(7 , GPIO.IN)
# List of LED GPIO numbers
self.LedSeq = [4,17,22,10,9,11]
# Set up the GPIO pins as outputs and set False
print "Setup Outputs"
for x in range(6):
GPIO.setup(self.LedSeq[x], GPIO.OUT)
GPIO.output(self.LedSeq[x], False)
except:
print " ERROR: There was a problem with initaion of the GPIOs"
raise
# --------------------------------------------------------------------------------
def takeImage(self):
try:
GPIO.output(22, True)
GPIO.output(4, False)
# Remove the old file if present
if os.path.isfile(self.file):
os.remove(self.file)
# Take the photo
call(['/usr/bin/raspistill','-o',self.file,'-t','10','-f','-q','10'])
except:
print " ERROR: There was a problem with taking the image"
GPIO.output(22, False)
GPIO.output(4, True)
#raise
# --------------------------------------------------------------------------------
def sendFile(self):
try:
GPIO.output(10, True)
GPIO.output(17, False)
sftp=ftplib.FTP_TLS()
print " Connecting,",
sftp.connect('192.168.10.5',21,10)
print "-Done \n Setup secure control connection,",
sftp.auth()
print "-Done \n Setup secure data connection,",
sftp.prot_p()
print "-Done \n Login,",
sftp.login('x','x')
print "-Done"
#sftp.retrlines('LIST')
sftp.cwd('www')
#sftp.retrlines('LIST')
sftp.sendcmd("TYPE I")
fileHandle=open(self.file)
sftp.storbinary('STOR %s' %self.file,fileHandle)
sftp.close()
except:
print " ERROR: There was a problem with uploading the image"
GPIO.output(10, False)
GPIO.output(17, True)
#raise
# --------------------------------------------------------------------------------
def waitForConnection(self):
def connection():
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the command, only accept ONE message of 1024 bytes
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data=='photo':
connection.sendall('Pi is taking a photo')
takePhoto=True
elif data:
print >>sys.stderr, 'sending data back to the client'
data='Greeings from PI, You sent: %s' %data
connection.sendall(data)
takePhoto=False
except:
takePhoto=False
finally:
# Clean up the connection
connection.close()
return takePhoto
while True:
if connection():
break
else:
pass
# --------------------------------------------------------------------------------
# M A I N
# --------------------------------------------------------------------------------
try:
cB=netCam()
# Initialize LEDs
print "Initialize LEDs"
try:
cB.initGPIO()
except:
sys.exit("ERROR: Could not initiate!")
time.sleep(0.5)
GPIO.output(11, True)
GPIO.output(9, True)
# Loop until users quits with CTRL-C
print "Ready to take image"
while True:
# if GPIO.input(7):
cB.waitForConnection()
cB.takeImage()
cB.sendFile()
print " -Done"
GPIO.output(22, False)
GPIO.output(10, False)
except KeyboardInterrupt:
print " You pressed Ctrl-C"
except:
print "ERROR: An error occured"
raise
finally:
# Reset GPIO settings
GPIO.cleanup()
På webservern kör jag med php som sagt, i conf.php måste du aktivera sockets, annars kan du inte använda dig av det i koden.
Web-server php:
<html>
<head>
</head>
<body>
<?php
$message=$_POST['message'];
echo "<html>";
print("<br>Start php-script <br>");
echo "</html>";
// The recieved message
echo "Typed message: $message";
// Socket error handeling
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "<html>";
print("<br>Socket created <br>");
echo "</html>";
// Establish a connection
if(!socket_connect($sock , '192.168.10.11' , 10002))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
echo "<html>";
print("Connection to Pi could not be established <br>");
echo "</html>";
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "<html>";
print("Connection established <br>");
echo "</html>";
//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
echo "<html>";
print("Message send successfully <br> Waiting for response <br>");
echo "</html>";
//Now receive reply from server
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
echo "Recieved message: $buf <br>";
echo "<html>";
print("End php-script <br>");
echo "</html>";
?>
</body>
</html>
Denna koden anropas av en html-sida:
<html>
<head>
<title>Take a bite of Pi</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<p> </p>
<p><font face="Verdana, Arial, Helvetica, sans-serif"><strong>Send a message to my Pi:</strong></font></p>
<form name ="resultat" method="POST" action="index.php">
<div align="left">
<p><font face="Verdana, Arial, Helvetica, sans-serif">Enter message:</font>
<input type="text" name="message" size="14">
<input type="submit" value="Send msg">
</p>
<br>
<font face="Verdana, Arial, Helvetica, sans-serif"><p align=left><img src="test2.jpg" width="400" height="300"></font>
</div>
</form>
</body>
</html>