Esempio n. 1
0
def move(direction):
    # Choose the direction of the request
    if direction == 'camleft':
        video_dir.move_decrease_x()
    elif direction == 'camright':
        video_dir.move_increase_x()
    elif direction == 'camup':
        video_dir.move_increase_y()
    elif direction == 'camdown':
        video_dir.move_decrease_y()
    elif direction == 'camhome':
        video_dir.home_x_y()
    elif direction == 'record':
        subprocess.call(['motion'], shell=True)
    elif direction == 'stoprecord':
        subprocess.call(['./stop.sh'], shell=True)
    elif direction == 'forward':
        motor.forward()
    elif direction == 'reverse':
        motor.backward()
    elif direction == 'left':
        car_dir.turn_left()
    elif direction == 'right':
        car_dir.turn_right()
    elif direction == 'stop':
        motor.ctrl(0)
    elif direction == 'home':
        car_dir.home()
Esempio n. 2
0
def move(direction):
    # Choose the direction of the request
    if direction == 'camleft':
        video_dir.move_decrease_x()
    elif direction == 'camright':
        video_dir.move_increase_x()
    elif direction == 'camup':
        video_dir.move_increase_y()
    elif direction == 'camdown':
        video_dir.move_decrease_y()
    elif direction == 'camhome':
        video_dir.home_x_y()
    elif direction == 'record':
        subprocess.call(['motion'], shell=True)
    elif direction == 'stoprecord':
        subprocess.call(['./stop.sh'], shell=True)
    elif direction == 'forward':
        motor.forward()
    elif direction == 'reverse':
        motor.backward()
    elif direction == 'left':
        car_dir.turn_left()
    elif direction == 'right':
        car_dir.turn_right()
    elif direction == 'stop':
        motor.ctrl(0)
    elif direction == 'home':
        car_dir.home()
Esempio n. 3
0
def left_forward():
	print("turn left")
	turn.home()
	turn.turn_left()
	motor.forwardWithSpeed(spd=100)
	time.sleep(1)
	motor.stop()
	turn.home()
	while True:
		data = ''
		data = tcpCliSock.recv(BUFSIZ)    # Receive data sent from the client. 
		# Analyze the command received and control the car accordingly.
		if not data:
			break
		if data == ctrl_cmd[0]:
			print 'motor moving forward'
			motor.forward()
		elif data == ctrl_cmd[1]:
			print 'recv backward cmd'
			motor.backward()
		elif data == ctrl_cmd[2]:
			print 'recv left cmd'
			car_dir.turn_left()
		elif data == ctrl_cmd[3]:
			print 'recv right cmd'
			car_dir.turn_right()
		elif data == ctrl_cmd[6]:
			print 'recv home cmd'
			car_dir.home()
		elif data == ctrl_cmd[4]:
			print 'recv stop cmd'
			motor.ctrl(0)
		elif data == ctrl_cmd[5]:
			print 'read cpu temp...'
			temp = cpu_temp.read()
			tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
		elif data == ctrl_cmd[8]:
			print 'recv x+ cmd'
