class Turntable:
    def __init__(self, port_motor_move, port_motor_turn):
        # Motor for moving turntable forwards and backwards
        self.motor_move = Motor(port_motor_move)
        self.motor_move.speed_sp = 400
        self.motor_move.stop_action = 'brake'
        self.motor_move_positions = (0, -740, -890, -1030, -1175, -1380)

        # Motor for rotating turntable
        self.motor_turn = Motor(port_motor_turn)
        self.motor_turn.speed_sp = 400
        self.motor_turn.stop_action = 'brake'
        self.motor_turn_positions = (0, -345, 345)

    @try_except
    def move_to_abs_pos(self, pos):
        ''' Move the turntable to given absolute position [0,..,5].'''
        self.motor_move.run_to_abs_pos(
            position_sp=self.motor_move_positions[pos])

    @try_except
    def move_to_rel_pos(self, rel_pos):
        ''' Move the turntable over a given distance.'''
        self.motor_move.run_to_rel_pos(position_sp=rel_pos)  # rel_pos=150
        wait_while_motors_running(self.motor_move)

    @try_except
    def turn_to_abs_pos(self, pos):
        ''' Turn the turntable to a given absolute position [0,..,2].'''
        self.motor_turn.run_to_abs_pos(
            position_sp=self.motor_turn_positions[pos])

    @try_except
    def goto_start_pos(self):
        ''' Move and turn the turntable to its start position.'''
        self.move_to_abs_pos(0)
        self.turn_to_abs_pos(0)
Example #2
0
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, Motor
import argparse
import logging

# command line args
parser = argparse.ArgumentParser(description="Used to adjust the position of a motor in an already assembled robot")
parser.add_argument("motor", type=str, help="A, B, C or D")
parser.add_argument("degrees", type=int)
parser.add_argument("-s", "--speed", type=int, default=50)
args = parser.parse_args()

# logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)5s: %(message)s")
log = logging.getLogger(__name__)

if args.motor == "A":
    motor = Motor(OUTPUT_A)
elif args.motor == "B":
    motor = Motor(OUTPUT_B)
elif args.motor == "C":
    motor = Motor(OUTPUT_C)
elif args.motor == "D":
    motor = Motor(OUTPUT_D)
else:
    raise Exception("%s is invalid, options are A, B, C, D")

if args.degrees:
    log.info("Motor %s, current position %d, move to position %d, max speed %d" %
             (args.motor, motor.position, args.degrees, motor.max_speed))
    motor.run_to_rel_pos(speed_sp=args.speed, position_sp=args.degrees, stop_action='hold')
Example #3
0
class MindstormsGadget(AlexaGadget):
    """
    A Mindstorms gadget that performs movement based on voice commands.
    Two types of commands are supported, directional movement and preset.
    """
    def __init__(self):
        """
        Performs Alexa Gadget initialization routines and ev3dev resource allocation.
        """
        super().__init__()

        # Ev3dev initialization
        self.leds = Leds()
        self.sound = Sound()
        self.motor = Motor(OUTPUT_A)

    def on_connected(self, device_addr):
        """
        Gadget connected to the paired Echo device.
        :param device_addr: the address of the device we connected to
        """
        self.leds.set_color("LEFT", "GREEN")
        self.leds.set_color("RIGHT", "GREEN")
        print("{} connected to Echo device".format(self.friendly_name))

    def on_disconnected(self, device_addr):
        """
        Gadget disconnected from the paired Echo device.
        :param device_addr: the address of the device we disconnected from
        """
        self.leds.set_color("LEFT", "BLACK")
        self.leds.set_color("RIGHT", "BLACK")
        print("{} disconnected from Echo device".format(self.friendly_name))

    def on_custom_mindstorms_gadget_control(self, directive):
        """
        Handles the Custom.Mindstorms.Gadget control directive.
        :param directive: the custom directive with the matching namespace and name
        """
        try:
            payload = json.loads(directive.payload.decode("utf-8"))
            print("Control payload: {}".format(payload))
            control_type = payload["type"]
            if control_type == "move":

                # Expected params: [direction, duration, speed]
                self._move(payload["direction"], int(payload["duration"]),
                           int(payload["speed"]))

            if control_type == "command":
                # Expected params: [command]
                self._activate(payload["command"])

        except KeyError:
            print("Missing expected parameters: {}".format(directive))

    def _move(self, direction, duration: int, speed: int, is_blocking=False):
        """
        Handles move commands from the directive.
        Right and left movement can under or over turn depending on the surface type.
        :param direction: the move direction
        :param duration: the duration in rotations
        :param speed: the speed percentage as an integer
        :param is_blocking: if set, motor run until duration expired before accepting another command
        """
        print("Move command: ({}, {}, {}, {})".format(direction, speed,
                                                      duration, is_blocking))
        position = duration * 360
        if direction in Direction.FORWARD.value:
            self.motor.run_to_rel_pos(position_sp=(position),
                                      speed_sp=(speed),
                                      stop_action="hold")

        if direction in Direction.BACKWARD.value:
            self.motor.run_to_rel_pos(position_sp=(-position),
                                      speed_sp=(speed),
                                      stop_action="hold")

        if direction in Direction.STOP.value:
            self.motor.stop(stop_action="hold")

    def _activate(self, command, speed=500):
        """
        Handles preset commands.
        :param command: the preset command
        :param speed: the speed if applicable
        """
        print("Activate command: ({}, {})".format(command, speed))
        if command in Command.RAISE_BLIND.value:
            self.motor.run_to_rel_pos(position_sp=5000,
                                      speed_sp=500,
                                      stop_action="hold")
            print('running raise blinds')

        if command in Command.LOWER_BLIND.value:
            self.motor.run_to_rel_pos(position_sp=-5000,
                                      speed_sp=500,
                                      stop_action="hold")
            print('running lower blinds')