Example #1
0
def cozmo_program(robot: cozmo.robot.Robot):
    robot.world.image_annotator.add_static_text(
        'text', 'Coz-Cam', position=cozmo.annotate.TOP_RIGHT)
    robot.world.image_annotator.add_annotator('clock', clock)
    robot.world.image_annotator.add_annotator('battery', Battery)
    print("--------------------------")
    print("Battery (below 3.5V is low)")
    print(robot.world.robot.battery_voltage)
    print("--------------------------")

    robot.world.add_event_handler(cozmo.objects.EvtObjectTapped, object_tapped)
    # Initialization
    if robot.is_on_charger:
        robot.drive_off_charger_contacts().wait_for_completed()
        robot.drive_straight(distance_mm(100),
                             speed_mmps(50)).wait_for_completed()

    robot.start_freeplay_behaviors()

    while True:
        time.sleep(1)
        # Run mini games
        run = random.randint(0, 100)
        global interaction
        if run == 1:
            interaction = 1
            useless(robot)
        interaction = 0
 def check_charger(self, robot:cozmo.robot.Robot, distance=150, speed=100):
     if robot.is_on_charger:
         if log:
             print("I am on the charger. Driving off the charger...")
         robot.drive_off_charger_contacts().wait_for_completed()
         robot.drive_straight(distance_mm(distance), speed_mmps(speed)).wait_for_completed()
         robot.move_lift(-8)
Example #3
0
def drive_to_charger(robot: cozmo.robot.Robot):
    robot.say_text(
        "You're welcome. I'm done. Now I am going to take a nap. Bye bye."
    ).wait_for_completed()
    '''The core of the drive_to_charger program'''

    # If the robot was on the charger, drive them forward and clear of the charger
    if robot.is_on_charger:
        # drive off the charger
        robot.drive_off_charger_contacts().wait_for_completed()
        robot.drive_straight(distance_mm(100),
                             speed_mmps(50)).wait_for_completed()
        # Start moving the lift down
        robot.move_lift(-3)
        # turn around to look at the charger
        robot.turn_in_place(degrees(180)).wait_for_completed()
        # Tilt the head to be level
        robot.set_head_angle(degrees(0)).wait_for_completed()
        # wait half a second to ensure Cozmo has seen the charger
        time.sleep(0.5)
        # drive backwards away from the charger
        robot.drive_straight(distance_mm(-60),
                             speed_mmps(50)).wait_for_completed()

    # try to find the charger
    charger = None

    # see if Cozmo already knows where the charger is
    if robot.world.charger:
        if robot.world.charger.pose.is_comparable(robot.pose):
            print("Cozmo already knows where the charger is!")
            charger = robot.world.charger
        else:
            # Cozmo knows about the charger, but the pose is not based on the
            # same origin as the robot (e.g. the robot was moved since seeing
            # the charger) so try to look for the charger first
            pass

    if not charger:
        # Tell Cozmo to look around for the charger
        look_around = robot.start_behavior(
            cozmo.behavior.BehaviorTypes.LookAroundInPlace)
        try:
            charger = robot.world.wait_for_observed_charger(timeout=30)
            print("Found charger: %s" % charger)
        except asyncio.TimeoutError:
            print("Didn't see the charger")
        finally:
            # whether we find it or not, we want to stop the behavior
            look_around.stop()

    if charger:
        # Attempt to drive near to the charger, and then stop.
        action = robot.go_to_object(charger, distance_mm(65.0))
        action.wait_for_completed()
        print("Completed action: result = %s" % action)
        print("Done.")
Example #4
0
def main(robot: cozmo.robot.Robot):
    print(f"\n---------------------------\n\nStarting robot as {robot}\n\n")
    robot.say_text("Starting manual control").wait_for_completed()
    robot.drive_off_charger_contacts().wait_for_completed()
    robot.drive_straight(distance_mm(100),
                         speed_mmps(200)).wait_for_completed()
    loop = True
    while loop == True:
        events = get_gamepad()
        for event in events:
            if event.code == "BTN_SOUTH" and event.state == 1:
                print("[inputs]", event.code, event.state, "\n  >SMASHING\n")
                robot.set_lift_height(1, 0, 0, 0).wait_for_completed()
                robot.set_lift_height(0, 0, 0, 0).wait_for_completed()

            if event.code == "BTN_WEST" and event.state == 1:
                print("[inputs]", event.code, event.state, "\n  >ROASTED")
                rand = random.randint(0, len(roasts) - 1)
                print(f"rand is {rand}")
                robot.say_text(roasts[rand]).wait_for_completed()

            if event.code == "ABS_HAT0Y" and event.state == -1:
                print("[inputs]", event.code, event.state, "\n  >LIFTING UP\n")
                robot.set_lift_height(1, 5, 0, 0).wait_for_completed()
            elif event.code == "ABS_HAT0Y" and event.state == 1:
                print("[inputs]", event.code, event.state,
                      "\n  >LIFTING DOWN\n")
                robot.set_lift_height(0, 5, 0, 0).wait_for_completed()

            if event.code == "ABS_Y" and event.state >= 3000:
                print("[inputs]", event.code, event.state,
                      "\n  >DRIVING FORWARD\n")
                robot.drive_straight(distance_mm(300),
                                     speed_mmps(200)).wait_for_completed()
            elif event.code == "ABS_Y" and event.state <= -3000:
                print("[inputs]", event.code, event.state,
                      "\n  >LIFTING BACKWARD\n")
                robot.drive_straight(distance_mm(-300),
                                     speed_mmps(200)).wait_for_completed()

            if event.code == "ABS_RX" and event.state >= 3000:
                print("[inputs]", event.code, event.state,
                      "\n  >TURNING RIGHT\n")
                robot.turn_in_place(degrees(-45)).wait_for_completed()
            elif event.code == "ABS_RX" and event.state <= -3000:
                print("[inputs]", event.code, event.state,
                      "\n  >TURNING LEFT\n")
                robot.turn_in_place(degrees(45)).wait_for_completed()

            if event.code == "BTN_START" and event.state == 1:
                print("\n\t>KILLING PROGRAM, BYEBYE!!!\n")
                loop = False