Esempio n. 5
0
def server(
    value, collision
):  #get value as Direction and collision as Collision detection from Shared memory
    pre_dir = 'home'
    x = 0
    flag = 0
    while True:
        sys.stdout.flush()
        print 'Waiting for connection...'
        # Waiting for connection. Once receiving a connection, the function accept() returns a separate
        # client socket for the subsequent communication. By default, the function accept() is a blocking
        # one, which means it is suspended before the connection comes.
        tcpCliSock, addr = tcpSerSock.accept()
        print '...connected from :', addr  # Print the IP address of the client connected with the server.

        while True:
            data = ''
            data = tcpCliSock.recv(BUFSIZ)
            # Receive data sent from the client.
            # Analyze the command received and control the car accordingly.
            print data
            if not data:
                break
            if x == 1:
                if flag < 5:
                    flag = flag + 1
                    continue  #if there is any collision, Do not receive data from client.If so, Get stacked!
            x = 0  #after refusing data from client, start receiving
            flag = 0
            if data == ctrl_cmd[0]:  #If Client send message "forward"
                if collision.value == 1:  #if there is obstacle in front of iCar
                    motor.ctrl(0)  #stop
                else:
                    motor.forward()  #Run the motors to forward
            elif data == ctrl_cmd[1]:  #If Client send message "backward"
                motor.backward()

            elif data == ctrl_cmd[2]:  #If Client send message "left"
                car_dir.turn_left()  #change car direction to Left

            elif data == ctrl_cmd[3]:  #If Client send message "right"
                car_dir.turn_right()  #change car direction to Right

            elif data == ctrl_cmd[6]:  #If Client send message "home"
                car_dir.home()  #Set car direction to center

            elif data == ctrl_cmd[4]:  #if Client send message "stop"
                motor.ctrl(0)  #Stop Motor running

            elif data == ctrl_cmd[
                    5]:  #If Client click auto button, send message "auto"
                #auto drive
                motor.setSpeed(44)  #Set motor speed with  optimized speed 44
                temp = value.value  #get Value from jeongwook.py that is information of Car Direction

                if collision.value != 0:  #If there is Collision
                    print 'Collision detected'
                    if collision.value == 1:  #Collision in front of iCar
                        print "Obstacle In Front"
                        motor.collision_auto(
                        )  #collision_auto function let iCar move backward
                        car_dir.turn_right()  #to avoid collision, turn right
                        motor.forward_auto(
                        )  #move only for 0.8second (forward_auto let iCar move for 0.2second)
                        motor.forward_auto()
                        motor.forward_auto()
                        motor.forward_auto()
                        car_dir.home()
                        motor.forward_auto()
                        motor.forward_auto()
                        pre_dir = 'left'  #if iCar cannot detect any lane, it SHOULD BE on left side, so makes iCar go left after avoiding
                    elif collision.value == 2:  #Collision on Left side
                        print "Obstacle is on Left"
                        motor.collision_auto()
                        car_dir.turn_right()  #to avoid collision, turn right
                        motor.forward_auto()
                        motor.forward_auto()
                        motor.forward_auto()
                        motor.forward_auto()
                        car_dir.home()
                        motor.forward_auto()
                        motor.forward_auto()
                        pre_dir = 'left'
                    elif collision.value == 3:  #go left
                        print "Obstacle is on Right"
                        motor.collision_auto()
                        car_dir.turn_left()  #to avoid collision, turn left
                        motor.forward_auto()
                        motor.forward_auto()
                        motor.forward_auto()
                        motor.forward_auto()
                        car_dir.home()
                        motor.forward_auto()
                        motor.forward_auto()
                        pre_dir = 'right'  #if iCar cannot detect any lane, it SHOULD BE on right side, so makes iCar go right after avoiding

                    collision.value = 0

                    x = 1  #set x = 1 to Not receiving data from client for a moment

                elif temp == 1:  #iCar is on Lane, Go with center direction
                    print 'Lane is on my way'
                    car_dir.home()
                    motor.forward_auto()  #move iCar for 0.2second with 44speed
                    #because of camera delay

                elif temp == 2:  #lane is located on left side
                    print 'Lane is on left side'
                    car_dir.turn_left()
                    motor.forward_auto()
                    pre_dir = 'left'

                elif temp == 3:  #lane is located on right side
                    print 'Lane is on right side'
                    car_dir.turn_right()
                    motor.setSpeed(44)
                    motor.forward_auto()
                    pre_dir = 'right'
                else:
                    if pre_dir == 'right':  #when No detection but predict that lane is on right side
                        print 'cannot find but go right'
                        car_dir.turn_right()
                        motor.setSpeed(44)
                        motor.forward_auto()

                    elif pre_dir == 'left':  #when No detection but predict that lane is on left side
                        print 'cannot find but go left'
                        car_dir.turn_left()
                        motor.forward_auto()

                    else:
                        print 'Cannot find a Lane'  #No detection with no prediction
                        car_dir.home()  #set center direction and stop
                        motor.backward()
                        time.sleep(0.6)
                        motor.ctrl(0)
                        time.sleep(1)

            elif data == ctrl_cmd[7]:  #move camera right
                video_dir.move_increase_x()
            elif data == ctrl_cmd[8]:  #move camera left
                video_dir.move_decrease_x()
            elif data == ctrl_cmd[9]:  #move camera up
                video_dir.move_increase_y()
            elif data == ctrl_cmd[10]:  #move camera down
                video_dir.move_decrease_y()

            elif data[0:5] == 'speed':  # Change the speed
                print data
                numLen = len(data) - len('speed')
                if numLen == 1 or numLen == 2 or numLen == 3:
                    tmp = data[-numLen:]
                    spd = int(tmp)
                    if spd < 24:
                        spd = 24
                    motor.setSpeed(spd)

            elif data[
                    0:
                    7] == 'leftPWM':  #If Client send message like ~PWM, it is for initialization or servo motor that control Car direction.
                numLen = len(data) - len('leftPWM')
                pwm = data[-numLen:]
                leftpwm = int(pwm)

                car_dir.change_left(leftpwm)
            elif data[0:7] == 'homePWM':
                numLen = len(data) - len('homePWM')
                pwm = data[-numLen:]
                homepwm = int(pwm)

                car_dir.change_home(homepwm)
            elif data[0:8] == 'rightPWM':
                numLen = len(data) - len('rightPWM')
                pwm = data[-numLen:]
                rightpwm = int(pwm)
                car_dir.change_right(rightpwm)

            else:
                print 'Command Error! Cannot recognize command: ' + data

    tcpSerSock.close()
