Beispiel #1
0
 def set_left_led(self, color: Color):
     """Changes the color of the LED on RVR's left side (which is the side with RVR's battery bay door). Set this
     using RGB (red, green, blue) values on a scale of 0 - 255. For example, the green color is expressed as
     ``set_left_led(Color(0, 255, 34))``."""
     if isinstance(self.__toy, RVR):
         self.__leds['left'] = bound_color(color, self.__leds['left'])
         ToyUtil.set_battery_side_led(self.__toy, **self.__leds['left']._asdict())
Beispiel #2
0
 def set_right_headlight_led(self, color: Color):
     """Changes the color of the front right headlight LED on RVR. Set this using RGB (red, green, blue) values on a
     scale of 0 - 255. For example, the blue color is expressed as
     ``set_right_headlight_led(0, 28, 255)``."""
     if isinstance(self.__toy, RVR):
         self.__leds['right_headlight'] = bound_color(color, self.__leds['right_headlight'])
         ToyUtil.set_right_front_led(self.__toy, **self.__leds['right_headlight']._asdict())
Beispiel #3
0
    def __init__(self, toy: Toy):
        self.__toy = toy
        self.__heading = 0
        self.__speed = 0
        self.__stabilization = True
        self.__raw_motor = rawMotor(0, 0)
        self.__leds = LedManager(toy.__class__)

        self.__sensor_data: Dict[str, Union[float, Dict[str, float]]] = {
            'distance': 0.,
            'color_index': -1
        }
        self.__sensor_name_mapping = {}
        self.__last_location = (0., 0.)
        self.__last_non_fall = time.time()
        self.__falling_v = 1.
        self.__last_message = None
        self.__should_land = self.__free_falling = False
        ToyUtil.add_listeners(toy, self)

        self.__listeners = defaultdict(set)

        self.__stopped = threading.Event()
        self.__stopped.set()
        self.__updating = threading.Lock()
        self.__thread = None
Beispiel #4
0
 def set_right_led(self, color: Color):
     """Changes the color of the LED on RVR's right side (which is the side with RVR's power button). Set this using
     RGB (red, green, blue) values on a scale of 0 - 255. For example, the red color is expressed as
     ``set_right_led(Color(255, 18, 0))``."""
     if isinstance(self.__toy, RVR):
         self.__leds['right'] = bound_color(color, self.__leds['right'])
         ToyUtil.set_power_side_led(self.__toy, **self.__leds['right']._asdict())
Beispiel #5
0
 def play_sound(self, sound: IntEnum):
     """Unique Star Wars Droid Sounds are available for BB-8, BB-9E and R2-D2. For example, to play the R2-D2 Burnout
     sound use ``play_sound(R2D2.Audio.R2_BURNOUT)``."""
     if hasattr(self.__toy, 'Audio'):
         if sound not in self.__toy.Audio:
             raise ValueError(f'Sound {sound} cannot be played by this toy')
         ToyUtil.play_sound(self.__toy, sound, False)
Beispiel #6
0
 def set_holo_projector_led(self, brightness: int):
     """Changes the brightness of the Holographic Projector white LED, from 0 to 255. For example, set it to full
     brightness using ``set_holo_projector_led(255)``."""
     if isinstance(self.__toy, (R2D2, R2Q5)):
         self.__leds['holo_projector'] = bound_value(0, brightness, 255)
         ToyUtil.set_holo_projector(self.__toy,
                                    self.__leds['holo_projector'])
Beispiel #7
0
 def set_main_led(self, color: Color):
     """Changes the color of the main LED light, or the full matrix on Sphero BOLT. Set this using RGB
     (red, green, blue) values on a scale of 0 - 255. For example, ``set_main_led(Color(r=90, g=255, b=90))``."""
     self.__leds['main'] = bound_color(color, self.__leds['main'])
     ToyUtil.set_main_led(self.__toy,
                          **self.__leds['main']._asdict(),
                          is_user_color=False)
Beispiel #8
0
 def __update_raw_motor(self):
     ToyUtil.set_raw_motor(
         self.__toy, RawMotorModes.REVERSE
         if self.__raw_motor.left < 0 else RawMotorModes.FORWARD,
         abs(self.__raw_motor.left), RawMotorModes.REVERSE
         if self.__raw_motor.right < 0 else RawMotorModes.FORWARD,
         abs(self.__raw_motor.right))