Example #5
0
def initial_settings(robot: cozmo.robot.Robot):
    # Set Neutral Face fot Cozmo
    robot.play_anim_trigger(cozmo.anim.Triggers.NeutralFace,
                            in_parallel=True).wait_for_completed()
    # check if Cozmo is on charger
    charger = robot.is_on_charger
    # Set Cozmo volume
    robot.set_robot_volume(robot_volume=0.3)
    # Activate face expression estimation
    robot.enable_facial_expression_estimation()
    # Activate stop on cliff
    robot.enable_stop_on_cliff(enable=True)
    # Volts on battery
    battery = robot.battery_voltage
    # If Cozmo is on charger, drive off it to start FindFaces behavior
    if charger is True:
        robot.drive_off_charger_contacts(in_parallel=True).wait_for_completed()
        robot.drive_straight(distance_mm(120),
                             speed_mmps(50),
                             in_parallel=True)
    # Set lift to down position5
    robot.move_lift(-3)
    # Start "Battery check" animation
    robot.say_text("Checking battery level",
                   in_parallel=True,
                   use_cozmo_voice=Voice,
                   duration_scalar=0.85).wait_for_completed()
    # Cozmo announce that he is ready to play if battery is higher then 3.6 volts - If less than 3.6 volts, Cozmo as to be placed on charger
    if battery > 3.69:
        robot.play_anim_trigger(cozmo.anim.Triggers.VC_Alrighty,
                                in_parallel=True).wait_for_completed()
        robot.say_text("My battery is good! I am ready to play!",
                       in_parallel=True,
                       play_excited_animation=False,
                       use_cozmo_voice=Voice,
                       duration_scalar=0.85).wait_for_completed()
        robot.set_head_angle(degrees(30)).wait_for_completed()
    else:
        robot.play_anim_trigger(
            cozmo.anim.Triggers.SparkFailure).wait_for_completed()
        robot.play_anim_trigger(cozmo.anim.Triggers.NeedsSevereLowEnergyGetIn,
                                in_parallel=True).wait_for_completed()
        robot.say_text(
            "I need to charge my battery. Please, place me on the charger.",
            in_parallel=True,
            use_cozmo_voice=Voice,
            duration_scalar=0.85).wait_for_completed()
def cozmo_program(robot: cozmo.robot.Robot):
    print("--------------------------")
    print("Battery (below 3.5V is low)")
    print(robot.world.robot.battery_voltage)
    print("--------------------------")
    new_color = cozmo.lights.Color(rgb=(0, 255, 0))
    green = cozmo.lights.Light(on_color=new_color)

    cubes = [
        robot.world.light_cubes.get(cozmo.objects.LightCube1Id),
        robot.world.light_cubes.get(cozmo.objects.LightCube2Id),
        robot.world.light_cubes.get(cozmo.objects.LightCube3Id)
    ]
    for cube in cubes:
        cube.set_lights(green)
    time.sleep(1)
    robot.world.add_event_handler(cozmo.objects.EvtObjectTapped, tap_handler)

    if robot.is_on_charger:
        robot.drive_off_charger_contacts().wait_for_completed()
        robot.drive_straight(distance_mm(100),
                             speed_mmps(50)).wait_for_completed()
    robot.say_text("Where are my cubes?").wait_for_completed()
    look = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
    cube_vision = robot.world.wait_until_observe_num_objects(
        num=3,
        object_type=cozmo.objects.LightCube,
        timeout=30,
        include_existing=True)
    look.stop()
    print("Cubes found")
    robot.say_text("My favourite color is green!").wait_for_completed()
    global id_cube
    while True:
        time.sleep(1)
        if id_cube:
            robot.play_anim_trigger(cozmo.anim.Triggers.CubePounceLoseSession
                                    ).wait_for_completed()
            print("Going to cube ", id_cube)
            for mycube in cube_vision:
                if mycube.object_id == id_cube:
                    robot.go_to_object(mycube,
                                       distance_mm(60)).wait_for_completed()
                    robot.play_anim(name="ID_pokedB").wait_for_completed()
                    mycube.set_lights(green)
            id_cube = None
