from bluetooth import *
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service( server_sock, "SampleServer",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ], 
#                   protocols = [ OBEX_UUID ] 
                    )
                   
print "Waiting for connection on RFCOMM channel %d" % port

client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print "received [%s]" % data

        if data == "backward":
            GPIO.output(17,True)
            GPIO.output(27,False)
            GPIO.output(23,False)
            GPIO.output(22,True)
            print "motor on"

        if data == "forward":
            GPIO.output(22,False)
            GPIO.output(23,True)
            GPIO.output(17,False)
            GPIO.output(27,True)
            print "motor on"

        if data == "turn left":
            GPIO.output(27,True)
            GPIO.output(17,False)
            GPIO.output(22,False)
            GPIO.output(23,False)
            print "motor on"

        if data == "turn right":
            GPIO.output(17,False)
            GPIO.output(22,False)
            GPIO.output(27,False)
            GPIO.output(23,True)
            print "motor on"    
            
        if data == "stop":
            GPIO.output(17,False)
            GPIO.output(27,False)
            GPIO.output(23,False)
            GPIO.output(22,False)
            print "motor off"

except IOError:
    pass

print "disconnected"

client_sock.close()
server_sock.close()

GPIO.output(17,False)
GPIO.output(27,False)
GPIO.output(23,False)
GPIO.output(22,False)
            
print "all done"