Beispiel #9
0
 def set_dome_leds(self, brightness: int):
     """Controls the brightness of the two single color LEDs (red and blue) in the dome, from 0 to 15. We don't use
     0-255 for this light because it has less granular control. For example, set them to full brightness using
     ``set_dome_leds(15)``."""
     if isinstance(self.__toy, BB9E):
         self.__leds['dome'] = bound_value(0, brightness, 15)
         ranged = self.__leds['dome'] * 255 // 15
         ToyUtil.set_head_led(self.__toy, ranged)
Beispiel #10
0
 def __exit__(self, *args):
     self.__stopped.set()
     self.__thread.join()
     try:
         ToyUtil.sleep(self.__toy)
     except:
         pass
     self.__toy.__exit__(*args)
Beispiel #11
0
 def start_ir_follow(self, near: int, far: int):
     """Sets the IR receivers to look for broadcasting BOLTs on the same channel pair, from 0 to 7. Upon receiving
     messages from a broadcasting BOLT, the follower will adjust its heading and speed to follow the broadcaster.
     When a follower loses sight of a broadcaster, the follower will spin in place to search for the broadcaster.
     You can't use a channel for more than one purpose at time, such as sending messages along with broadcasting,
     following, or evading. For example, use ``start_ir_follow(0, 1)`` to follow another BOLT that is broadcasting on
     channels 0 and 1."""
     ToyUtil.start_robot_to_robot_infrared_following(self.__toy, bound_value(0, far, 7), bound_value(0, near, 7))
Beispiel #12
0
 def set_waddle(self, waddle: bool):
     """Turns the waddle walk on using `set_waddle(True)`` and off using ``set_waddle(False)``."""
     if isinstance(self.__toy, (R2D2, R2Q5)):
         with self.__updating:
             self.__stop_all()
         ToyUtil.perform_leg_action(
             self.__toy,
             R2LegActions.WADDLE if waddle else R2LegActions.STOP)
Beispiel #13
0
 def listen_for_ir_message(self,
                           channels: Union[int, Iterable[int]],
                           duration: int = 0xFFFFFFFF):
     if isinstance(channels, int):
         channels = (channels, )
     if len(channels) > 0:
         ToyUtil.listen_for_robot_to_robot_infrared_message(
             self.__toy, map(lambda v: bound_value(0, v, 7), channels),
             bound_value(0, duration, 0xFFFFFFFF))
Beispiel #14
0
 def send_ir_message(self, channel: int, intensity: int):
     """Sends a message on a given IR channel, at a set intensity, from 1 to 64. Intensity is proportional to
     proximity, where a 1 is the closest, and 64 is the farthest. For example, use ``send_ir_message(4, 5)`` to send
     message 4 at intensity 5. You will need to use ``onIRMessage4(channel)`` event for on a corresponding robot to
     receive the message. Also see the ``getLastIRMessage()`` sensor to keep track of the last message your robot
     received. You can't use a channel for more than one purpose at time, such as sending messages along with
     broadcasting, following, or evading."""
     ToyUtil.send_robot_to_robot_infrared_message(
         self.__toy, bound_value(0, channel, 7), bound_value(1, intensity, 64))
Beispiel #15
0
 def start_ir_evade(self, near: int, far: int):
     """Sets the IR receivers to look for broadcasting BOLTs on the same channel pair, from 0 to 7. Upon receiving
     messages from a broadcasting BOLT, the evader will adjust its heading to roll away from the broadcaster.
     When an evader loses sight of a broadcaster, the evader will spin in place to search for the broadcaster.
     The evader may stop if it is in the far range for a period of time so it does not roll too far away from the
     broadcaster. You can't use a channel for more than one purpose at time, such as sending messages along with
     broadcasting, following, or evading. For example, use ``start_ir_evade(0, 1)`` to evade another BOLT that is
     broadcasting on channels 0 and 1."""
     ToyUtil.start_robot_to_robot_infrared_evading(self.__toy, bound_value(0, far, 7), bound_value(0, near, 7))