Example #7
0
def wiggle_for_charger(robot: cozmo.robot.Robot):
    robot.set_lift_height(0, accel=20).wait_for_completed()
    drive = robot.drive_straight(distance=distance_mm(-200),
                                 speed=speed_mmps(50))
    ax0 = robot.accelerometer.x
    dx = None
    while True:
        ax1 = robot.accelerometer.x
        dx = ax1 - ax0
        ax0 = ax1
        time.sleep(
            .1)  #useless to take a dx at every iteration of the While loop
        if abs(dx) > 1000:
            #pretty sure we hit the charger
            print('Hit charger!')
            drive.abort()
            #proceed to wiggle
            robot.drive_wheels(-100.0,
                               -100.0,
                               l_wheel_acc=150,
                               r_wheel_acc=150)
            while not robot.is_on_charger:
                # robot.set_lift_height(1, accel=100, duration=0, in_parallel=True)
                # robot.set_lift_height(.6, accel=100, duration=0, in_parallel=True)
                robot.move_lift(10)
                time.sleep(.05)
                robot.move_lift(-10)
                time.sleep(1)
            robot.drive_wheels(0.0, 0.0)
            time.sleep(3)
            robot.drive_off_charger_contacts().wait_for_completed()
            robot.drive_straight(distance=distance_mm(125),
                                 speed=speed_mmps(100)).wait_for_completed()
            break
    robot.play_anim_trigger(
        cozmo.anim.Triggers.CubePounceWinHand).wait_for_completed()
def cozmo_program(robot: cozmo.robot.Robot):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket_error as msg:
        robot.say_text("socket failed" + msg).wait_for_completed()
    ip = "10.0.1.10"
    port = 5000

    try:
        s.connect((ip, port))
    except socket_error as msg:
        robot.say_text("socket failed to bind").wait_for_completed()
    cont = True

    robot.say_text("ready").wait_for_completed()

    #SET COZMO's NAME
    myName = 'chase'
    while cont:
        bytedata = s.recv(4048)
        #data = str(bytedata)
        data = bytedata.decode('utf-8')
        if not data:
            cont = False
            s.close()
            quit()
        else:
            #---------------------------------------------------------
            #This is where you need to adjust the program
            #---------------------------------------------------------
            print(data)
            instructions = data.split('&')
            if len(instructions) == 2:
                if instructions[0] == myName:
                    robot.drive_off_charger_contacts().wait_for_completed()
                    robot.drive_straight(
                        cozmo.util.distance_mm(200),
                        cozmo.util.speed_mmps(50)).wait_for_completed()
                    robot.say_text("please Place Go Pro on my lift",
                                   play_excited_animation=False,
                                   use_cozmo_voice=False,
                                   duration_scalar=0.6,
                                   voice_pitch=0.3,
                                   in_parallel=False,
                                   num_retries=0).wait_for_completed()
                    time.sleep(4)
                    #split second part of instructions into separate command list (commands for photo/video/TL)
                    commands = instructions[1].split("%")
                    for command in commands:
                        #split separate commands into individual pieces
                        message = command.split(";")

                        #PHOTO SECTION
                        #step 1 = "photo"
                        #step 2 = "front, back, left or right"
                        #return to original position in front of charger
                        if message[0] == "photo":
                            robot.say_text("photo program initiated",
                                           play_excited_animation=False,
                                           use_cozmo_voice=False,
                                           duration_scalar=0.6,
                                           voice_pitch=0.3,
                                           in_parallel=False,
                                           num_retries=0).wait_for_completed()
                            driveStraight(robot)
                            if message[1] == "front":
                                takePhoto(robot)
                                backUp(robot)
                            if message[1] == "back":
                                turnAround(robot)
                                takePhoto(robot)
                                turnAround(robot)
                                backUp(robot)
                            if message[1] == "left":
                                robot.turn_in_place(
                                    degrees(90)).wait_for_completed()
                                driveStraight(robot)
                                takePhoto(robot)
                                backUp(robot)
                                robot.turn_in_place(
                                    degrees(-90)).wait_for_completed()
                                backUp(robot)
                            if message[1] == "right":
                                robot.turn_in_place(
                                    degrees(-90)).wait_for_completed()
                                driveStraight(robot)
                                takePhoto(robot)
                                backUp(robot)
                                robot.turn_in_place(
                                    degrees(90)).wait_for_completed()
                                backUp(robot)

                        # VIDEO SECTION
                        # step 1 = "video"
                        # step 2 = "stationary or pan"
                        # step 3 = "front, back or 360"
                        # return to original position in front of charger
                        if message[0] == "video":
                            robot.say_text("video program initiated",
                                           play_excited_animation=False,
                                           use_cozmo_voice=False,
                                           duration_scalar=0.6,
                                           voice_pitch=0.3,
                                           in_parallel=False,
                                           num_retries=0).wait_for_completed()
                            driveStraight(robot)
                            if message[1] == "stationary":
                                startVideo(robot)
                                time.sleep(videoTime)
                                stopVideo(robot)
                                backUp(robot)
                            if message[1] == "pan":
                                if message[2] == "front":
                                    robot.turn_in_place(
                                        degrees(90)).wait_for_completed()
                                    startVideo(robot)
                                    robot.turn_in_place(
                                        degrees(-180), None, 0, None,
                                        degrees(3)).wait_for_completed()
                                    stopVideo(robot)
                                    robot.turn_in_place(
                                        degrees(90)).wait_for_completed()
                                    backUp(robot)
                                if message[2] == "back":
                                    robot.turn_in_place(
                                        degrees(-90)).wait_for_completed()
                                    startVideo(robot)
                                    robot.turn_in_place(
                                        degrees(-180), None, 0, None,
                                        degrees(3)).wait_for_completed()
                                    stopVideo(robot)
                                    robot.turn_in_place(
                                        degrees(-90)).wait_for_completed()
                                    backUp(robot)
                                if message[2] == "360":
                                    startVideo(robot)
                                    robot.turn_in_place(
                                        degrees(-360), None, 0, None,
                                        degrees(3)).wait_for_completed()
                                    stopVideo(robot)
                                    backUp(robot)

                        #TIME LAPSE SECTION
                        # step 1 = "timelapse"
                        # step 2 = "front, back, left or right"
                        # return to original position in front of charger
                        if message[0] == "timelapse":
                            robot.say_text("time lapse program initiated",
                                           play_excited_animation=False,
                                           use_cozmo_voice=False,
                                           duration_scalar=0.6,
                                           voice_pitch=0.3,
                                           in_parallel=False,
                                           num_retries=0).wait_for_completed()
                            driveStraight(robot)
                            if message[1] == "front":
                                takeTimeLapse(robot)
                                backUp(robot)
                            if message[1] == "back":
                                turnAround(robot)
                                takeTimeLapse(robot)
                                turnAround(robot)
                                backUp(robot)
                            if message[1] == "left":
                                robot.turn_in_place(
                                    degrees(90)).wait_for_completed()
                                driveStraight(robot)
                                takeTimeLapse(robot)
                                backUp(robot)
                                robot.turn_in_place(
                                    degrees(-90)).wait_for_completed()
                                backUp(robot)
                            if message[1] == "right":
                                robot.turn_in_place(
                                    degrees(-90)).wait_for_completed()
                                driveStraight(robot)
                                takeTimeLapse(robot)
                                backUp(robot)
                                robot.turn_in_place(
                                    degrees(90)).wait_for_completed()
                                backUp(robot)

                    #AFTER ALL COMMANDS
                    robot.say_text("Please take Go Pro off my lift",
                                   play_excited_animation=False,
                                   use_cozmo_voice=False,
                                   duration_scalar=0.6,
                                   voice_pitch=0.3,
                                   in_parallel=False,
                                   num_retries=0).wait_for_completed()
                    time.sleep(4)
                    returnToCharger(robot)