def run_server(key):
    #!/usr/bin/env python
    import RPi.GPIO as GPIO
    import video_dir
    import car_dir
    import motor
    from time import ctime  # Import necessary modules

    ctrl_cmd = [
        'forward', 'backward', 'left', 'right', 'stop', 'read cpu_temp',
        'home', 'distance', 'x+', 'x-', 'y+', 'y-', 'xy_home'
    ]

    busnum = 1  # Edit busnum to 0, if you uses Raspberry Pi 1 or 0

    HOST = ''  # The variable of HOST is null, so the function bind( ) can be bound to all valid addresses.
    PORT = 21567
    BUFSIZ = 1024  # Size of the buffer
    ADDR = (HOST, PORT)

    tcpSerSock = socket(AF_INET, SOCK_STREAM)  # Create a socket.
    tcpSerSock.bind(ADDR)  # Bind the IP address and port number of the server.
    tcpSerSock.listen(
        5
    )  # The parameter of listen() defines the number of connections permitted at one time. Once the
    # connections are full, others will be rejected.

    #video_dir.setup(busnum=busnum)
    #car_dir.setup(busnum=busnum)
    #motor.setup(busnum=busnum)     # Initialize the Raspberry Pi GPIO connected to the DC motor.
    #video_dir.home_x_y()
    #car_dir.home()

    while True:
        print 'Waiting for connection...'
        # Waiting for connection. Once receiving a connection, the function accept() returns a separate
        # client socket for the subsequent communication. By default, the function accept() is a blocking
        # one, which means it is suspended before the connection comes.
        tcpCliSock, addr = tcpSerSock.accept()
        print '...connected from :', addr  # Print the IP address of the client connected with the server.

        while True:
            try:
                data = ''
                data = tcpCliSock.recv(
                    BUFSIZ)  # Receive data sent from the client.
                print "\nEncrypted command recieved from client = ,", eval(
                    data)[2]
                data = crypto.AES_decrypt(eval(data), key)
            except:
                print "INCOMPLETE PACKET ERROR - try to input the command again"
            # Analyze the command received and control the car accordingly.

            if not data:
                break
            if data == ctrl_cmd[0]:
                print 'motor moving forward'
                motor.forward()
            elif data == ctrl_cmd[1]:
                print 'recv backward cmd'
                motor.backward()
            elif data == ctrl_cmd[2]:
                print 'recv left cmd'
                car_dir.turn_left()
            elif data == ctrl_cmd[3]:
                print 'recv right cmd'
                car_dir.turn_right()
            elif data == ctrl_cmd[6]:
                print 'recv home cmd'
                car_dir.home()
            elif data == ctrl_cmd[4]:
                print 'recv stop cmd'
                motor.ctrl(0)
            elif data == ctrl_cmd[5]:
                print 'read cpu temp...'
                temp = cpu_temp.read()
                tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
            elif data == ctrl_cmd[8]:
                print 'recv x+ cmd'
                video_dir.move_increase_x()
            elif data == ctrl_cmd[9]:
                print 'recv x- cmd'
                video_dir.move_decrease_x()
            elif data == ctrl_cmd[10]:
                print 'recv y+ cmd'
                video_dir.move_increase_y()
            elif data == ctrl_cmd[11]:
                print 'recv y- cmd'
                video_dir.move_decrease_y()
            elif data == ctrl_cmd[12]:
                print 'home_x_y'
                video_dir.home_x_y()
            elif data[0:5] == 'speed':  # Change the speed
                print data
                numLen = len(data) - len('speed')
                if numLen == 1 or numLen == 2 or numLen == 3:
                    tmp = data[-numLen:]
                    print 'tmp(str) = %s' % tmp
                    spd = int(tmp)
                    print 'spd(int) = %d' % spd
                    if spd < 24:
                        spd = 24
                    motor.setSpeed(spd)
            elif data[0:5] == 'turn=':  #Turning Angle
                print 'data =', data
                angle = data.split('=')[1]
                try:
                    angle = int(angle)
                    car_dir.turn(angle)
                except:
                    print 'Error: angle =', angle
            elif data[0:8] == 'forward=':
                print 'data =', data
                spd = data[8:]
                try:
                    spd = int(spd)
                    motor.forward(spd)
                except:
                    print 'Error speed =', spd

            elif data[0:9] == 'backward=':
                print 'data =', data
                spd = data.split('=')[1]
                try:
                    spd = int(spd)
                    motor.backward(spd)
                except:
                    print 'ERROR, speed =', spd

            else:
                #print 'Command Error! Cannot recognize command: ' + data
                print "COMMAND ERROR - Unable to interpret recieved command"
    tcpSerSock.close()