Beispiel #16
0
 def start_ir_broadcast(self, near: int, far: int):
     """Sets the IR emitters to broadcast on two specified channels, from 0 to 7, so other BOLTs can follow or evade.
     The broadcaster uses two channels because the first channel emits near IR pulses (< 1 meter), and the second
     channel emits far IR pulses (1 to 3 meters) so the following and evading BOLTs can detect these messages on
     their IR receivers with a sense of relative proximity to the broadcaster. You can't use a channel for more than
     one purpose at time, such as sending messages along with broadcasting, following, or evading. For example,
     use ``start_ir_broadcast(0, 1)`` to broadcast on channels 0 and 1, so that other BOLTs following or evading on
     0 and 1 will recognize this robot."""
     ToyUtil.start_robot_to_robot_infrared_broadcasting(self.__toy, bound_value(0, far, 7), bound_value(0, near, 7))
Beispiel #17
0
 def __start_capturing_sensor_data(self):
     if isinstance(self.__toy, RVR):
         sensors = ['accelerometer', 'gyroscope', 'imu', 'locator', 'velocity', 'ambient_light', 'color_detection']
         self.__sensor_name_mapping['imu'] = 'attitude'
     elif isinstance(self.__toy, BOLT):
         sensors = ['accelerometer', 'gyroscope', 'attitude', 'locator', 'velocity', 'ambient_light']
     else:
         sensors = ['attitude', 'accelerometer', 'gyroscope', 'locator', 'velocity']
     ToyUtil.enable_sensors(self.__toy, sensors)
Beispiel #18
0
 def play_animation(self, animation: IntEnum):
     """Plays iconic `Star Wars Droid animations <https://edu.sphero.com/remixes/1195472/>`_ unique to BB-8, BB-9E,
     R2-D2 and R2-Q5 that combine movement, lights and sound. All animation enums can be accessed under the droid
     class, such as :class:`R2D2.Animations.CHARGER_1`."""
     if hasattr(self.__toy, 'Animations'):
         if animation not in self.__toy.Animations:
             raise ValueError(f'Animation {animation} cannot be played by this toy')
         with self.__updating:
             self.__stop_all()
         ToyUtil.play_animation(self.__toy, animation, True)
Beispiel #19
0
 def set_stance(self, stance: Stance):
     """Changes the stance between bipod and tripod. Set to bipod using ``set_stance(Stance.Bipod)`` and
     to tripod using ``set_stance(Stance.Tripod)``. Tripod is required for rolling."""
     if isinstance(self.__toy, (R2D2, R2Q5)):
         if stance == Stance.Bipod:
             ToyUtil.perform_leg_action(self.__toy, R2LegActions.TWO_LEGS)
         elif stance == Stance.Tripod:
             ToyUtil.perform_leg_action(self.__toy, R2LegActions.THREE_LEGS)
         else:
             raise ValueError(f'Stance {stance} is not supported')
Beispiel #20
0
    def set_front_led(self, color: Color):
        """For Sphero RVR: Changes the color of RVR's front two LED headlights together.

        For Sphero BOLT, R2D2, R2Q5: Changes the color of the front LED light.

        Set this using RGB (red, green, blue) values on a scale of 0 - 255. For example, the magenta color is expressed
        as ``set_front_color(Color(239, 0, 255))``."""
        if isinstance(self.__toy, (R2D2, R2Q5, BOLT, RVR)):
            self.__leds['front'] = bound_color(color, self.__leds['front'])
            ToyUtil.set_front_led(self.__toy, **self.__leds['front']._asdict())
Beispiel #21
0
 def __enter__(self):
     self.__stopped.clear()
     self.__thread = threading.Thread(target=self.__background)
     self.__toy.__enter__()
     self.__thread.start()
     try:
         self.__toy.wake()
         ToyUtil.set_robot_state_on_start(self.__toy)
         self.__start_capturing_sensor_data()
     except:
         self.__exit__(None, None, None)
         raise
     return self
Beispiel #22
0
    def set_stabilization(self, stabilize: bool):
        """Turns the stabilization system on and ``set_stabilization(false)`` turns it off.
        Stabilization is normally on to keep the robot upright using the Inertial Measurement Unit (IMU),
        a combination of readings from the Accelerometer (directional acceleration), Gyroscope (rotation speed),
        and Encoders (location and distance). When ``set_stabilization(false)`` and you power the motors,
        the robot will not balance, resulting in possible unstable behaviors like wobbly driving,
        or even jumping if you set the power very high. Some use cases to turn it off are:

        1. Jumping: Set Motor Power to max values and the robot will jump off the ground!
        2. Gyro: Programs like the Spinning Top where you want to to isolate the Gyroscope readings rather than having
           the robot auto balance inside the shell.

        When stabilization is off you can't use :func:`set_speed` to set a speed because it requires the control system
        to be on to function. However, you can control the motors using Motor Power with :func:`raw_motor` when
        the control system is off."""
        self.__stabilization = stabilize
        if isinstance(self.__toy, (Sphero, Mini, Ollie, BB8, BB9E, BOLT)):
            ToyUtil.set_stabilization(self.__toy, stabilize)