Example #9
0
def cozmo_program(robot: cozmo.robot.Robot):
    # create an origin point where Cozmo's charger is. When he picks up objects he will return here.
    # If the robot was on the charger, drive them forward and clear of the charger
    if robot.is_on_charger:
        robot.drive_off_charger_contacts().wait_for_completed()
        robot.drive_straight(distance_mm(100), speed_mmps(50)).wait_for_completed()
        robot.move_lift(-3)
        robot.turn_in_place(degrees(180)).wait_for_completed()
        robot.set_head_angle(degrees(0)).wait_for_completed()
        time.sleep(0.5)

    # try to find the charger
    charger = None

    if robot.world.charger:
        if robot.world.charger.pose.is_comparable(robot.pose):
            # Cozmo knows where the charger is
            charger = robot.world.charger
        else:
            pass

    if not charger:
        # Tell Cozmo to look around for the charger
        look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
        try:
            charger = robot.world.wait_for_observed_charger(timeout=30)
        except asyncio.TimeoutError:
            print("Didn't see the charger")
        finally:
            look_around.stop()

    origin = charger
    robot.go_to_object(origin, 70)

    # on boot up show loading screen

    # locate all cubes
    look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)

    look_around.stop()

    # define light colours
    red_light = cozmo.lights.Light(cozmo.lights.Color(rgb=(255, 0, 0)))
    blue_light = cozmo.lights.Light(cozmo.lights.Color(rgb=(0, 0, 255)))
    yellow__light = cozmo.lights.Light(cozmo.lights.Color(rgb=(255, 255, 0)))

    # tag each cube found as a different colour
    red_cube = robot.world.get_light_cube(LightCube1Id)
    blue_cube = robot.world.get_light_cube(LightCube2Id)
    yellow_cube = robot.world.get_light_cube(LightCube3Id)

    red_cube.set_lights(red_light)
    blue_cube.set_lights(blue_light)
    yellow_cube.set_lights(yellow__light)

    # Pass found objects to GUI for selection

    robot.say_text("Ready when you are").wait_for_completed()

    # user selects which cube they want
    robot.say_text("When you are sure that's the one you want. Press the tick, if you want to select another, "
                   "just press on another object").wait_for_completed()

    # Wait for conformation
    robot.say_text("OK, I'll be right back.").wait_for_completed()

    # cozmo goes and gets cube
    action = robot.go_to_object(red_cube, distance_mm(70.0))
    action.wait_for_completed()
    action = robot.dock_with_cube(red_cube, approach_angle=cozmo.util.degrees(0), num_retries=2)
    action.wait_for_completed()
    action = robot.pickup_object(red_cube, num_retries=3)
    action.wait_for_completed()
    robot.say_text("Got it").wait_for_completed()

    # Cozmo returns cube to user
    action = robot.go_to_object(origin, 70)
    action.wait_for_completed()
    robot.say_text("Is this one the right one?").wait_for_completed()

    # Object is confirmed

    robot.say_text("Yay")

    # get dat fist bump
    robot.say_text("Do you want me to fetch anything else")

    # user says no

    # cozmo returns to base

    # wait for five minutes of inactivity

    robot.say_text("I'm going to have a nap now, let me know if you need anything?")