Esempio n. 7
0
 def left(self):
     cd.turn_left()
Esempio n. 8
0
def on_message(ws, data):
    print data
    # Analyze the command received and control the car accordingly.
    #if not data:

    if data == ctrl_cmd[0]:
        print 'motor moving forward'
        motor.forward()
    elif data == ctrl_cmd[1]:
        print 'recv backward cmd'
        motor.backward()
    elif data == ctrl_cmd[2]:
        print 'recv left cmd'
        car_dir.turn_left()
    elif data == ctrl_cmd[3]:
        print 'recv right cmd'
        car_dir.turn_right()
    elif data == ctrl_cmd[6]:
        print 'recv home cmd'
        car_dir.home()
    elif data == ctrl_cmd[4]:
        print 'recv stop cmd'
        motor.ctrl(0)
    elif data == ctrl_cmd[5]:
        print 'read cpu temp...'
        temp = cpu_temp.read()
        tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
    elif data == ctrl_cmd[8]:
        print 'recv x+ cmd'
        video_dir.move_increase_x()
    elif data == ctrl_cmd[9]:
        print 'recv x- cmd'
        video_dir.move_decrease_x()
    elif data == ctrl_cmd[10]:
        print 'recv y+ cmd'
        video_dir.move_increase_y()
    elif data == ctrl_cmd[11]:
        print 'recv y- cmd'
        video_dir.move_decrease_y()
    elif data == ctrl_cmd[12]:
        print 'home_x_y'
        video_dir.home_x_y()
    elif data[0:12] == ctrl_cmd[13]:     # Change the speed
        print data
        #numLen = len(data) - len('speed')
        #if numLen == 1 or numLen == 2 or numLen == 3:
        #    tmp = data[-numLen:]
        #    print 'tmp(str) = %s' % tmp
        #    spd = int(tmp)
        #    print 'spd(int) = %d' % spd
        #    if spd < 24:
        #        spd = 24
        motor.setSpeed(30)
    elif data[0:5] == 'turn=':	#Turning Angle
        print 'data =', data
        angle = data.split('=')[1]
        try:
            angle = int(angle)
            car_dir.turn(angle)
        except:
            print 'Error: angle =', angle
    elif data[0:8] == 'forward=':
        print 'data =', data
        spd = 30
        try:
            spd = int(spd)
            motor.forward(spd)
        except:
            print 'Error speed =', spd
    elif data[0:9] == 'backward=':
        print 'data =', data
        spd = data.split('=')[1]
        try:
            spd = int(spd)
            motor.backward(spd)
        except:
            print 'ERROR, speed =', spd

    else:
        print 'Command Error! Cannot recognize command: ' + data