Beispiel #23
0
 def raw_motor(self, left: int, right: int, duration: float):
     """Controls the electrical power sent to the left and right motors independently, on a scale from -255 to 255
     where positive is forward, negative is backward, and 0 is stopped. If you set both motors to full power
     the robot will jump because stabilization (use of the IMU to keep the robot upright) is disabled when using
     this command. This is different from :func:`set_speed` because Raw Motor sends an "Electromotive force"
     to the motors, whereas Set Speed is a target speed measured by the encoders. For example, to set the raw motor
     to full power for 4s, making the robot jump off the ground, use ``raw_motor(255, 255, 4)``."""
     stabilize = self.__stabilization
     if stabilize:
         self.set_stabilization(False)
     self.__raw_motor.left = bound_value(-255, left, 255)
     self.__raw_motor.right = bound_value(-255, right, 255)
     self.__update_raw_motor()
     if duration is not None:
         time.sleep(duration)
         if stabilize:
             self.set_stabilization(True)
         self.__raw_motor.left = self.__raw_motor.right = 0
         ToyUtil.set_raw_motor(self.__toy, RawMotorModes.OFF, 0, RawMotorModes.OFF, 0)
Beispiel #24
0
    def set_back_led(self, color: Union[Color, int]):
        """For older Sphero:
        Sets the brightness of the back aiming LED, aka the "Tail Light." This LED is limited to blue only, with a
        brightness scale from 0 to 255. For example, use ``set_back_led(255)`` to set the back LED to full brightness.
        Use :func:`time.sleep` to set it on for a duration. For example, to create a dim and a bright blink
        sequence use::

            set_back_led(0)  # Dim
            delay(0.33)
            set_back_led(255)  # Bright
            delay(0.33)

        For Sphero BOLT, R2D2, R2Q5:
        Changes the color of the back LED light. Set this using RGB (red, green, blue) values on a scale of 0 - 255.

        For Sphero RVR:
        Changes the color of the left and right breaklight LED light. Set this using RGB (red, green, blue) values
        on a scale of 0 - 255."""
        if isinstance(color, int):
            self.__leds['back'] = Color(0, 0, bound_value(0, color, 255))
            ToyUtil.set_back_led_brightness(self.__toy, self.__leds['back'].b)
        elif isinstance(self.__toy, (R2D2, R2Q5, BOLT, RVR)):
            self.__leds['back'] = bound_color(color, self.__leds['back'])
            ToyUtil.set_back_led(self.__toy, **self.__leds['back']._asdict())
Beispiel #25
0
 def stop_ir_evade(self):
     """Stops the evading behavior."""
     ToyUtil.stop_robot_to_robot_infrared_evading(self.__toy)
Beispiel #26
0
 def stop_ir_follow(self):
     """Stops the following behavior."""
     ToyUtil.stop_robot_to_robot_infrared_following(self.__toy)
Beispiel #27
0
 def stop_ir_broadcast(self):
     """Stops the broadcasting behavior."""
     ToyUtil.stop_robot_to_robot_infrared_broadcasting(self.__toy)
Beispiel #28
0
 def set_logic_display_leds(self, brightness: int):
     """Changes the brightness of the Logic Display LEDs, from 0 to 255. For example, set it to full brightness
     using ``set_logic_display_leds(255)``."""
     if isinstance(self.__toy, (R2D2, R2Q5)):
         self.__leds['logic_display'] = bound_value(0, brightness, 255)
         ToyUtil.set_logic_display(self.__toy, self.__leds['logic_display'])
Beispiel #29
0
 def reset_aim(self):
     """Resets the heading calibration (aim) angle to use the current direction of the robot as 0°."""
     ToyUtil.reset_heading(self.__toy)
Beispiel #30
0
 def set_dome_position(self, angle: float):
     """Rotates the dome on its axis, from -160° to 180°. For example, set to 45° using ``set_dome_position(45).``"""
     if isinstance(self.__toy, (R2D2, R2Q5)):
         ToyUtil.set_head_position(self.__toy, bound_value(-160., angle, 180.))