Example #10
0
def mainLoop(robot: cozmo.robot.Robot):
    threadFace = threading.Thread(target=face_follower.follow_faces,
                                  args=(robot, ))
    threadFace.start()

    while True:
        print('Expression:' + face_follower.notifyExpression())

        # In a loop, we grab the user input
        print("Listening...")
        humanString = (voiceParse.parseVoice()).lower()
        ListOfCommand = [str(s) for s in (humanString.lower()).split()]

        # Check it for a quit condition.
        if {'shut', 'down', 'cozmo'} <= set(ListOfCommand) or {
                'cosmo', 'shut', 'down'
        } <= set(ListOfCommand):
            # If we quit, we log the quit and leave the program.
            robot.say_text("Ok, shut down",
                           in_parallel=True).wait_for_completed()
            docking_cozmo(robot)
            ListOfCommand.clear()
            addEntry(log, "Conversation ended.")
            ListOfCommand.clear()
            sys.exit()

        if robot.battery_voltage <= 2.0:
            print('Running out of battery')
            robot.say_text("Running out of battery",
                           in_parallel=True).wait_for_completed()
            docking_cozmo(robot)

        if {'go', 'out', 'charger'} <= set(ListOfCommand):
            robot.drive_off_charger_contacts().wait_for_completed()
            robot.drive_straight(distance_mm(150),
                                 speed_mmps(60)).wait_for_completed()
            ListOfCommand.clear()

        if 'open reddit' in humanString:
            reg_ex = re.search('open reddit(.*)', humanString.lower())
            url = 'https://www.reddit.com/'
            addEntry(log, "Human says: " + humanString)
            print("Human says: " + humanString)
            if reg_ex:
                subreddit = reg_ex.group(1)
                url = url + 'r/' + subreddit
            webbrowser.open(url)
            addEntry(log, "Cozmo says: " + humanString)
            print("Cozmo says: " + "Done")
            robot.say_text("Done", in_parallel=True).wait_for_completed()
            continue

        if {'go', 'to', 'charger'} <= set(ListOfCommand):
            docking_cozmo(robot)
            ListOfCommand.clear()
        if 'open google' in humanString:
            reg_ex = re.search('open google(.*)', humanString.lower())
            url = 'https://www.google.com/'
            if reg_ex:
                subreddit = reg_ex.group(1)
                url = url + 'search?q=' + subreddit
            webbrowser.open(url)
            addEntry(log, "Human says: " + humanString)
            print("Human says: " + humanString)
            addEntry(log, "Cozmo says: " + humanString)
            print("Cozmo says: " + "Done")
            robot.say_text("Done", in_parallel=True).wait_for_completed()
            continue

        if 'open my favorite song' in humanString:
            robot.say_text("What song?", in_parallel=True).wait_for_completed()
            humanString1 = (voiceParse.parseVoice()).lower()
            print("Human says: " + humanString1)
            reg_ex = re.search('(.+)', humanString1)

            if reg_ex:
                SongName = reg_ex.group(1)
                #you can add any song you want in the ListofSongs, by adding key word with its watch?v=?????????
                json_file = open('texttest.json')
                json_str = json_file.read()
                dictOfSong = ast.literal_eval(json_str)
                """ListofSongs = {"part of your world": "watch?v=gtpLsPPtC88", "full nocturne": 'watch?v=liTSRH4fix4',
                               'eyes on fire': 'watch?v=LAxCqlU-OAo', 'nocturne in f minor': 'watch?v=E3qHO9aOQYM',
                               'moonlight sonata': 'watch?v=4Tr0otuiQuU', 'clair de lune': 'watch?v=ea2WoUtbzuw',
                               'hello': 'watch?v=YQHsXMglC9A', 'skyfall': 'watch?v=DeumyOzKqgI'}"""

                subUrl = 'https://www.youtube.com/search?q=' + SongName
                has_Song = False
                for x in range(len(dictOfSong['song'])):
                    if (dictOfSong['song'][x]['name']).lower() == SongName:
                        webbrowser.open(dictOfSong['song'][x]['url'])
                        has_Song = True
                        break
                if has_Song == False:
                    webbrowser.open(subUrl)
                    continue
                continue
            elif type(SongName) == type(None):
                robot.say_text("No command found",
                               in_parallel=True).wait_for_completed()
                continue
            robot.say_text("Done", in_parallel=True).wait_for_completed()
            addEntry(log, "Cozmo says: " + "Done")
            print("Cozmo says: " + "Done")
            continue

        if 'open website' in humanString:
            robot.say_text("What do you want me to open",
                           in_parallel=True).wait_for_completed()
            humanString1 = (voiceParse.parseVoice()).lower()
            print("Human says: " + humanString1)
            reg_ex = re.search('(.+)', humanString1)
            if reg_ex:
                domain = reg_ex.group(1)
                url = 'https://www.' + domain + ".com"
                ListofDictionaries = {
                    "google": "search?q=",
                    "youtube": 'search?q=',
                    "reddit": "r/",
                    'amazon': 's?url=search-alias%3Daps&field-keywords='
                }
                if domain not in str(ListofDictionaries):
                    webbrowser.open(url)
                    continue
                robot.say_text("What are you looking for in " + domain,
                               in_parallel=True).wait_for_completed()
                addEntry(
                    log,
                    "Cozmo says: " + "What are you looking for in " + domain)
                print("Cozmo says: " + "What are you looking for in " + domain)
                humanString2 = (voiceParse.parseVoice()).lower()
                addEntry(log, "Human says: " + humanString2)
                print("Human says: " + humanString2)
                if "nothing" in humanString2:
                    webbrowser.open(url)
                else:
                    newurl = url + "/" + ListofDictionaries.get(
                        domain) + humanString2
                    webbrowser.open(newurl)
            else:
                pass
            robot.say_text("Done", in_parallel=True).wait_for_completed()
            addEntry(log, "Cozmo says: " + "Done")
            print("Cozmo says: " + "Done")
            continue

        if ({"cosmo", "email"} <= set(ListOfCommand)) or ({"cozmo", "email"} <=
                                                          set(ListOfCommand)):
            ListOfCommand.clear()
            robot.say_text("Who is the recipient?",
                           in_parallel=True).wait_for_completed()
            addEntry(log, "Cozmo says: " + "Who is the recipient?")
            print("Cozmo says: " + "Who is the recipient?")
            recipient = (voiceParse.parseVoice()).lower()
            print(recipient)
            addEntry(log, "Human says: " + recipient)
            print("Human says: " + recipient)
            #you can add any email in the line below
            """ListofEmails = {"bright":"*****@*****.**","boss":"*****@*****.**",
                            "tim":"*****@*****.**","lucky":"*****@*****.**"}"""

            json_file1 = open('emailtext.json')
            json_str1 = json_file1.read()
            dictOfEmail = ast.literal_eval(json_str1)

            has_Email = False
            for x in range(len(dictOfEmail['email'])):
                print((dictOfEmail['email'][x]['name']).lower())
                if (dictOfEmail['email'][x]['name']).lower() == recipient:
                    robot.say_text("What should I say?",
                                   in_parallel=True).wait_for_completed()
                    addEntry(log, "Cozmo says: " + "What should I say?")
                    print("Cozmo says: " + "What should I say?")
                    content = (voiceParse.parseVoice()).lower()
                    addEntry(log, "Human says: " + content)
                    print("Human says: " + content)

                    # init gmail SMTP
                    ListOfSmtp = {
                        'gmail': [{
                            'name': 'smtp.gmail.com',
                            'key': '587'
                        }],
                        'outlook': [{
                            'name': 'smtp-mail.outlook.com',
                            'key': '587'
                        }],
                        'hotmail': [{
                            'name': 'smtp.live.com',
                            'key': '25'
                        }]
                    }
                    checkSmtp = dictOfEmail['email'][0]['url'].split(".")
                    b = str(checkSmtp[0]).split("@")
                    c = b[1].split(".")
                    d = c[0]
                    #check email whether our email is outlook or gmail
                    if d in ListOfSmtp:
                        mail = smtplib.SMTP(ListOfSmtp[d][0]['name'],
                                            ListOfSmtp[d][0]['key'])
                        # smtp-mail.outlook.com

                        # identify to server
                        mail.ehlo()

                        # encrypt session
                        mail.starttls()

                        # In this line, we open text file from gui
                        json_file = open('useradding.json')
                        json_str = json_file.read()
                        dictOfUser = ast.literal_eval(json_str)

                        # In this line, put your email and password
                        mail.login(dictOfUser['email'][0]['name'],
                                   dictOfUser['email'][0]['password'])

                        # send to the recipient
                        mail.sendmail('recipient',
                                      dictOfEmail['email'][x]['url'],
                                      content + "\n" + "sent via Cozmo")

                        # end mail connection
                        mail.close()

                        robot.say_text("Sent",
                                       in_parallel=True).wait_for_completed()
                        addEntry(log, "Cozmo says: " + "Sent")
                        print("Cozmo says: " + "Sent")
                        has_Email = True
                        break

                    else:
                        robot.say_text(
                            "I can\'t send because I don't know the SMTP name",
                            in_parallel=True).wait_for_completed()
                        addEntry(
                            log, "Cozmo says: " +
                            "I can\'t send because I don't know the SMTP name")
                        print(
                            "Cozmo says: " +
                            "I can\'t send because I don't know the SMTP name")
                        return mainLoop()

            if has_Email == False:
                robot.say_text("I don\'t know him",
                               in_parallel=True).wait_for_completed()
                addEntry(log, "Cozmo says: " + "I don\'t know him")
                print("Cozmo says: " + "I don\'t know him")
                continue

        if 'weather forecast in' in humanString:
            addEntry(log, "Human says: " + humanString)
            print("Human says: " + humanString)
            reg_ex = re.search('weather forecast in (.*)', humanString)
            if reg_ex:
                city = reg_ex.group(1)
                weather = Weather()
                location = weather.lookup_by_location(city)
                forecasts = location.forecast
                for i in range(0, 3):
                    TempetureForecast = (
                        'On %s will it %s. The maximum temperture will be %.1f degrees Celcius.'
                        'The lowest temperature will be %.1f degrees Celcius.'
                        % (forecasts[i].date, forecasts[i].text,
                           int(forecasts[i].high), int(forecasts[i].low)))
                robot.say_text(TempetureForecast,
                               use_cozmo_voice=True,
                               duration_scalar=1,
                               in_parallel=True).wait_for_completed()
                addEntry(log, "Cozmo says: " + TempetureForecast)
                print("Cozmo says: " + TempetureForecast)
                continue

        if ({"cosmo", "joke"} <= set(ListOfCommand)) or ({"cozmo", "joke"} <=
                                                         set(ListOfCommand)):
            ListOfCommand.clear()
            res = requests.get('https://icanhazdadjoke.com/',
                               headers={"Accept": "application/json"})
            if res.status_code == requests.codes.ok:
                robot.say_text(str(res.json()['joke']),
                               in_parallel=True,
                               duration_scalar=1.2).wait_for_completed()
                functionsCozmo.motion_step(robot)
                print("Cozmo says: " + str(res.json()['joke']))
                addEntry(log, "Cozmo says: " + str(res.json()['joke']))

            else:
                robot.say_text(str(res.json()['oops!I ran out of jokes']),
                               in_parallel=True).wait_for_completed()

                print("Cozmo says: " + 'oops!I ran out of jokes')
                addEntry(log, "Cozmo says: " + 'oops!I ran out of jokes')
            continue

        #Action Commands

        if ({"sing", "song", "cosmo", "stupid"} <= set(ListOfCommand)) or (
            {"sing", "song", "cozmo", "stupid"} <= set(ListOfCommand)):
            addEntry(log, "Human says: " + humanString)
            print("Human says: " + humanString)
            ListOfCommand.clear()
            functionsCozmo.cozmo_singing(robot)
            robot.say_text("Do you like my song?",
                           play_excited_animation=True,
                           in_parallel=True).wait_for_completed()
            print("Cozmo says: " + "Do you like my song?")
            addEntry(log, "Cozmo says: " + "Do you like my song?")
            continue

        if ({"random", "cosmo", 'emotion'} <= set(ListOfCommand)) or (
            {"random", "cozmo", 'emotion'} <= set(ListOfCommand)):
            ListOfCommand.clear()
            functionsCozmo.motion_step(robot)
            continue

        # Else, we log what the human said.
        addEntry(log, "Human says: " + humanString)
        print("Human says: " + humanString)

        # Grab the response from CleverBot
        cozmoString = cleverbot.say(humanString)

        # Print the response to the screen and add it to the log
        print("Cozmo says: " + cozmoString)
        addEntry(log, "Cozmo says: " + cozmoString)

        # Then we make Cozmo say it.
        robot.say_text(cozmoString, in_parallel=True).wait_for_completed()
        ListOfCommand.clear()