Esempio n. 9
0
def drive(stops):
    # setup all devices and initialize values
    busnum = 1
    car_dir.setup(busnum=busnum)
    motor.setup(busnum=busnum)
    distance_detect.setup()
    car_dir.home()
    motor.setSpeed(30)

    video_capture = cv2.VideoCapture(-1)
    video_capture.set(3, 160)
    video_capture.set(4, 120)
    command = 0
    stopCount = 0
    stopFound = 0

    #drive until passed certain amount of stops
    while True:
        # capture video frames
        ret, frame = video_capture.read()

        # set color masking boundaries for red and mask image
        colorLower = np.array([0, 0, 100], dtype='uint8')
        colorUpper = np.array([50, 50, 255], dtype='uint8')
        colorMask = cv2.inRange(frame, colorLower, colorUpper)
        outMask = cv2.bitwise_and(frame, frame, mask=colorMask)

        # create mask image, convert to grayscale, and blur
        clonedImg = outMask.copy()
        clonedImg = cv2.cvtColor(clonedImg, cv2.COLOR_BGR2GRAY)
        clonedImg = cv2.GaussianBlur(clonedImg, (5, 5), 0)

        # show current image
        cv2.namedWindow('Gray color select', cv2.WINDOW_NORMAL)
        cv2.imshow('Gray color select', clonedImg)

        # calculate circles within image
        circles = cv2.HoughCircles(clonedImg,
                                   cv2.cv.CV_HOUGH_GRADIENT,
                                   1,
                                   20,
                                   param1=50,
                                   param2=30,
                                   minRadius=15,
                                   maxRadius=100)

        # if a circle was detected
        if circles != None:
            # if this is first time encountering this stop increase stop count
            if stopFound == 0:
                stopCount += 1
                stopFound = 1

            # map out circles for display
            circles = np.uint16(np.around(circles))

            for i in circles[0, :]:
                cv2.circle(clonedImg, (i[0], i[1]), i[2], (0, 255, 0), 2)
                cv2.circle(clonedImg, (i[0], i[1]), 2, (0, 255, 0), 3)
        elif (cv2.countNonZero(clonedImg) == 0):
            stopFound = 0

        # display camera feed and circles
        cv2.namedWindow('Circles', cv2.WINDOW_NORMAL)
        cv2.imshow('Circles', clonedImg)

        # crop the image
        crop_img = frame[60:120, 0:160]

        # convert to grayscale
        gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)

        # gaussian blur
        blur = cv2.GaussianBlur(gray, (5, 5), 0)

        # color thresholding
        ret, thresh = cv2.threshold(blur, 60, 255, cv2.THRESH_BINARY_INV)

        # find the contours of the frame
        contours, hierarchy = cv2.findContours(thresh.copy(), 1,
                                               cv2.CHAIN_APPROX_NONE)

        # detect distance to closes object
        dis = distance_detect.checkdis()
        print "distance: ", dis

        # find the biggest contour (if detected)
        if len(contours) > 0 and dis >= 15:
            c = max(contours, key=cv2.contourArea)
            M = cv2.moments(c)

            if M['m00'] != 0:
                cx = int(M['m10'] / M['m00'])
                cy = int(M['m01'] / M['m00'])

            cv2.line(crop_img, (cx, 0), (cx, 720), (255, 0, 0), 1)
            cv2.line(crop_img, (0, cy), (1280, cy), (255, 0, 0), 1)
            cv2.drawContours(crop_img, contours, -1, (0, 255, 0), 1)

            if cx >= 120:
                print "Turn Right ", cx
                car_dir.turn_right()
                motor.forward()

            if cx < 120 and cx > 50:
                print "On Track! ", cx
                car_dir.home()
                motor.forward()

            if cx <= 50:
                print "Turn Left! ", cx
                car_dir.turn_left()
                motor.forward()

        else:
            if dis < 15:
                print "something blocking me"
                car_dir.home()
                motor.stop()
            else:
                print "I don't see the line"
                car_dir.home()
                motor.backward()

        # display the resulting frame
        cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
        cv2.imshow('frame', crop_img)

        # exit condition after passing certain amount of stops or 'q' is pressed
        if stopCount == stops or (cv2.waitKey(1) & 0xFF == ord('q')):
            # clean up
            motor.stop()
            distance_detect.cleanup()
            cv2.destroyAllWindows()
            break
    def run(self):

        while True:
            print 'Waiting for connection...'

            tcpCliSock, addr = tcpSerSock.accept()
            print '...connected from :', addr

            while True:
                data = ''
                data = tcpCliSock.recv(BUFSIZ)
                if not data:
                    break
                if data == ctrl_cmd[0]:
                    print 'motor moving forward'
                    motor.forward()
                elif data == ctrl_cmd[1]:
                    print 'recv backward cmd'
                    motor.backward()
                elif data == ctrl_cmd[2]:
                    print 'recv left cmd'
                    car_dir.turn_left()
                elif data == ctrl_cmd[3]:
                    print 'recv right cmd'
                    car_dir.turn_right()
                elif data == ctrl_cmd[6]:
                    print 'recv home cmd'
                    car_dir.home()
                elif data == ctrl_cmd[4]:
                    print 'recv stop cmd'
                    motor.ctrl(0)
                elif data == ctrl_cmd[5]:
                    print 'read cpu temp...'
                    temp = cpu_temp.read()
                    tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
                elif data == ctrl_cmd[8]:
                    print 'recv x+ cmd'
                    video_dir.move_increase_x()
                elif data == ctrl_cmd[9]:
                    print 'recv x- cmd'
                    video_dir.move_decrease_x()
                elif data == ctrl_cmd[10]:
                    print 'recv y+ cmd'
                    video_dir.move_increase_y()
                elif data == ctrl_cmd[11]:
                    print 'recv y- cmd'
                    video_dir.move_decrease_y()
                elif data == ctrl_cmd[12]:
                    print 'home_x_y'
                    video_dir.home_x_y()
                elif data[0:5] == 'speed':
                    print data
                    numLen = len(data) - len('speed')
                    if numLen == 1 or numLen == 2 or numLen == 3:
                        tmp = data[-numLen:]
                        print 'tmp(str) = %s' % tmp
                        spd = int(tmp)
                        print 'spd(int) = %d' % spd
                        if spd < 24:
                            spd = 24
                        motor.setSpeed(spd)
                elif data[0:5] == 'turn=':
                    print 'data =', data
                    angle = data.split('=')[1]
                    try:
                        angle = int(angle)
                        car_dir.turn(angle)
                    except:
                        print 'Error: angle =', angle
                elif data[0:8] == 'forward=':
                    print 'data =', data
                    spd = data[8:]
                    try:
                        spd = int(spd)
                        motor.forward(spd)
                    except:
                        print 'Error speed =', spd
                elif data[0:9] == 'backward=':
                    print 'data =', data
                    spd = data.split('=')[1]
                    try:
                        spd = int(spd)
                        motor.backward(spd)
                    except:
                        print 'ERROR, speed =', spd

                else:
                    print 'Command Error! Cannot recognize command: ' + data

        tcpSerSock.close()
