import socket
import sys
import RPi.GPIO as GPIO
from subprocess import call

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('192.168.3.77', 6000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()

    try:
        print >>sys.stderr, 'connection from', client_address

        # Receive the data in small chunks and retransmit it
        while True:
#            data = connection.recv(16)
            data = connection.recv(9)

            print >>sys.stderr, 'received "%s"' % data

            if data:

                if   data == "fan    on":
                  GPIO.output(4,True)
                  call(["espeak", "Dakai fongshan"])
                elif data == "fan   off":
                  GPIO.output(4,False)
                  call(["espeak", "Guanbi fongshan"])
                elif data == "light  on":
                  GPIO.output(17,True)
                  call(["espeak", "Dengliang"])
                elif data == "light off":
                  GPIO.output(17,False)
                  call(["espeak", "Guan deng"])

                print >>sys.stderr, 'sending data back to the client'
                connection.sendall(data)
            else:
                print >>sys.stderr, 'no more data from', client_address
                break

    finally:
        # Clean up the connection
        connection.close()