def cozmo_program(robot: cozmo.robot.Robot):
    # create an origin point where Cozmo's charger is. When he picks up objects he will return here.
    # If the robot was on the charger, drive them forward and clear of the charger
    if robot.is_on_charger:
        robot.drive_off_charger_contacts().wait_for_completed()
        robot.drive_straight(distance_mm(100), speed_mmps(50)).wait_for_completed()
        robot.move_lift(-3)
        robot.turn_in_place(degrees(180)).wait_for_completed()
        robot.set_head_angle(degrees(0)).wait_for_completed()
        time.sleep(0.5)

    # try to find the charger
    charger = None

    if robot.world.charger:
        if robot.world.charger.pose.is_comparable(robot.pose):
            # Cozmo knows where the charger is
            charger = robot.world.charger
        else:
            pass

    if not charger:
        # Tell Cozmo to look around for the charger
        look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
        try:
            charger = robot.world.wait_for_observed_charger(timeout=30)
        except asyncio.TimeoutError:
            print("Didn't see the charger")
        finally:
            look_around.stop()



    # on boot up show loading screen


    # define light colours
    red_light = cozmo.lights.Light(cozmo.lights.Color(rgb=(255, 0, 0)))
    blue_light = cozmo.lights.Light(cozmo.lights.Color(rgb=(0, 0, 255)))
    yellow__light = cozmo.lights.Light(cozmo.lights.Color(rgb=(255, 255, 0)))

    # tag each cube found as a different colour
    red_cube = robot.world.get_light_cube(LightCube1Id)
    blue_cube = robot.world.get_light_cube(LightCube2Id)
    yellow_cube = robot.world.get_light_cube(LightCube3Id)

    red_cube.set_lights(red_light)
    blue_cube.set_lights(blue_light)
    yellow_cube.set_lights(yellow__light)

    # Pass found objects to GUI for selection

    robot.say_text("Ready").wait_for_completed()
    
    # user selects which cube they want
    cube_selected_input = input("Which cube do you want. Options: red_cube, yellow_cube, blue_cube: ")
    cube_selected = cube_selected_input
    print(cube_selected)
    robot.say_text("press").wait_for_completed()

    # Wait for conformation
    confirmation = input("Are you sure Y/N: ")
    if confirmation == "Y":
        robot.say_text("OK.").wait_for_completed()
        cube_wanted = cube_selected
    else:
        print("Fine")
        cube_wanted = ""

    # Move lift down and tilt the head up
    robot.move_lift(-3)
    robot.set_head_angle(degrees(0)).wait_for_completed()

    # look around and try to find a cube
    look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
    look_around.start()
    cubes = robot.world.wait_until_observe_num_objects(num=3, object_type=cozmo.objects.LightCube, timeout=60)
        
    look_around.stop()
    
    # cozmo goes and gets cube
    robot.pickup_object(yellow_cube, num_retries=3).wait_for_completed
    
    robot.say_text("Got it").wait_for_completed()


    # Cozmo returns cube to user
    robot.go_to_object(charger,  distance_mm(100)).wait_for_completed()
    robot.say_text("Is this one the right one?").wait_for_completed()

    # Object is confirmed
    confirmation1 = input("Is this the right one? Y/N: ")
    if confirmation1 == "Y":
        robot.say_text("Yay")
    else:
        robot.say_text("Well you're getting it anyway.")

    action = robot.place_object_on_ground_here(cube_wanted)
    action.wait_for_completed()

    # get dat fist bump
    robot.say_text("Do you want me to fetch anything else")

    # user says no

    # cozmo returns to base

    # wait for five minutes of inactivity

    robot.say_text("I'm going to have a nap now, let me know if you need anything?")