Esempio n. 11
0
            angle = int((pred / 2 + 0.5) * 170 + 35)
            data = "turn=" + str(angle)

        if lstop_detected:
            motor.forward()
            lstop_detected = False

        if data == ctrl_cmd[0]:
            print 'motor moving forward'
            motor.forward()
        elif data == ctrl_cmd[1]:
            print 'recv backward cmd'
            motor.backward()
        elif data == ctrl_cmd[2]:
            print 'recv left cmd'
            car_dir.turn_left()
        elif data == ctrl_cmd[3]:
            print 'recv right cmd'
            car_dir.turn_right()
        elif data == ctrl_cmd[6]:
            print 'recv home cmd'
            car_dir.home()
        elif data == ctrl_cmd[4]:
            print 'recv stop cmd'
            motor.ctrl(0)
        elif data == ctrl_cmd[5]:
            print 'read cpu temp...'
            temp = cpu_temp.read()
        elif data == ctrl_cmd[8]:
            print 'recv x+ cmd'
            video_dir.move_increase_x()
        elif data == ctrl_cmd[9]:
Esempio n. 12
0
 def steer_left(self):
     sfsteering.turn_left()
     return True
def process_request(data):
    # Analyze the command received and control the car accordingly.
    if not data:
        return "cmd not understood"
    if data == ctrl_cmd[0]:
        print('motor moving forward')
        motor.forward()
    elif data == ctrl_cmd[1]:
        print('recv backward cmd')
        motor.backward()
    elif data == ctrl_cmd[2]:
        print('recv left cmd')
        car_dir.turn_left()
    elif data == ctrl_cmd[3]:
        print('recv right cmd')
        car_dir.turn_right()
    elif data == ctrl_cmd[6]:
        print('recv home cmd')
        car_dir.home()
    elif data == ctrl_cmd[4]:
        print('recv stop cmd')
        motor.ctrl(0)
    elif data == ctrl_cmd[5]:
        print('read cpu temp...')
        temp = cpu_temp.read()
        tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
    elif data == ctrl_cmd[8]:
        print('recv x+ cmd')
        video_dir.move_increase_x()
    elif data == ctrl_cmd[9]:
        print('recv x- cmd')
        video_dir.move_decrease_x()
    elif data == ctrl_cmd[10]:
        print('recv y+ cmd')
        video_dir.move_increase_y()
    elif data == ctrl_cmd[11]:
        print('recv y- cmd')
        video_dir.move_decrease_y()
    elif data == ctrl_cmd[12]:
        print('home_x_y')
        video_dir.home_x_y()
    elif data[0:5] == 'speed':     # Change the speed
        print(data)
        numLen = len(data) - len('speed')
        if numLen == 1 or numLen == 2 or numLen == 3:
            tmp = data[-numLen:]
            print('tmp(str) = %s' % tmp)
            spd = int(tmp)
            print('spd(int) = %d' % spd)
            if spd < 24:
                spd = 24
            motor.setSpeed(spd)
    elif data[0:5] == 'turn=':  # Turning Angle
        print('data =', data)
        angle = data.split('=')[1]
        try:
            angle = int(angle)
            car_dir.turn(angle)
        except:
            print('Error: angle =', angle)
    elif data[0:8] == 'forward=':
        print('data =', data)
        spd = data[8:]
        try:
            spd = int(spd)
            motor.forward(spd)
        except:
            print('Error speed =', spd)
    elif data[0:9] == 'backward=':
        print('data =', data)
        spd = data.split('=')[1]
        try:
            spd = int(spd)
            motor.backward(spd)
        except:
            print('ERROR, speed =', spd)
    else:
        print('Command Error! Cannot recognize command: ' + data)
Esempio n. 14
0
def CarController(socket):
    while True:
        print 'Waiting for connection to car controller service...'
        # Waiting for connection. Once receiving a connection, the function accept() returns a separate
        # client socket for the subsequent communication. By default, the function accept() is a blocking
        # one, which means it is suspended before the connection comes.
        clientSocket, addr = socket.accept()
        print '...connected to car controller service:', addr  # Print the IP address of the client connected with the server.

        lastCmd = ''

        while True:
            msgs = ''
            recdata = clientSocket.recv(BUFSIZ)
            # Receive data sent from the client.
            # Analyze the command received and control the car accordingly.
            msgs = recdata.split(';')
            #print("Received", len(msgs), "new messages")
            for data in msgs:
                if not data:
                    break

                if lastCmd == data:
                    print("Last Command:", lastCmd, "Current Data:", data,
                          "Ignoring")
                    break

                if data == ctrl_cmd[0]:
                    print 'motor moving forward'
                    motor.forward()
                elif data == ctrl_cmd[1]:
                    print 'recv backward cmd'
                    motor.backward()
                elif data == ctrl_cmd[2]:
                    print 'recv left cmd'
                    car_dir.turn_left()
                elif data == ctrl_cmd[3]:
                    print 'recv right cmd'
                    car_dir.turn_right()
                elif data == ctrl_cmd[6]:
                    print 'recv home cmd'
                    car_dir.home()
                elif data == ctrl_cmd[4]:
                    print 'recv stop cmd'
                    motor.ctrl(0)
                elif data == ctrl_cmd[5]:
                    print 'read cpu temp...'
                    temp = cpu_temp.read()
                    tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
                elif data[0:5] == 'speed':
                    #print data
                    numLen = len(data) - len('speed')
                    if numLen == 1 or numLen == 2 or numLen == 3:
                        tmp = data[-numLen:]
                        #print 'tmp(str) = %s' % tmp
                        spd = int(tmp)
                        #print 'spd(int) = %d' % spd
                        if spd < 24:
                            spd = 24
                        motor.setSpeed(spd)
                elif data[0:8] == 'network=':
                    print 'network =', data
                    spd = data.split('=')[1]
                    try:
                        spd = int(spd)
                        os.system('sudo tc qdisc del dev wlan0 root')
                        os.system(
                            'sudo tc qdisc add dev wlan0 root netem delay {0}ms'
                            .format(spd))
                    except:
                        print 'ERROR , speed =', spd
                elif data[0:7] == 'offset=':
                    print 'offset called, data = ', data
                    offset = int(data[7:]) + 28
                    car_dir.calibrate(offset)
                elif data[0:8] == 'forward=':
                    #print 'data =', data
                    spd = data.split('=')[1]
                    try:
                        spd = int(spd)
                        motor.setSpeed(spd)
                        motor.forward()
                    except:
                        print 'Error speed =', spd
                elif data[0:9] == 'backward=':
                    #print 'data =', data
                    spd = data.split('=')[1]
                    try:
                        spd = int(spd)
                        motor.setSpeed(spd)
                        motor.backward()
                    except:
                        print 'ERROR , speed =', spd

                else:
                    print 'Command Error! Cannot recognize command: ' + data