Example #12
0
def cozmo_program(robot: cozmo.robot.Robot):
    robot.drive_off_charger_contacts().wait_for_completed()
    robot.drive_straight(cozmo.util.distance_mm(200),
                         cozmo.util.speed_mmps(50)).wait_for_completed()
    robot.say_text("please Place Go Pro on my lift",
                   play_excited_animation=False,
                   use_cozmo_voice=False,
                   duration_scalar=0.6,
                   voice_pitch=0.3,
                   in_parallel=False,
                   num_retries=0).wait_for_completed()
    time.sleep(4)

    #parse input for separate actions
    commandList = commands.split('%')
    for command in commandList:
        instructions = command.split(';')

        #PHOTO SECTION
        #step 1 = "photo"
        #step 2 = "front, back, left or right"
        #return to original position in front of charger
        if instructions[0] == "photo":
            robot.say_text("photo program initiated",
                           play_excited_animation=False,
                           use_cozmo_voice=False,
                           duration_scalar=0.6,
                           voice_pitch=0.3,
                           in_parallel=False,
                           num_retries=0).wait_for_completed()
            driveStraight(robot)
            if instructions[1] == "front":
                takePhoto(robot)
                backUp(robot)
            if instructions[1] == "back":
                turnAround(robot)
                takePhoto(robot)
                turnAround(robot)
                backUp(robot)
            if instructions[1] == "left":
                robot.turn_in_place(degrees(90)).wait_for_completed()
                driveStraight(robot)
                takePhoto(robot)
                backUp(robot)
                robot.turn_in_place(degrees(-90)).wait_for_completed()
                backUp(robot)
            if instructions[1] == "right":
                robot.turn_in_place(degrees(-90)).wait_for_completed()
                driveStraight(robot)
                takePhoto(robot)
                backUp(robot)
                robot.turn_in_place(degrees(90)).wait_for_completed()
                backUp(robot)

        # VIDEO SECTION
        # step 1 = "video"
        # step 2 = "stationary or pan"
        # step 3 = "front, back or 360"
        # return to original position in front of charger
        if instructions[0] == "video":
            robot.say_text("video program initiated",
                           play_excited_animation=False,
                           use_cozmo_voice=False,
                           duration_scalar=0.6,
                           voice_pitch=0.3,
                           in_parallel=False,
                           num_retries=0).wait_for_completed()
            driveStraight(robot)
            if instructions[1] == "stationary":
                startVideo(robot)
                time.sleep(videoTime)
                stopVideo(robot)
                backUp(robot)
            if instructions[1] == "pan":
                if instructions[2] == "front":
                    robot.turn_in_place(degrees(90)).wait_for_completed()
                    startVideo(robot)
                    robot.turn_in_place(degrees(-180), None, 0, None,
                                        degrees(3)).wait_for_completed()
                    stopVideo(robot)
                    robot.turn_in_place(degrees(90)).wait_for_completed()
                    backUp(robot)
                if instructions[2] == "back":
                    robot.turn_in_place(degrees(-90)).wait_for_completed()
                    startVideo(robot)
                    robot.turn_in_place(degrees(-180), None, 0, None,
                                        degrees(3)).wait_for_completed()
                    stopVideo(robot)
                    robot.turn_in_place(degrees(-90)).wait_for_completed()
                    backUp(robot)
                if instructions[2] == "360":
                    startVideo(robot)
                    robot.turn_in_place(degrees(-360), None, 0, None,
                                        degrees(3)).wait_for_completed()
                    stopVideo(robot)
                    backUp(robot)

        #TIME LAPSE SECTION
        # step 1 = "timelapse"
        # step 2 = "front, back, left or right"
        # return to original position in front of charger
        if instructions[0] == "timelapse":
            robot.say_text("time lapse program initiated",
                           play_excited_animation=False,
                           use_cozmo_voice=False,
                           duration_scalar=0.6,
                           voice_pitch=0.3,
                           in_parallel=False,
                           num_retries=0).wait_for_completed()
            driveStraight(robot)
            if instructions[1] == "front":
                takeTimeLapse(robot)
                backUp(robot)
            if instructions[1] == "back":
                turnAround(robot)
                takeTimeLapse(robot)
                turnAround(robot)
                backUp(robot)
            if instructions[1] == "left":
                robot.turn_in_place(degrees(90)).wait_for_completed()
                driveStraight(robot)
                takeTimeLapse(robot)
                backUp(robot)
                robot.turn_in_place(degrees(-90)).wait_for_completed()
                backUp(robot)
            if instructions[1] == "right":
                robot.turn_in_place(degrees(-90)).wait_for_completed()
                driveStraight(robot)
                takeTimeLapse(robot)
                backUp(robot)
                robot.turn_in_place(degrees(90)).wait_for_completed()
                backUp(robot)

    #AFTER ALL COMMANDS
    robot.say_text("Please take Go Pro off my lift",
                   play_excited_animation=False,
                   use_cozmo_voice=False,
                   duration_scalar=0.6,
                   voice_pitch=0.3,
                   in_parallel=False,
                   num_retries=0).wait_for_completed()
    time.sleep(4)
    returnToCharger(robot)
Example #13
0
def cozmo_off(robot: cozmo.robot.Robot, parallel=False, num_retries=1):
    robot.drive_off_charger_contacts(parallel, num_retries)