Esempio n. 15
0
def mover():
    #Init variables for the control loop
    counter = 1
    bDriving = False
    bEndLoops = False

    sRobotDirection = Direction()

    rospy.init_node('mover', anonymous=True)

    rospy.Subscriber("motioncommand", String,
                     sRobotDirection.direction_callback)

    scooper_dir.setup(busnum=busnum)
    car_dir.setup(busnum=busnum)

    # Initialize the Raspberry Pi GPIO connected to the DC motor.
    motor.setup(busnum=busnum)

    #video_dir.home_x_y()
    #scooper_dir.servo_test ()
    car_dir.home()

    # Loop to wait for received commands.
    while (bEndLoops == False):

        # Loop to perform movement controls while input received.
        while (bEndLoops == False):

            data = sRobotDirection.directionMsg

            # Analyze the command received and control the car accordingly.
            #doAction (data, counter)
            #counter += 1
            #print counter

            if not data:
                break

            if data == ctrl_cmd[0]:
                print 'ELFF WILL DRIVE'
                counter += 1
                print counter

                try:
                    spd = 20
                    #print "Moving forward with speed!"
                    motor.forwardWithSpeed(spd)
                except:
                    print 'Error speed =' + str(spd)

            elif data == ctrl_cmd[1]:
                print 'ELFF WILL REVERSE'
                counter += 1
                print counter

                try:
                    spd = 20
                    #print "Moving backward with speed!"
                    motor.backwardWithSpeed(spd)
                except:
                    print 'Error speed =' + str(spd)

            elif data == ctrl_cmd[2]:
                print 'ELFF WILL GO LEFT'
                counter += 1
                car_dir.turn_left()

            elif data == ctrl_cmd[3]:
                print 'ELFF WILL GO RIGHT'
                counter += 1
                car_dir.turn_right()

            elif data == ctrl_cmd[4]:
                print 'ELFF WILL SCOOP'

                scooper_dir.home_x_y()
                scooper_dir.doScoop()
                scooper_dir.home_x_y()

            # Used with publisher.py only as a debug method.
            elif data == ctrl_cmd[5]:
                print 'ELFF WILL RESET POSITION'
                scooper_dir.home_x_y()
                car_dir.home()
                motor.ctrl(0)

                bEndLoops = True

            elif data == ctrl_cmd[6]:
                print 'ELFF WILL STOP'
                counter += 1
                print counter
                try:
                    spd = 0
                    motor.forwardWithSpeed(spd)
                except:
                    print 'Error speed =' + str(spd)

            else:
                print 'Waiting to receive a command...'
Esempio n. 16
0
def turn_left():
	car_dir.turn_left()
Esempio n. 17
0
		data = tcpCliSock.recv(BUFSIZ)    # Receive data sent from the client. 
		# Analyze the command received and control the car accordingly.
		if not data:
			break

		print('data : ' + str(data))

		elif data == ctrl_cmd[0]:
			
			motor.forward()
		elif data == ctrl_cmd[1]:
			
			motor.backward()
		elif data == ctrl_cmd[2]:
			
			car_dir.turn_left()
		elif data == ctrl_cmd[3]:
			
			car_dir.turn_right()
		elif data == ctrl_cmd[6]:
			
			car_dir.home()
		elif data == ctrl_cmd[4]:
			
			motor.ctrl(0)
		elif data == ctrl_cmd[5]:
			
			temp = cpu_temp.read()
			tcpCliSock.send('[%s] %0.2f' % (ctime(), temp))
		elif data == ctrl_cmd[8]:
			
Esempio n. 18
0
 def turn_left(self):
     """Front wheels will turn left, regardless of whether it
     is moving or not."""
     car_dir.turn_left()